File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1010: download - view: text, annotated - select for diffs
Sat Aug 8 00:36:10 2009 UTC (14 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Course Requests within LON-CAPA.

- Start on documentation for domainprefs.pm

- Domain setting for course requests for each instituional affiliate type (and
also default, and _LC_adv) for each course type (official, unofficial and
community) can now be one of:
  0, approve, validate, autolimit=N (where N is blank, or a positive integer.

- Custom course request settings set for an individual user in the user's domain
can also be one of: approve, validate, autolimit=N for the three course types

- A user's environment setting for course requests in external domains (modifiable
by a DC in a domain other than the user's home domain) can also be one of the
three.

0: course requests not allowed for the specific affiliation/course type.
approve - requests queued and must be approved by DC in course's domain before
processing.

validate: institutional validation (e.g., check requestor is instructor
of record) before course will be created.

autolimit: requests will be processed autoatically up to a limit of N requests
for the course type for that requestor.
- If N is undefined, there is no limit to the number of course requests which a
course owner may submit for automatic processing.

lonnet.pm
- auto_courserequest_checks() placeholder.

Work in progress.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1010 2009/08/08 00:36: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);
   80: 
   81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   82:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   83:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   84:     %courseownerbuf, %coursetypebuf,$locknum);
   85: 
   86: use IO::Socket;
   87: use GDBM_File;
   88: use HTML::LCParser;
   89: use Fcntl qw(:flock);
   90: use Storable qw(thaw nfreeze);
   91: use Time::HiRes qw( gettimeofday tv_interval );
   92: use Cache::Memcached;
   93: use Digest::MD5;
   94: use Math::Random;
   95: use LONCAPA qw(:DEFAULT :match);
   96: use LONCAPA::Configuration;
   97: 
   98: my $readit;
   99: my $max_connection_retries = 10;     # Or some such value.
  100: 
  101: my $upload_photo_form = 0; #Variable to check  when user upload a photo 0=not 1=true
  102: 
  103: require Exporter;
  104: 
  105: our @ISA = qw (Exporter);
  106: our @EXPORT = qw(%env);
  107: 
  108: 
  109: # --------------------------------------------------------------------- Logging
  110: {
  111:     my $logid;
  112:     sub instructor_log {
  113: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  114:         if (($cnum eq '') || ($cdom eq '')) {
  115:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  116:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  117:         }
  118: 	$logid++;
  119:         my $now = time();
  120: 	my $id=$now.'00000'.$$.'00000'.$logid;
  121: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  122: 				    { $id => {
  123: 					'exe_uname' => $env{'user.name'},
  124: 					'exe_udom'  => $env{'user.domain'},
  125: 					'exe_time'  => $now,
  126: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  127: 					'delflag'   => $delflag,
  128: 					'logentry'  => $storehash,
  129: 					'uname'     => $uname,
  130: 					'udom'      => $udom,
  131: 				    }
  132: 				  },$cdom,$cnum);
  133:     }
  134: }
  135: 
  136: sub logtouch {
  137:     my $execdir=$perlvar{'lonDaemons'};
  138:     unless (-e "$execdir/logs/lonnet.log") {	
  139: 	open(my $fh,">>$execdir/logs/lonnet.log");
  140: 	close $fh;
  141:     }
  142:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  143:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  144: }
  145: 
  146: sub logthis {
  147:     my $message=shift;
  148:     my $execdir=$perlvar{'lonDaemons'};
  149:     my $now=time;
  150:     my $local=localtime($now);
  151:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  152: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  153: 	print $fh $logstring;
  154: 	close($fh);
  155:     }
  156:     return 1;
  157: }
  158: 
  159: sub logperm {
  160:     my $message=shift;
  161:     my $execdir=$perlvar{'lonDaemons'};
  162:     my $now=time;
  163:     my $local=localtime($now);
  164:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  165: 	print $fh "$now:$message:$local\n";
  166: 	close($fh);
  167:     }
  168:     return 1;
  169: }
  170: 
  171: sub create_connection {
  172:     my ($hostname,$lonid) = @_;
  173:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  174: 				     Type    => SOCK_STREAM,
  175: 				     Timeout => 10);
  176:     return 0 if (!$client);
  177:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  178:     my $result = <$client>;
  179:     chomp($result);
  180:     return 1 if ($result eq 'done');
  181:     return 0;
  182: }
  183: 
  184: sub get_server_timezone {
  185:     my ($cnum,$cdom) = @_;
  186:     my $home=&homeserver($cnum,$cdom);
  187:     if ($home ne 'no_host') {
  188:         my $cachetime = 24*3600;
  189:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  190:         if (defined($cached)) {
  191:             return $timezone;
  192:         } else {
  193:             my $timezone = &reply('servertimezone',$home);
  194:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  195:         }
  196:     }
  197: }
  198: 
  199: sub get_server_loncaparev {
  200:     my ($dom,$lonhost) = @_;
  201:     if (defined($lonhost)) {
  202:         if (!defined(&hostname($lonhost))) {
  203:             undef($lonhost);
  204:         }
  205:     }
  206:     if (!defined($lonhost)) {
  207:         if (defined(&domain($dom,'primary'))) {
  208:             $lonhost=&domain($dom,'primary');
  209:             if ($lonhost eq 'no_host') {
  210:                 undef($lonhost);
  211:             }
  212:         }
  213:     }
  214:     if (defined($lonhost)) {
  215:         my $cachetime = 24*3600;
  216:         my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  217:         if (defined($cached)) {
  218:             return $loncaparev;
  219:         } else {
  220:             my $loncaparev = &reply('serverloncaparev',$lonhost);
  221:             return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  222:         }
  223:     }
  224: }
  225: 
  226: # -------------------------------------------------- Non-critical communication
  227: sub subreply {
  228:     my ($cmd,$server)=@_;
  229:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  230:     #
  231:     #  With loncnew process trimming, there's a timing hole between lonc server
  232:     #  process exit and the master server picking up the listen on the AF_UNIX
  233:     #  socket.  In that time interval, a lock file will exist:
  234: 
  235:     my $lockfile=$peerfile.".lock";
  236:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  237: 	sleep(1);
  238:     }
  239:     # At this point, either a loncnew parent is listening or an old lonc
  240:     # or loncnew child is listening so we can connect or everything's dead.
  241:     #
  242:     #   We'll give the connection a few tries before abandoning it.  If
  243:     #   connection is not possible, we'll con_lost back to the client.
  244:     #   
  245:     my $client;
  246:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  247: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  248: 				      Type    => SOCK_STREAM,
  249: 				      Timeout => 10);
  250: 	if ($client) {
  251: 	    last;		# Connected!
  252: 	} else {
  253: 	    &create_connection(&hostname($server),$server);
  254: 	}
  255:         sleep(1);		# Try again later if failed connection.
  256:     }
  257:     my $answer;
  258:     if ($client) {
  259: 	print $client "sethost:$server:$cmd\n";
  260: 	$answer=<$client>;
  261: 	if (!$answer) { $answer="con_lost"; }
  262: 	chomp($answer);
  263:     } else {
  264: 	$answer = 'con_lost';	# Failed connection.
  265:     }
  266:     return $answer;
  267: }
  268: 
  269: sub reply {
  270:     my ($cmd,$server)=@_;
  271:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  272:     my $answer=subreply($cmd,$server);
  273:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  274:        &logthis("<font color=\"blue\">WARNING:".
  275:                 " $cmd to $server returned $answer</font>");
  276:     }
  277:     return $answer;
  278: }
  279: 
  280: # ----------------------------------------------------------- Send USR1 to lonc
  281: 
  282: sub reconlonc {
  283:     my ($lonid) = @_;
  284:     my $hostname = &hostname($lonid);
  285:     if ($lonid) {
  286: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  287: 	if ($hostname && -e $peerfile) {
  288: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  289: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  290: 					     Type    => SOCK_STREAM,
  291: 					     Timeout => 10);
  292: 	    if ($client) {
  293: 		print $client ("reset_retries\n");
  294: 		my $answer=<$client>;
  295: 		#reset just this one.
  296: 	    }
  297: 	}
  298: 	return;
  299:     }
  300: 
  301:     &logthis("Trying to reconnect lonc");
  302:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  303:     if (open(my $fh,"<$loncfile")) {
  304: 	my $loncpid=<$fh>;
  305:         chomp($loncpid);
  306:         if (kill 0 => $loncpid) {
  307: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  308:             kill USR1 => $loncpid;
  309:             sleep 1;
  310:          } else {
  311: 	    &logthis(
  312:                "<font color=\"blue\">WARNING:".
  313:                " lonc at pid $loncpid not responding, giving up</font>");
  314:         }
  315:     } else {
  316: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  317:     }
  318: }
  319: 
  320: # ------------------------------------------------------ Critical communication
  321: 
  322: sub critical {
  323:     my ($cmd,$server)=@_;
  324:     unless (&hostname($server)) {
  325:         &logthis("<font color=\"blue\">WARNING:".
  326:                " Critical message to unknown server ($server)</font>");
  327:         return 'no_such_host';
  328:     }
  329:     my $answer=reply($cmd,$server);
  330:     if ($answer eq 'con_lost') {
  331: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  332: 	my $answer=reply($cmd,$server);
  333:         if ($answer eq 'con_lost') {
  334:             my $now=time;
  335:             my $middlename=$cmd;
  336:             $middlename=substr($middlename,0,16);
  337:             $middlename=~s/\W//g;
  338:             my $dfilename=
  339:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  340:             $dumpcount++;
  341:             {
  342: 		my $dfh;
  343: 		if (open($dfh,">$dfilename")) {
  344: 		    print $dfh "$cmd\n"; 
  345: 		    close($dfh);
  346: 		}
  347:             }
  348:             sleep 2;
  349:             my $wcmd='';
  350:             {
  351: 		my $dfh;
  352: 		if (open($dfh,"<$dfilename")) {
  353: 		    $wcmd=<$dfh>; 
  354: 		    close($dfh);
  355: 		}
  356:             }
  357:             chomp($wcmd);
  358:             if ($wcmd eq $cmd) {
  359: 		&logthis("<font color=\"blue\">WARNING: ".
  360:                          "Connection buffer $dfilename: $cmd</font>");
  361:                 &logperm("D:$server:$cmd");
  362: 	        return 'con_delayed';
  363:             } else {
  364:                 &logthis("<font color=\"red\">CRITICAL:"
  365:                         ." Critical connection failed: $server $cmd</font>");
  366:                 &logperm("F:$server:$cmd");
  367:                 return 'con_failed';
  368:             }
  369:         }
  370:     }
  371:     return $answer;
  372: }
  373: 
  374: # ------------------------------------------- check if return value is an error
  375: 
  376: sub error {
  377:     my ($result) = @_;
  378:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  379: 	if ($2 == 2) { return undef; }
  380: 	return $1;
  381:     }
  382:     return undef;
  383: }
  384: 
  385: sub convert_and_load_session_env {
  386:     my ($lonidsdir,$handle)=@_;
  387:     my @profile;
  388:     {
  389: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  390: 	if (!$opened) {
  391: 	    return 0;
  392: 	}
  393: 	flock($idf,LOCK_SH);
  394: 	@profile=<$idf>;
  395: 	close($idf);
  396:     }
  397:     my %temp_env;
  398:     foreach my $line (@profile) {
  399: 	if ($line !~ m/=/) {
  400: 	    return 0;
  401: 	}
  402: 	chomp($line);
  403: 	my ($envname,$envvalue)=split(/=/,$line,2);
  404: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  405:     }
  406:     unlink("$lonidsdir/$handle.id");
  407:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  408: 	    0640)) {
  409: 	%disk_env = %temp_env;
  410: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  411: 	untie(%disk_env);
  412:     }
  413:     return 1;
  414: }
  415: 
  416: # ------------------------------------------- Transfer profile into environment
  417: my $env_loaded;
  418: sub transfer_profile_to_env {
  419:     my ($lonidsdir,$handle,$force_transfer) = @_;
  420:     if (!$force_transfer && $env_loaded) { return; } 
  421: 
  422:     if (!defined($lonidsdir)) {
  423: 	$lonidsdir = $perlvar{'lonIDsDir'};
  424:     }
  425:     if (!defined($handle)) {
  426:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  427:     }
  428: 
  429:     my $convert;
  430:     {
  431:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  432: 	if (!$opened) {
  433: 	    return;
  434: 	}
  435: 	flock($idf,LOCK_SH);
  436: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  437: 		&GDBM_READER(),0640)) {
  438: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  439: 	    untie(%disk_env);
  440: 	} else {
  441: 	    $convert = 1;
  442: 	}
  443:     }
  444:     if ($convert) {
  445: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  446: 	    &logthis("Failed to load session, or convert session.");
  447: 	}
  448:     }
  449: 
  450:     my %remove;
  451:     while ( my $envname = each(%env) ) {
  452:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  453:             if ($time < time-300) {
  454:                 $remove{$key}++;
  455:             }
  456:         }
  457:     }
  458: 
  459:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  460:     $env_loaded=1;
  461:     foreach my $expired_key (keys(%remove)) {
  462:         &delenv($expired_key);
  463:     }
  464: }
  465: 
  466: # ---------------------------------------------------- Check for valid session 
  467: sub check_for_valid_session {
  468:     my ($r) = @_;
  469:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  470:     my $lonid=$cookies{'lonID'};
  471:     return undef if (!$lonid);
  472: 
  473:     my $handle=&LONCAPA::clean_handle($lonid->value);
  474:     my $lonidsdir=$r->dir_config('lonIDsDir');
  475:     return undef if (!-e "$lonidsdir/$handle.id");
  476: 
  477:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  478:     return undef if (!$opened);
  479: 
  480:     flock($idf,LOCK_SH);
  481:     my %disk_env;
  482:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  483: 	    &GDBM_READER(),0640)) {
  484: 	return undef;	
  485:     }
  486: 
  487:     if (!defined($disk_env{'user.name'})
  488: 	|| !defined($disk_env{'user.domain'})) {
  489: 	return undef;
  490:     }
  491:     return $handle;
  492: }
  493: 
  494: sub timed_flock {
  495:     my ($file,$lock_type) = @_;
  496:     my $failed=0;
  497:     eval {
  498: 	local $SIG{__DIE__}='DEFAULT';
  499: 	local $SIG{ALRM}=sub {
  500: 	    $failed=1;
  501: 	    die("failed lock");
  502: 	};
  503: 	alarm(13);
  504: 	flock($file,$lock_type);
  505: 	alarm(0);
  506:     };
  507:     if ($failed) {
  508: 	return undef;
  509:     } else {
  510: 	return 1;
  511:     }
  512: }
  513: 
  514: # ---------------------------------------------------------- Append Environment
  515: 
  516: sub appenv {
  517:     my ($newenv,$roles) = @_;
  518:     if (ref($newenv) eq 'HASH') {
  519:         foreach my $key (keys(%{$newenv})) {
  520:             my $refused = 0;
  521: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  522:                 $refused = 1;
  523:                 if (ref($roles) eq 'ARRAY') {
  524:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  525:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  526:                         $refused = 0;
  527:                     }
  528:                 }
  529:             }
  530:             if ($refused) {
  531:                 &logthis("<font color=\"blue\">WARNING: ".
  532:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  533:                          .'</font>');
  534: 	        delete($newenv->{$key});
  535:             } else {
  536:                 $env{$key}=$newenv->{$key};
  537:             }
  538:         }
  539:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  540:         if ($opened
  541: 	    && &timed_flock($env_file,LOCK_EX)
  542: 	    &&
  543: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  544: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  545: 	    while (my ($key,$value) = each(%{$newenv})) {
  546: 	        $disk_env{$key} = $value;
  547: 	    }
  548: 	    untie(%disk_env);
  549:         }
  550:     }
  551:     return 'ok';
  552: }
  553: # ----------------------------------------------------- Delete from Environment
  554: 
  555: sub delenv {
  556:     my ($delthis,$regexp) = @_;
  557:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  558:         &logthis("<font color=\"blue\">WARNING: ".
  559:                 "Attempt to delete from environment ".$delthis);
  560:         return 'error';
  561:     }
  562:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  563:     if ($opened
  564: 	&& &timed_flock($env_file,LOCK_EX)
  565: 	&&
  566: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  567: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  568: 	foreach my $key (keys(%disk_env)) {
  569: 	    if ($regexp) {
  570:                 if ($key=~/^$delthis/) {
  571:                     delete($env{$key});
  572:                     delete($disk_env{$key});
  573:                 } 
  574:             } else {
  575:                 if ($key=~/^\Q$delthis\E/) {
  576: 		    delete($env{$key});
  577: 		    delete($disk_env{$key});
  578: 	        }
  579:             }
  580: 	}
  581: 	untie(%disk_env);
  582:     }
  583:     return 'ok';
  584: }
  585: 
  586: sub get_env_multiple {
  587:     my ($name) = @_;
  588:     my @values;
  589:     if (defined($env{$name})) {
  590:         # exists is it an array
  591:         if (ref($env{$name})) {
  592:             @values=@{ $env{$name} };
  593:         } else {
  594:             $values[0]=$env{$name};
  595:         }
  596:     }
  597:     return(@values);
  598: }
  599: 
  600: # ------------------------------------------------------------------- Locking
  601: 
  602: sub set_lock {
  603:     my ($text)=@_;
  604:     $locknum++;
  605:     my $id=$$.'-'.$locknum;
  606:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  607:              'session.lock.'.$id => $text});
  608:     return $id;
  609: }
  610: 
  611: sub get_locks {
  612:     my $num=0;
  613:     my %texts=();
  614:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  615:        if ($lock=~/\w/) {
  616:           $num++;
  617:           $texts{$lock}=$env{'session.lock.'.$lock};
  618:        }
  619:    }
  620:    return ($num,%texts);
  621: }
  622: 
  623: sub remove_lock {
  624:     my ($id)=@_;
  625:     my $newlocks='';
  626:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  627:        if (($lock=~/\w/) && ($lock ne $id)) {
  628:           $newlocks.=','.$lock;
  629:        }
  630:     }
  631:     &appenv({'session.locks' => $newlocks});
  632:     &delenv('session.lock.'.$id);
  633: }
  634: 
  635: sub remove_all_locks {
  636:     my $activelocks=$env{'session.locks'};
  637:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  638:        if ($lock=~/\w/) {
  639:           &remove_lock($lock);
  640:        }
  641:     }
  642: }
  643: 
  644: 
  645: # ------------------------------------------ Find out current server userload
  646: sub userload {
  647:     my $numusers=0;
  648:     {
  649: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  650: 	my $filename;
  651: 	my $curtime=time;
  652: 	while ($filename=readdir(LONIDS)) {
  653: 	    next if ($filename eq '.' || $filename eq '..');
  654: 	    next if ($filename =~ /publicuser_\d+\.id/);
  655: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  656: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  657: 	}
  658: 	closedir(LONIDS);
  659:     }
  660:     my $userloadpercent=0;
  661:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  662:     if ($maxuserload) {
  663: 	$userloadpercent=100*$numusers/$maxuserload;
  664:     }
  665:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  666:     return $userloadpercent;
  667: }
  668: 
  669: # ------------------------------------------ Fight off request when overloaded
  670: 
  671: sub overloaderror {
  672:     my ($r,$checkserver)=@_;
  673:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  674:     my $loadavg;
  675:     if ($checkserver eq $perlvar{'lonHostID'}) {
  676:        open(my $loadfile,'/proc/loadavg');
  677:        $loadavg=<$loadfile>;
  678:        $loadavg =~ s/\s.*//g;
  679:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  680:        close($loadfile);
  681:     } else {
  682:        $loadavg=&reply('load',$checkserver);
  683:     }
  684:     my $overload=$loadavg-100;
  685:     if ($overload>0) {
  686: 	$r->err_headers_out->{'Retry-After'}=$overload;
  687:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  688:         return 413;
  689:     }    
  690:     return '';
  691: }
  692: 
  693: # ------------------------------ Find server with least workload from spare.tab
  694: 
  695: sub spareserver {
  696:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  697:     my $spare_server;
  698:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  699:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  700:                                                      :  $userloadpercent;
  701:     
  702:     foreach my $try_server (@{ $spareid{'primary'} }) {
  703: 	($spare_server, $lowest_load) =
  704: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  705:     }
  706: 
  707:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  708: 
  709:     if (!$found_server) {
  710: 	foreach my $try_server (@{ $spareid{'default'} }) {
  711: 	    ($spare_server, $lowest_load) =
  712: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  713: 	}
  714:     }
  715: 
  716:     if (!$want_server_name) {
  717:         my $protocol = 'http';
  718:         if ($protocol{$spare_server} eq 'https') {
  719:             $protocol = $protocol{$spare_server};
  720:         }
  721:         if (defined($spare_server)) {
  722:             my $hostname = &hostname($spare_server);
  723:             if (defined($hostname)) {  
  724: 	        $spare_server = $protocol.'://'.$hostname;
  725:             }
  726:         }
  727:     }
  728:     return $spare_server;
  729: }
  730: 
  731: sub compare_server_load {
  732:     my ($try_server, $spare_server, $lowest_load) = @_;
  733: 
  734:     my $loadans     = &reply('load',    $try_server);
  735:     my $userloadans = &reply('userload',$try_server);
  736: 
  737:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  738: 	next; #didn't get a number from the server
  739:     }
  740: 
  741:     my $load;
  742:     if ($loadans =~ /\d/) {
  743: 	if ($userloadans =~ /\d/) {
  744: 	    #both are numbers, pick the bigger one
  745: 	    $load = ($loadans > $userloadans) ? $loadans 
  746: 		                              : $userloadans;
  747: 	} else {
  748: 	    $load = $loadans;
  749: 	}
  750:     } else {
  751: 	$load = $userloadans;
  752:     }
  753: 
  754:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  755: 	$spare_server = $try_server;
  756: 	$lowest_load  = $load;
  757:     }
  758:     return ($spare_server,$lowest_load);
  759: }
  760: 
  761: # --------------------------- ask offload servers if user already has a session
  762: sub find_existing_session {
  763:     my ($udom,$uname) = @_;
  764:     foreach my $try_server (@{ $spareid{'primary'} },
  765: 			    @{ $spareid{'default'} }) {
  766: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
  767:     }
  768:     return;
  769: }
  770: 
  771: # -------------------------------- ask if server already has a session for user
  772: sub has_user_session {
  773:     my ($lonid,$udom,$uname) = @_;
  774:     my $result = &reply(join(':','userhassession',
  775: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  776:     return 1 if ($result eq 'ok');
  777: 
  778:     return 0;
  779: }
  780: 
  781: # --------------------------------------------- Try to change a user's password
  782: 
  783: sub changepass {
  784:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  785:     $currentpass = &escape($currentpass);
  786:     $newpass     = &escape($newpass);
  787:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  788: 		       $server);
  789:     if (! $answer) {
  790: 	&logthis("No reply on password change request to $server ".
  791: 		 "by $uname in domain $udom.");
  792:     } elsif ($answer =~ "^ok") {
  793:         &logthis("$uname in $udom successfully changed their password ".
  794: 		 "on $server.");
  795:     } elsif ($answer =~ "^pwchange_failure") {
  796: 	&logthis("$uname in $udom was unable to change their password ".
  797: 		 "on $server.  The action was blocked by either lcpasswd ".
  798: 		 "or pwchange");
  799:     } elsif ($answer =~ "^non_authorized") {
  800:         &logthis("$uname in $udom did not get their password correct when ".
  801: 		 "attempting to change it on $server.");
  802:     } elsif ($answer =~ "^auth_mode_error") {
  803:         &logthis("$uname in $udom attempted to change their password despite ".
  804: 		 "not being locally or internally authenticated on $server.");
  805:     } elsif ($answer =~ "^unknown_user") {
  806:         &logthis("$uname in $udom attempted to change their password ".
  807: 		 "on $server but were unable to because $server is not ".
  808: 		 "their home server.");
  809:     } elsif ($answer =~ "^refused") {
  810: 	&logthis("$server refused to change $uname in $udom password because ".
  811: 		 "it was sent an unencrypted request to change the password.");
  812:     }
  813:     return $answer;
  814: }
  815: 
  816: # ----------------------- Try to determine user's current authentication scheme
  817: 
  818: sub queryauthenticate {
  819:     my ($uname,$udom)=@_;
  820:     my $uhome=&homeserver($uname,$udom);
  821:     if (!$uhome) {
  822: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  823: 	return 'no_host';
  824:     }
  825:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  826:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  827: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  828:     }
  829:     return $answer;
  830: }
  831: 
  832: # --------- Try to authenticate user from domain's lib servers (first this one)
  833: 
  834: sub authenticate {
  835:     my ($uname,$upass,$udom,$checkdefauth)=@_;
  836:     $upass=&escape($upass);
  837:     $uname= &LONCAPA::clean_username($uname);
  838:     my $uhome=&homeserver($uname,$udom,1);
  839:     my $newhome;
  840:     if ((!$uhome) || ($uhome eq 'no_host')) {
  841: # Maybe the machine was offline and only re-appeared again recently?
  842:         &reconlonc();
  843: # One more
  844: 	$uhome=&homeserver($uname,$udom,1);
  845:         if (($uhome eq 'no_host') && $checkdefauth) {
  846:             if (defined(&domain($udom,'primary'))) {
  847:                 $newhome=&domain($udom,'primary');
  848:             }
  849:             if ($newhome ne '') {
  850:                 $uhome = $newhome;
  851:             }
  852:         }
  853: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  854: 	    &logthis("User $uname at $udom is unknown in authenticate");
  855: 	    return 'no_host';
  856:         }
  857:     }
  858:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
  859:     if ($answer eq 'authorized') {
  860:         if ($newhome) {
  861:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
  862:             return 'no_account_on_host'; 
  863:         } else {
  864:             &logthis("User $uname at $udom authorized by $uhome");
  865:             return $uhome;
  866:         }
  867:     }
  868:     if ($answer eq 'non_authorized') {
  869: 	&logthis("User $uname at $udom rejected by $uhome");
  870: 	return 'no_host'; 
  871:     }
  872:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  873:     return 'no_host';
  874: }
  875: 
  876: # ---------------------- Find the homebase for a user from domain's lib servers
  877: 
  878: my %homecache;
  879: sub homeserver {
  880:     my ($uname,$udom,$ignoreBadCache)=@_;
  881:     my $index="$uname:$udom";
  882: 
  883:     if (exists($homecache{$index})) { return $homecache{$index}; }
  884: 
  885:     my %servers = &get_servers($udom,'library');
  886:     foreach my $tryserver (keys(%servers)) {
  887:         next if ($ignoreBadCache ne 'true' && 
  888: 		 exists($badServerCache{$tryserver}));
  889: 
  890: 	my $answer=reply("home:$udom:$uname",$tryserver);
  891: 	if ($answer eq 'found') {
  892: 	    delete($badServerCache{$tryserver}); 
  893: 	    return $homecache{$index}=$tryserver;
  894: 	} elsif ($answer eq 'no_host') {
  895: 	    $badServerCache{$tryserver}=1;
  896: 	}
  897:     }    
  898:     return 'no_host';
  899: }
  900: 
  901: # ------------------------------------- Find the usernames behind a list of IDs
  902: 
  903: sub idget {
  904:     my ($udom,@ids)=@_;
  905:     my %returnhash=();
  906:     
  907:     my %servers = &get_servers($udom,'library');
  908:     foreach my $tryserver (keys(%servers)) {
  909: 	my $idlist=join('&',@ids);
  910: 	$idlist=~tr/A-Z/a-z/; 
  911: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  912: 	my @answer=();
  913: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  914: 	    @answer=split(/\&/,$reply);
  915: 	}                    ;
  916: 	my $i;
  917: 	for ($i=0;$i<=$#ids;$i++) {
  918: 	    if ($answer[$i]) {
  919: 		$returnhash{$ids[$i]}=$answer[$i];
  920: 	    } 
  921: 	}
  922:     } 
  923:     return %returnhash;
  924: }
  925: 
  926: # ------------------------------------- Find the IDs behind a list of usernames
  927: 
  928: sub idrget {
  929:     my ($udom,@unames)=@_;
  930:     my %returnhash=();
  931:     foreach my $uname (@unames) {
  932:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  933:     }
  934:     return %returnhash;
  935: }
  936: 
  937: # ------------------------------- Store away a list of names and associated IDs
  938: 
  939: sub idput {
  940:     my ($udom,%ids)=@_;
  941:     my %servers=();
  942:     foreach my $uname (keys(%ids)) {
  943: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  944:         my $uhom=&homeserver($uname,$udom);
  945:         if ($uhom ne 'no_host') {
  946:             my $id=&escape($ids{$uname});
  947:             $id=~tr/A-Z/a-z/;
  948:             my $esc_unam=&escape($uname);
  949: 	    if ($servers{$uhom}) {
  950: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  951:             } else {
  952:                 $servers{$uhom}=$id.'='.$esc_unam;
  953:             }
  954:         }
  955:     }
  956:     foreach my $server (keys(%servers)) {
  957:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  958:     }
  959: }
  960: 
  961: # ------------------------------------------- get items from domain db files   
  962: 
  963: sub get_dom {
  964:     my ($namespace,$storearr,$udom,$uhome)=@_;
  965:     my $items='';
  966:     foreach my $item (@$storearr) {
  967:         $items.=&escape($item).'&';
  968:     }
  969:     $items=~s/\&$//;
  970:     if (!$udom) {
  971:         $udom=$env{'user.domain'};
  972:         if (defined(&domain($udom,'primary'))) {
  973:             $uhome=&domain($udom,'primary');
  974:         } else {
  975:             undef($uhome);
  976:         }
  977:     } else {
  978:         if (!$uhome) {
  979:             if (defined(&domain($udom,'primary'))) {
  980:                 $uhome=&domain($udom,'primary');
  981:             }
  982:         }
  983:     }
  984:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  985:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  986:         my %returnhash;
  987:         if ($rep eq '' || $rep =~ /^error: 2 /) {
  988:             return %returnhash;
  989:         }
  990:         my @pairs=split(/\&/,$rep);
  991:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  992:             return @pairs;
  993:         }
  994:         my $i=0;
  995:         foreach my $item (@$storearr) {
  996:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  997:             $i++;
  998:         }
  999:         return %returnhash;
 1000:     } else {
 1001:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1002:     }
 1003: }
 1004: 
 1005: # -------------------------------------------- put items in domain db files 
 1006: 
 1007: sub put_dom {
 1008:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1009:     if (!$udom) {
 1010:         $udom=$env{'user.domain'};
 1011:         if (defined(&domain($udom,'primary'))) {
 1012:             $uhome=&domain($udom,'primary');
 1013:         } else {
 1014:             undef($uhome);
 1015:         }
 1016:     } else {
 1017:         if (!$uhome) {
 1018:             if (defined(&domain($udom,'primary'))) {
 1019:                 $uhome=&domain($udom,'primary');
 1020:             }
 1021:         }
 1022:     } 
 1023:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1024:         my $items='';
 1025:         foreach my $item (keys(%$storehash)) {
 1026:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1027:         }
 1028:         $items=~s/\&$//;
 1029:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1030:     } else {
 1031:         &logthis("put_dom failed - no homeserver and/or domain");
 1032:     }
 1033: }
 1034: 
 1035: sub retrieve_inst_usertypes {
 1036:     my ($udom) = @_;
 1037:     my (%returnhash,@order);
 1038:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1039:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1040:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1041:         %returnhash = %{$domdefs{'inststatustypes'}};
 1042:         @order = @{$domdefs{'inststatusorder'}};
 1043:     } else {
 1044:         if (defined(&domain($udom,'primary'))) {
 1045:             my $uhome=&domain($udom,'primary');
 1046:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1047:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1048:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1049:                 return (\%returnhash,\@order);
 1050:             }
 1051:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1052:             my @pairs=split(/\&/,$hashitems);
 1053:             foreach my $item (@pairs) {
 1054:                 my ($key,$value)=split(/=/,$item,2);
 1055:                 $key = &unescape($key);
 1056:                 next if ($key =~ /^error: 2 /);
 1057:                 $returnhash{$key}=&thaw_unescape($value);
 1058:             }
 1059:             my @esc_order = split(/\&/,$orderitems);
 1060:             foreach my $item (@esc_order) {
 1061:                 push(@order,&unescape($item));
 1062:             }
 1063:         } else {
 1064:             &logthis("get_dom failed - no primary domain server for $udom");
 1065:         }
 1066:     }
 1067:     return (\%returnhash,\@order);
 1068: }
 1069: 
 1070: sub is_domainimage {
 1071:     my ($url) = @_;
 1072:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1073:         if (&domain($1) ne '') {
 1074:             return '1';
 1075:         }
 1076:     }
 1077:     return;
 1078: }
 1079: 
 1080: sub inst_directory_query {
 1081:     my ($srch) = @_;
 1082:     my $udom = $srch->{'srchdomain'};
 1083:     my %results;
 1084:     my $homeserver = &domain($udom,'primary');
 1085:     my $outcome;
 1086:     if ($homeserver ne '') {
 1087: 	my $queryid=&reply("querysend:instdirsearch:".
 1088: 			   &escape($srch->{'srchby'}).':'.
 1089: 			   &escape($srch->{'srchterm'}).':'.
 1090: 			   &escape($srch->{'srchtype'}),$homeserver);
 1091: 	my $host=&hostname($homeserver);
 1092: 	if ($queryid !~/^\Q$host\E\_/) {
 1093: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1094: 	    return;
 1095: 	}
 1096: 	my $response = &get_query_reply($queryid);
 1097: 	my $maxtries = 5;
 1098: 	my $tries = 1;
 1099: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1100: 	    $response = &get_query_reply($queryid);
 1101: 	    $tries ++;
 1102: 	}
 1103: 
 1104:         if (!&error($response) && $response ne 'refused') {
 1105:             if ($response eq 'unavailable') {
 1106:                 $outcome = $response;
 1107:             } else {
 1108:                 $outcome = 'ok';
 1109:                 my @matches = split(/\n/,$response);
 1110:                 foreach my $match (@matches) {
 1111:                     my ($key,$value) = split(/=/,$match);
 1112:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1113:                 }
 1114:             }
 1115:         }
 1116:     }
 1117:     return ($outcome,%results);
 1118: }
 1119: 
 1120: sub usersearch {
 1121:     my ($srch) = @_;
 1122:     my $dom = $srch->{'srchdomain'};
 1123:     my %results;
 1124:     my %libserv = &all_library();
 1125:     my $query = 'usersearch';
 1126:     foreach my $tryserver (keys(%libserv)) {
 1127:         if (&host_domain($tryserver) eq $dom) {
 1128:             my $host=&hostname($tryserver);
 1129:             my $queryid=
 1130:                 &reply("querysend:".&escape($query).':'.
 1131:                        &escape($srch->{'srchby'}).':'.
 1132:                        &escape($srch->{'srchtype'}).':'.
 1133:                        &escape($srch->{'srchterm'}),$tryserver);
 1134:             if ($queryid !~/^\Q$host\E\_/) {
 1135:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1136:                 next;
 1137:             }
 1138:             my $reply = &get_query_reply($queryid);
 1139:             my $maxtries = 1;
 1140:             my $tries = 1;
 1141:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1142:                 $reply = &get_query_reply($queryid);
 1143:                 $tries ++;
 1144:             }
 1145:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1146:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1147:             } else {
 1148:                 my @matches;
 1149:                 if ($reply =~ /\n/) {
 1150:                     @matches = split(/\n/,$reply);
 1151:                 } else {
 1152:                     @matches = split(/\&/,$reply);
 1153:                 }
 1154:                 foreach my $match (@matches) {
 1155:                     my ($uname,$udom,%userhash);
 1156:                     foreach my $entry (split(/:/,$match)) {
 1157:                         my ($key,$value) =
 1158:                             map {&unescape($_);} split(/=/,$entry);
 1159:                         $userhash{$key} = $value;
 1160:                         if ($key eq 'username') {
 1161:                             $uname = $value;
 1162:                         } elsif ($key eq 'domain') {
 1163:                             $udom = $value;
 1164:                         }
 1165:                     }
 1166:                     $results{$uname.':'.$udom} = \%userhash;
 1167:                 }
 1168:             }
 1169:         }
 1170:     }
 1171:     return %results;
 1172: }
 1173: 
 1174: sub get_instuser {
 1175:     my ($udom,$uname,$id) = @_;
 1176:     my $homeserver = &domain($udom,'primary');
 1177:     my ($outcome,%results);
 1178:     if ($homeserver ne '') {
 1179:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1180:                            &escape($id).':'.&escape($udom),$homeserver);
 1181:         my $host=&hostname($homeserver);
 1182:         if ($queryid !~/^\Q$host\E\_/) {
 1183:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1184:             return;
 1185:         }
 1186:         my $response = &get_query_reply($queryid);
 1187:         my $maxtries = 5;
 1188:         my $tries = 1;
 1189:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1190:             $response = &get_query_reply($queryid);
 1191:             $tries ++;
 1192:         }
 1193:         if (!&error($response) && $response ne 'refused') {
 1194:             if ($response eq 'unavailable') {
 1195:                 $outcome = $response;
 1196:             } else {
 1197:                 $outcome = 'ok';
 1198:                 my @matches = split(/\n/,$response);
 1199:                 foreach my $match (@matches) {
 1200:                     my ($key,$value) = split(/=/,$match);
 1201:                     $results{&unescape($key)} = &thaw_unescape($value);
 1202:                 }
 1203:             }
 1204:         }
 1205:     }
 1206:     my %userinfo;
 1207:     if (ref($results{$uname}) eq 'HASH') {
 1208:         %userinfo = %{$results{$uname}};
 1209:     } 
 1210:     return ($outcome,%userinfo);
 1211: }
 1212: 
 1213: sub inst_rulecheck {
 1214:     my ($udom,$uname,$id,$item,$rules) = @_;
 1215:     my %returnhash;
 1216:     if ($udom ne '') {
 1217:         if (ref($rules) eq 'ARRAY') {
 1218:             @{$rules} = map {&escape($_);} (@{$rules});
 1219:             my $rulestr = join(':',@{$rules});
 1220:             my $homeserver=&domain($udom,'primary');
 1221:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1222:                 my $response;
 1223:                 if ($item eq 'username') {                
 1224:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1225:                                               ':'.&escape($uname).':'.$rulestr,
 1226:                                               $homeserver));
 1227:                 } elsif ($item eq 'id') {
 1228:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1229:                                               ':'.&escape($id).':'.$rulestr,
 1230:                                               $homeserver));
 1231:                 } elsif ($item eq 'selfcreate') {
 1232:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1233:                                                &escape($udom).':'.&escape($uname).
 1234:                                               ':'.$rulestr,$homeserver));
 1235:                 }
 1236:                 if ($response ne 'refused') {
 1237:                     my @pairs=split(/\&/,$response);
 1238:                     foreach my $item (@pairs) {
 1239:                         my ($key,$value)=split(/=/,$item,2);
 1240:                         $key = &unescape($key);
 1241:                         next if ($key =~ /^error: 2 /);
 1242:                         $returnhash{$key}=&thaw_unescape($value);
 1243:                     }
 1244:                 }
 1245:             }
 1246:         }
 1247:     }
 1248:     return %returnhash;
 1249: }
 1250: 
 1251: sub inst_userrules {
 1252:     my ($udom,$check) = @_;
 1253:     my (%ruleshash,@ruleorder);
 1254:     if ($udom ne '') {
 1255:         my $homeserver=&domain($udom,'primary');
 1256:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1257:             my $response;
 1258:             if ($check eq 'id') {
 1259:                 $response=&reply('instidrules:'.&escape($udom),
 1260:                                  $homeserver);
 1261:             } elsif ($check eq 'email') {
 1262:                 $response=&reply('instemailrules:'.&escape($udom),
 1263:                                  $homeserver);
 1264:             } else {
 1265:                 $response=&reply('instuserrules:'.&escape($udom),
 1266:                                  $homeserver);
 1267:             }
 1268:             if (($response ne 'refused') && ($response ne 'error') && 
 1269:                 ($response ne 'unknown_cmd') && 
 1270:                 ($response ne 'no_such_host')) {
 1271:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1272:                 my @pairs=split(/\&/,$hashitems);
 1273:                 foreach my $item (@pairs) {
 1274:                     my ($key,$value)=split(/=/,$item,2);
 1275:                     $key = &unescape($key);
 1276:                     next if ($key =~ /^error: 2 /);
 1277:                     $ruleshash{$key}=&thaw_unescape($value);
 1278:                 }
 1279:                 my @esc_order = split(/\&/,$orderitems);
 1280:                 foreach my $item (@esc_order) {
 1281:                     push(@ruleorder,&unescape($item));
 1282:                 }
 1283:             }
 1284:         }
 1285:     }
 1286:     return (\%ruleshash,\@ruleorder);
 1287: }
 1288: 
 1289: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1290: 
 1291: sub get_domain_defaults {
 1292:     my ($domain) = @_;
 1293:     my $cachetime = 60*60*24;
 1294:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1295:     if (defined($cached)) {
 1296:         if (ref($result) eq 'HASH') {
 1297:             return %{$result};
 1298:         }
 1299:     }
 1300:     my %domdefaults;
 1301:     my %domconfig =
 1302:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1303:                                   'requestcourses','inststatus'],$domain);
 1304:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1305:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1306:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1307:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1308:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1309:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1310:     } else {
 1311:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1312:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1313:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1314:     }
 1315:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1316:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1317:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1318:         } else {
 1319:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1320:         } 
 1321:         my @usertools = ('aboutme','blog','portfolio');
 1322:         foreach my $item (@usertools) {
 1323:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1324:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1325:             }
 1326:         }
 1327:     }
 1328:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1329:         foreach my $item ('official','unofficial','community') {
 1330:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1331:         }
 1332:     }
 1333:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 1334:         foreach my $item ('inststatustypes','inststatusorder') {
 1335:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 1336:         }
 1337:     }
 1338:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1339:                                   $cachetime);
 1340:     return %domdefaults;
 1341: }
 1342: 
 1343: # --------------------------------------------------- Assign a key to a student
 1344: 
 1345: sub assign_access_key {
 1346: #
 1347: # a valid key looks like uname:udom#comments
 1348: # comments are being appended
 1349: #
 1350:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1351:     $kdom=
 1352:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1353:     $knum=
 1354:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1355:     $cdom=
 1356:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1357:     $cnum=
 1358:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1359:     $udom=$env{'user.name'} unless (defined($udom));
 1360:     $uname=$env{'user.domain'} unless (defined($uname));
 1361:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1362:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1363:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1364:                                                   # assigned to this person
 1365:                                                   # - this should not happen,
 1366:                                                   # unless something went wrong
 1367:                                                   # the first time around
 1368: # ready to assign
 1369:         $logentry=$1.'; '.$logentry;
 1370:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1371:                                                  $kdom,$knum) eq 'ok') {
 1372: # key now belongs to user
 1373: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1374:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1375:                 &appenv({'environment.'.$envkey => $ckey});
 1376:                 return 'ok';
 1377:             } else {
 1378:                 return 
 1379:   'error: Count not permanently assign key, will need to be re-entered later.';
 1380: 	    }
 1381:         } else {
 1382:             return 'error: Could not assign key, try again later.';
 1383:         }
 1384:     } elsif (!$existing{$ckey}) {
 1385: # the key does not exist
 1386: 	return 'error: The key does not exist';
 1387:     } else {
 1388: # the key is somebody else's
 1389: 	return 'error: The key is already in use';
 1390:     }
 1391: }
 1392: 
 1393: # ------------------------------------------ put an additional comment on a key
 1394: 
 1395: sub comment_access_key {
 1396: #
 1397: # a valid key looks like uname:udom#comments
 1398: # comments are being appended
 1399: #
 1400:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1401:     $cdom=
 1402:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1403:     $cnum=
 1404:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1405:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1406:     if ($existing{$ckey}) {
 1407:         $existing{$ckey}.='; '.$logentry;
 1408: # ready to assign
 1409:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1410:                                                  $cdom,$cnum) eq 'ok') {
 1411: 	    return 'ok';
 1412:         } else {
 1413: 	    return 'error: Count not store comment.';
 1414:         }
 1415:     } else {
 1416: # the key does not exist
 1417: 	return 'error: The key does not exist';
 1418:     }
 1419: }
 1420: 
 1421: # ------------------------------------------------------ Generate a set of keys
 1422: 
 1423: sub generate_access_keys {
 1424:     my ($number,$cdom,$cnum,$logentry)=@_;
 1425:     $cdom=
 1426:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1427:     $cnum=
 1428:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1429:     unless (&allowed('mky',$cdom)) { return 0; }
 1430:     unless (($cdom) && ($cnum)) { return 0; }
 1431:     if ($number>10000) { return 0; }
 1432:     sleep(2); # make sure don't get same seed twice
 1433:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1434:     my $total=0;
 1435:     for (my $i=1;$i<=$number;$i++) {
 1436:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1437:                   sprintf("%lx",int(100000*rand)).'-'.
 1438:                   sprintf("%lx",int(100000*rand));
 1439:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1440:        $newkey=~s/0/h/g; # and also 0 and O
 1441:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1442:        if ($existing{$newkey}) {
 1443:            $i--;
 1444:        } else {
 1445: 	  if (&put('accesskeys',
 1446:               { $newkey => '# generated '.localtime().
 1447:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1448:                            '; '.$logentry },
 1449: 		   $cdom,$cnum) eq 'ok') {
 1450:               $total++;
 1451: 	  }
 1452:        }
 1453:     }
 1454:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1455:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1456:     return $total;
 1457: }
 1458: 
 1459: # ------------------------------------------------------- Validate an accesskey
 1460: 
 1461: sub validate_access_key {
 1462:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1463:     $cdom=
 1464:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1465:     $cnum=
 1466:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1467:     $udom=$env{'user.domain'} unless (defined($udom));
 1468:     $uname=$env{'user.name'} unless (defined($uname));
 1469:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1470:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1471: }
 1472: 
 1473: # ------------------------------------- Find the section of student in a course
 1474: sub devalidate_getsection_cache {
 1475:     my ($udom,$unam,$courseid)=@_;
 1476:     my $hashid="$udom:$unam:$courseid";
 1477:     &devalidate_cache_new('getsection',$hashid);
 1478: }
 1479: 
 1480: sub courseid_to_courseurl {
 1481:     my ($courseid) = @_;
 1482:     #already url style courseid
 1483:     return $courseid if ($courseid =~ m{^/});
 1484: 
 1485:     if (exists($env{'course.'.$courseid.'.num'})) {
 1486: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1487: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1488: 	return "/$cdom/$cnum";
 1489:     }
 1490: 
 1491:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1492:     if (exists($courseinfo{'num'})) {
 1493: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1494:     }
 1495: 
 1496:     return undef;
 1497: }
 1498: 
 1499: sub getsection {
 1500:     my ($udom,$unam,$courseid)=@_;
 1501:     my $cachetime=1800;
 1502: 
 1503:     my $hashid="$udom:$unam:$courseid";
 1504:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1505:     if (defined($cached)) { return $result; }
 1506: 
 1507:     my %Pending; 
 1508:     my %Expired;
 1509:     #
 1510:     # Each role can either have not started yet (pending), be active, 
 1511:     #    or have expired.
 1512:     #
 1513:     # If there is an active role, we are done.
 1514:     #
 1515:     # If there is more than one role which has not started yet, 
 1516:     #     choose the one which will start sooner
 1517:     # If there is one role which has not started yet, return it.
 1518:     #
 1519:     # If there is more than one expired role, choose the one which ended last.
 1520:     # If there is a role which has expired, return it.
 1521:     #
 1522:     $courseid = &courseid_to_courseurl($courseid);
 1523:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1524:     foreach my $key (keys(%roleshash)) {
 1525:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1526:         my $section=$1;
 1527:         if ($key eq $courseid.'_st') { $section=''; }
 1528:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1529:         my $now=time;
 1530:         if (defined($end) && $end && ($now > $end)) {
 1531:             $Expired{$end}=$section;
 1532:             next;
 1533:         }
 1534:         if (defined($start) && $start && ($now < $start)) {
 1535:             $Pending{$start}=$section;
 1536:             next;
 1537:         }
 1538:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1539:     }
 1540:     #
 1541:     # Presumedly there will be few matching roles from the above
 1542:     # loop and the sorting time will be negligible.
 1543:     if (scalar(keys(%Pending))) {
 1544:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1545:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1546:     } 
 1547:     if (scalar(keys(%Expired))) {
 1548:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1549:         my $time = pop(@sorted);
 1550:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1551:     }
 1552:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1553: }
 1554: 
 1555: sub save_cache {
 1556:     &purge_remembered();
 1557:     #&Apache::loncommon::validate_page();
 1558:     undef(%env);
 1559:     undef($env_loaded);
 1560: }
 1561: 
 1562: my $to_remember=-1;
 1563: my %remembered;
 1564: my %accessed;
 1565: my $kicks=0;
 1566: my $hits=0;
 1567: sub make_key {
 1568:     my ($name,$id) = @_;
 1569:     if (length($id) > 65 
 1570: 	&& length(&escape($id)) > 200) {
 1571: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1572:     }
 1573:     return &escape($name.':'.$id);
 1574: }
 1575: 
 1576: sub devalidate_cache_new {
 1577:     my ($name,$id,$debug) = @_;
 1578:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1579:     $id=&make_key($name,$id);
 1580:     $memcache->delete($id);
 1581:     delete($remembered{$id});
 1582:     delete($accessed{$id});
 1583: }
 1584: 
 1585: sub is_cached_new {
 1586:     my ($name,$id,$debug) = @_;
 1587:     $id=&make_key($name,$id);
 1588:     if (exists($remembered{$id})) {
 1589: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1590: 	$accessed{$id}=[&gettimeofday()];
 1591: 	$hits++;
 1592: 	return ($remembered{$id},1);
 1593:     }
 1594:     my $value = $memcache->get($id);
 1595:     if (!(defined($value))) {
 1596: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1597: 	return (undef,undef);
 1598:     }
 1599:     if ($value eq '__undef__') {
 1600: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1601: 	$value=undef;
 1602:     }
 1603:     &make_room($id,$value,$debug);
 1604:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1605:     return ($value,1);
 1606: }
 1607: 
 1608: sub do_cache_new {
 1609:     my ($name,$id,$value,$time,$debug) = @_;
 1610:     $id=&make_key($name,$id);
 1611:     my $setvalue=$value;
 1612:     if (!defined($setvalue)) {
 1613: 	$setvalue='__undef__';
 1614:     }
 1615:     if (!defined($time) ) {
 1616: 	$time=600;
 1617:     }
 1618:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1619:     my $result = $memcache->set($id,$setvalue,$time);
 1620:     if (! $result) {
 1621: 	&logthis("caching of id -> $id  failed");
 1622: 	$memcache->disconnect_all();
 1623:     }
 1624:     # need to make a copy of $value
 1625:     &make_room($id,$value,$debug);
 1626:     return $value;
 1627: }
 1628: 
 1629: sub make_room {
 1630:     my ($id,$value,$debug)=@_;
 1631: 
 1632:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1633:                                     : $value;
 1634:     if ($to_remember<0) { return; }
 1635:     $accessed{$id}=[&gettimeofday()];
 1636:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1637:     my $to_kick;
 1638:     my $max_time=0;
 1639:     foreach my $other (keys(%accessed)) {
 1640: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1641: 	    $to_kick=$other;
 1642: 	    $max_time=&tv_interval($accessed{$other});
 1643: 	}
 1644:     }
 1645:     delete($remembered{$to_kick});
 1646:     delete($accessed{$to_kick});
 1647:     $kicks++;
 1648:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1649:     return;
 1650: }
 1651: 
 1652: sub purge_remembered {
 1653:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1654:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1655:     undef(%remembered);
 1656:     undef(%accessed);
 1657: }
 1658: # ------------------------------------- Read an entry from a user's environment
 1659: 
 1660: sub userenvironment {
 1661:     my ($udom,$unam,@what)=@_;
 1662:     my $items;
 1663:     foreach my $item (@what) {
 1664:         $items.=&escape($item).'&';
 1665:     }
 1666:     $items=~s/\&$//;
 1667:     my %returnhash=();
 1668:     my $uhome = &homeserver($unam,$udom);
 1669:     unless ($uhome eq 'no_host') {
 1670:         my @answer=split(/\&/, 
 1671:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 1672:         my $i;
 1673:         for ($i=0;$i<=$#what;$i++) {
 1674: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 1675:         }
 1676:     }
 1677:     return %returnhash;
 1678: }
 1679: 
 1680: # ---------------------------------------------------------- Get a studentphoto
 1681: sub studentphoto {
 1682:     my ($udom,$unam,$ext) = @_;
 1683:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1684:     if (defined($env{'request.course.id'})) {
 1685:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1686:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1687:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1688:             } else {
 1689:                 my ($result,$perm_reqd)=
 1690: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1691:                 if ($result eq 'ok') {
 1692:                     if (!($perm_reqd eq 'yes')) {
 1693:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1694:                     }
 1695:                 }
 1696:             }
 1697:         }
 1698:     } else {
 1699:         my ($result,$perm_reqd) = 
 1700: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1701:         if ($result eq 'ok') {
 1702:             if (!($perm_reqd eq 'yes')) {
 1703:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1704:             }
 1705:         }
 1706:     }
 1707:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1708: }
 1709: 
 1710: sub retrievestudentphoto {
 1711:     my ($udom,$unam,$ext,$type) = @_;
 1712:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1713:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1714:     if ($ret eq 'ok') {
 1715:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1716:         if ($type eq 'thumbnail') {
 1717:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1718:         }
 1719:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1720:         return $tokenurl;
 1721:     } else {
 1722:         if ($type eq 'thumbnail') {
 1723:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1724:         } else { 
 1725:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1726:         }
 1727:     }
 1728: }
 1729: 
 1730: # -------------------------------------------------------------------- New chat
 1731: 
 1732: sub chatsend {
 1733:     my ($newentry,$anon,$group)=@_;
 1734:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1735:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1736:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1737:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1738: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1739: 		   &escape($newentry)).':'.$group,$chome);
 1740: }
 1741: 
 1742: # ------------------------------------------ Find current version of a resource
 1743: 
 1744: sub getversion {
 1745:     my $fname=&clutter(shift);
 1746:     unless ($fname=~/^\/res\//) { return -1; }
 1747:     return &currentversion(&filelocation('',$fname));
 1748: }
 1749: 
 1750: sub currentversion {
 1751:     my $fname=shift;
 1752:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1753:     if (defined($cached)) { return $result; }
 1754:     my $author=$fname;
 1755:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1756:     my ($udom,$uname)=split(/\//,$author);
 1757:     my $home=homeserver($uname,$udom);
 1758:     if ($home eq 'no_host') { 
 1759:         return -1; 
 1760:     }
 1761:     my $answer=reply("currentversion:$fname",$home);
 1762:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1763: 	return -1;
 1764:     }
 1765:     return &do_cache_new('resversion',$fname,$answer,600);
 1766: }
 1767: 
 1768: # ----------------------------- Subscribe to a resource, return URL if possible
 1769: 
 1770: sub subscribe {
 1771:     my $fname=shift;
 1772:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1773:     $fname=~s/[\n\r]//g;
 1774:     my $author=$fname;
 1775:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1776:     my ($udom,$uname)=split(/\//,$author);
 1777:     my $home=homeserver($uname,$udom);
 1778:     if ($home eq 'no_host') {
 1779:         return 'not_found';
 1780:     }
 1781:     my $answer=reply("sub:$fname",$home);
 1782:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1783: 	$answer.=' by '.$home;
 1784:     }
 1785:     return $answer;
 1786: }
 1787:     
 1788: # -------------------------------------------------------------- Replicate file
 1789: 
 1790: sub repcopy {
 1791:     my $filename=shift;
 1792:     $filename=~s/\/+/\//g;
 1793:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1794:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1795:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1796: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1797: 	return &repcopy_userfile($filename);
 1798:     }
 1799:     $filename=~s/[\n\r]//g;
 1800:     my $transname="$filename.in.transfer";
 1801: # FIXME: this should flock
 1802:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1803:     my $remoteurl=subscribe($filename);
 1804:     if ($remoteurl =~ /^con_lost by/) {
 1805: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1806:            return 'unavailable';
 1807:     } elsif ($remoteurl eq 'not_found') {
 1808: 	   #&logthis("Subscribe returned not_found: $filename");
 1809: 	   return 'not_found';
 1810:     } elsif ($remoteurl =~ /^rejected by/) {
 1811: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1812:            return 'forbidden';
 1813:     } elsif ($remoteurl eq 'directory') {
 1814:            return 'ok';
 1815:     } else {
 1816:         my $author=$filename;
 1817:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1818:         my ($udom,$uname)=split(/\//,$author);
 1819:         my $home=homeserver($uname,$udom);
 1820:         unless ($home eq $perlvar{'lonHostID'}) {
 1821:            my @parts=split(/\//,$filename);
 1822:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1823:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1824:                &logthis("Malconfiguration for replication: $filename");
 1825: 	       return 'bad_request';
 1826:            }
 1827:            my $count;
 1828:            for ($count=5;$count<$#parts;$count++) {
 1829:                $path.="/$parts[$count]";
 1830:                if ((-e $path)!=1) {
 1831: 		   mkdir($path,0777);
 1832:                }
 1833:            }
 1834:            my $ua=new LWP::UserAgent;
 1835:            my $request=new HTTP::Request('GET',"$remoteurl");
 1836:            my $response=$ua->request($request,$transname);
 1837:            if ($response->is_error()) {
 1838: 	       unlink($transname);
 1839:                my $message=$response->status_line;
 1840:                &logthis("<font color=\"blue\">WARNING:"
 1841:                        ." LWP get: $message: $filename</font>");
 1842:                return 'unavailable';
 1843:            } else {
 1844: 	       if ($remoteurl!~/\.meta$/) {
 1845:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1846:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1847:                   if ($mresponse->is_error()) {
 1848: 		      unlink($filename.'.meta');
 1849:                       &logthis(
 1850:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1851:                   }
 1852: 	       }
 1853:                rename($transname,$filename);
 1854:                return 'ok';
 1855:            }
 1856:        }
 1857:     }
 1858: }
 1859: 
 1860: # ------------------------------------------------ Get server side include body
 1861: sub ssi_body {
 1862:     my ($filelink,%form)=@_;
 1863:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1864:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1865:     }
 1866:     my $output='';
 1867:     my $response;
 1868:     if ($filelink=~/^https?\:/) {
 1869:        ($output,$response)=&externalssi($filelink);
 1870:     } else {
 1871:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 1872:        $filelink .= 'inhibitmenu=yes';
 1873:        ($output,$response)=&ssi($filelink,%form);
 1874:     }
 1875:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1876:     $output=~s/^.*?\<body[^\>]*\>//si;
 1877:     $output=~s/\<\/body\s*\>.*?$//si;
 1878:     if (wantarray) {
 1879:         return ($output, $response);
 1880:     } else {
 1881:         return $output;
 1882:     }
 1883: }
 1884: 
 1885: # --------------------------------------------------------- Server Side Include
 1886: 
 1887: sub absolute_url {
 1888:     my ($host_name) = @_;
 1889:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1890:     if ($host_name eq '') {
 1891: 	$host_name = $ENV{'SERVER_NAME'};
 1892:     }
 1893:     return $protocol.$host_name;
 1894: }
 1895: 
 1896: #
 1897: #   Server side include.
 1898: # Parameters:
 1899: #  fn     Possibly encrypted resource name/id.
 1900: #  form   Hash that describes how the rendering should be done
 1901: #         and other things.
 1902: # Returns:
 1903: #   Scalar context: The content of the response.
 1904: #   Array context:  2 element list of the content and the full response object.
 1905: #     
 1906: sub ssi {
 1907: 
 1908:     my ($fn,%form)=@_;
 1909:     my $ua=new LWP::UserAgent;
 1910:     my $request;
 1911: 
 1912:     $form{'no_update_last_known'}=1;
 1913:     &Apache::lonenc::check_encrypt(\$fn);
 1914:     if (%form) {
 1915:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1916:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 1917:     } else {
 1918:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1919:     }
 1920: 
 1921:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1922:     my $response=$ua->request($request);
 1923: 
 1924:     if (wantarray) {
 1925: 	return ($response->content, $response);
 1926:     } else {
 1927: 	return $response->content;
 1928:     }
 1929: }
 1930: 
 1931: sub externalssi {
 1932:     my ($url)=@_;
 1933:     my $ua=new LWP::UserAgent;
 1934:     my $request=new HTTP::Request('GET',$url);
 1935:     my $response=$ua->request($request);
 1936:     if (wantarray) {
 1937:         return ($response->content, $response);
 1938:     } else {
 1939:         return $response->content;
 1940:     }
 1941: }
 1942: 
 1943: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1944: 
 1945: sub allowuploaded {
 1946:     my ($srcurl,$url)=@_;
 1947:     $url=&clutter(&declutter($url));
 1948:     my $dir=$url;
 1949:     $dir=~s/\/[^\/]+$//;
 1950:     my %httpref=();
 1951:     my $httpurl=&hreflocation('',$url);
 1952:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1953:     &Apache::lonnet::appenv(\%httpref);
 1954: }
 1955: 
 1956: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1957: # input: action, courseID, current domain, intended
 1958: #        path to file, source of file, instruction to parse file for objects,
 1959: #        ref to hash for embedded objects,
 1960: #        ref to hash for codebase of java objects.
 1961: #
 1962: # output: url to file (if action was uploaddoc), 
 1963: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1964: #
 1965: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1966: # course.
 1967: #
 1968: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1969: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1970: #          course's home server.
 1971: #
 1972: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1973: #          be copied from $source (current location) to 
 1974: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1975: #         and will then be copied to
 1976: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1977: #         course's home server.
 1978: #
 1979: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1980: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1981: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1982: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1983: #         in course's home server.
 1984: #
 1985: 
 1986: sub process_coursefile {
 1987:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1988:     my $fetchresult;
 1989:     my $home=&homeserver($docuname,$docudom);
 1990:     if ($action eq 'propagate') {
 1991:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1992: 			     $home);
 1993:     } else {
 1994:         my $fpath = '';
 1995:         my $fname = $file;
 1996:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1997:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1998:         my $filepath = &build_filepath($fpath);
 1999:         if ($action eq 'copy') {
 2000:             if ($source eq '') {
 2001:                 $fetchresult = 'no source file';
 2002:                 return $fetchresult;
 2003:             } else {
 2004:                 my $destination = $filepath.'/'.$fname;
 2005:                 rename($source,$destination);
 2006:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2007:                                  $home);
 2008:             }
 2009:         } elsif ($action eq 'uploaddoc') {
 2010:             open(my $fh,'>'.$filepath.'/'.$fname);
 2011:             print $fh $env{'form.'.$source};
 2012:             close($fh);
 2013:             if ($parser eq 'parse') {
 2014:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2015:                 unless ($parse_result eq 'ok') {
 2016:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2017:                 }
 2018:             }
 2019:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2020:                                  $home);
 2021:             if ($fetchresult eq 'ok') {
 2022:                 return '/uploaded/'.$fpath.'/'.$fname;
 2023:             } else {
 2024:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2025:                         ' to host '.$home.': '.$fetchresult);
 2026:                 return '/adm/notfound.html';
 2027:             }
 2028:         }
 2029:     }
 2030:     unless ( $fetchresult eq 'ok') {
 2031:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2032:              ' to host '.$home.': '.$fetchresult);
 2033:     }
 2034:     return $fetchresult;
 2035: }
 2036: 
 2037: sub build_filepath {
 2038:     my ($fpath) = @_;
 2039:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2040:     unless ($fpath eq '') {
 2041:         my @parts=split('/',$fpath);
 2042:         foreach my $part (@parts) {
 2043:             $filepath.= '/'.$part;
 2044:             if ((-e $filepath)!=1) {
 2045:                 mkdir($filepath,0777);
 2046:             }
 2047:         }
 2048:     }
 2049:     return $filepath;
 2050: }
 2051: 
 2052: sub store_edited_file {
 2053:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2054:     my $file = $primary_url;
 2055:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2056:     my $fpath = '';
 2057:     my $fname = $file;
 2058:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2059:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2060:     my $filepath = &build_filepath($fpath);
 2061:     open(my $fh,'>'.$filepath.'/'.$fname);
 2062:     print $fh $content;
 2063:     close($fh);
 2064:     my $home=&homeserver($docuname,$docudom);
 2065:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2066: 			  $home);
 2067:     if ($$fetchresult eq 'ok') {
 2068:         return '/uploaded/'.$fpath.'/'.$fname;
 2069:     } else {
 2070:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2071: 		 ' to host '.$home.': '.$$fetchresult);
 2072:         return '/adm/notfound.html';
 2073:     }
 2074: }
 2075: 
 2076: sub clean_filename {
 2077:     my ($fname,$args)=@_;
 2078: # Replace Windows backslashes by forward slashes
 2079:     $fname=~s/\\/\//g;
 2080:     if (!$args->{'keep_path'}) {
 2081:         # Get rid of everything but the actual filename
 2082: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2083:     }
 2084: # Replace spaces by underscores
 2085:     $fname=~s/\s+/\_/g;
 2086: # Replace all other weird characters by nothing
 2087:     $fname=~s{[^/\w\.\-]}{}g;
 2088: # Replace all .\d. sequences with _\d. so they no longer look like version
 2089: # numbers
 2090:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2091:     return $fname;
 2092: }
 2093: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
 2094: sub resizeImage {
 2095: 	my($img_url) = @_;	
 2096: 	my $ima = Image::Magick->new;                       
 2097:         $ima->Read($img_url);
 2098: 	if($ima->Get('width') > 400)
 2099: 	{
 2100: 		my $factor = $ima->Get('width')/400;
 2101:              	$ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
 2102: 	}
 2103: 	if($ima->Get('height') > 500)
 2104:         {
 2105:         	my $factor = $ima->Get('height')/500;
 2106:                 $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
 2107:         } 
 2108: 		
 2109: 	$ima->Write($img_url);
 2110: }
 2111: 
 2112: #Wrapper function for userphotoupload
 2113: sub userphotoupload
 2114: {
 2115: 	my($formname,$subdir) = @_;
 2116: 	$upload_photo_form = 1;
 2117: 	return &userfileupload($formname,undef,$subdir);
 2118: }
 2119: 
 2120: # --------------- Take an uploaded file and put it into the userfiles directory
 2121: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2122: #                    the desired filenam is in $env{"form.$formname.filename"}
 2123: #        $coursedoc - if true up to the current course
 2124: #                     if false
 2125: #        $subdir - directory in userfile to store the file into
 2126: #        $parser - instruction to parse file for objects ($parser = parse)    
 2127: #        $allfiles - reference to hash for embedded objects
 2128: #        $codebase - reference to hash for codebase of java objects
 2129: #        $desuname - username for permanent storage of uploaded file
 2130: #        $dsetudom - domain for permanaent storage of uploaded file
 2131: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2132: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2133: # 
 2134: # output: url of file in userspace, or error: <message> 
 2135: #             or /adm/notfound.html if failure to upload occurse
 2136: 
 2137: 
 2138: sub userfileupload {
 2139:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 2140:         $destudom,$thumbwidth,$thumbheight)=@_;
 2141:     if (!defined($subdir)) { $subdir='unknown'; }
 2142:     my $fname=$env{'form.'.$formname.'.filename'};
 2143:     $fname=&clean_filename($fname);
 2144: # See if there is anything left
 2145:     unless ($fname) { return 'error: no uploaded file'; }
 2146:     chop($env{'form.'.$formname});
 2147:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 2148:         my $now = time;
 2149:         my $filepath = 'tmp/helprequests/'.$now;
 2150:         my @parts=split(/\//,$filepath);
 2151:         my $fullpath = $perlvar{'lonDaemons'};
 2152:         for (my $i=0;$i<@parts;$i++) {
 2153:             $fullpath .= '/'.$parts[$i];
 2154:             if ((-e $fullpath)!=1) {
 2155:                 mkdir($fullpath,0777);
 2156:             }
 2157:         }
 2158:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2159:         print $fh $env{'form.'.$formname};
 2160:         close($fh);
 2161:         return $fullpath.'/'.$fname;
 2162:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 2163:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2164:                        '_'.$env{'user.domain'}.'/pending';
 2165:         my @parts=split(/\//,$filepath);
 2166:         my $fullpath = $perlvar{'lonDaemons'};
 2167:         for (my $i=0;$i<@parts;$i++) {
 2168:             $fullpath .= '/'.$parts[$i];
 2169:             if ((-e $fullpath)!=1) {
 2170:                 mkdir($fullpath,0777);
 2171:             }
 2172:         }
 2173:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2174:         print $fh $env{'form.'.$formname};
 2175:         close($fh);
 2176:         return $fullpath.'/'.$fname;
 2177:     }
 2178:     if ($subdir eq 'scantron') {
 2179:         $fname = 'scantron_orig_'.$fname;
 2180:     } else {   
 2181: # Create the directory if not present
 2182:         $fname="$subdir/$fname";
 2183:     }
 2184:     if ($coursedoc) {
 2185: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2186: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2187:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2188:             return &finishuserfileupload($docuname,$docudom,
 2189: 					 $formname,$fname,$parser,$allfiles,
 2190: 					 $codebase,$thumbwidth,$thumbheight);
 2191:         } else {
 2192:             $fname=$env{'form.folder'}.'/'.$fname;
 2193:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2194: 				       $fname,$formname,$parser,
 2195: 				       $allfiles,$codebase);
 2196:         }
 2197:     } elsif (defined($destuname)) {
 2198:         my $docuname=$destuname;
 2199:         my $docudom=$destudom;
 2200: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2201: 				     $parser,$allfiles,$codebase,
 2202:                                      $thumbwidth,$thumbheight);
 2203:         
 2204:     } else {
 2205:         my $docuname=$env{'user.name'};
 2206:         my $docudom=$env{'user.domain'};
 2207:         if (exists($env{'form.group'})) {
 2208:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2209:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2210:         }
 2211: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2212: 				     $parser,$allfiles,$codebase,
 2213:                                      $thumbwidth,$thumbheight);
 2214:     }
 2215: }
 2216: 
 2217: sub finishuserfileupload {
 2218:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2219:         $thumbwidth,$thumbheight) = @_;
 2220:     my $path=$docudom.'/'.$docuname.'/';
 2221:     my $filepath=$perlvar{'lonDocRoot'};
 2222:   
 2223:     my ($fnamepath,$file,$fetchthumb);
 2224:     $file=$fname;
 2225:     if ($fname=~m|/|) {
 2226:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2227: 	$path.=$fnamepath.'/';
 2228:     }
 2229:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2230:     my $count;
 2231:     for ($count=4;$count<=$#parts;$count++) {
 2232:         $filepath.="/$parts[$count]";
 2233:         if ((-e $filepath)!=1) {
 2234: 	    mkdir($filepath,0777);
 2235:         }
 2236:     }
 2237: 
 2238: # Save the file
 2239:     {
 2240: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2241: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2242: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2243: 	    return '/adm/notfound.html';
 2244: 	}
 2245: 	if (!print FH ($env{'form.'.$formname})) {
 2246: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2247: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2248: 	    return '/adm/notfound.html';
 2249: 	}
 2250: 	close(FH);
 2251: 	if($upload_photo_form==1)
 2252: 	{
 2253: 		resizeImage($filepath.'/'.$file);		
 2254: 		$upload_photo_form = 0;
 2255: 	}
 2256:     }
 2257:     if ($parser eq 'parse') {
 2258:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
 2259: 						   $codebase);
 2260:         unless ($parse_result eq 'ok') {
 2261:             &logthis('Failed to parse '.$filepath.$file.
 2262: 		     ' for embedded media: '.$parse_result); 
 2263:         }
 2264:     }
 2265:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2266:         my $input = $filepath.'/'.$file;
 2267:         my $output = $filepath.'/'.'tn-'.$file;
 2268:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2269:         system("convert -sample $thumbsize $input $output");
 2270:         if (-e $filepath.'/'.'tn-'.$file) {
 2271:             $fetchthumb  = 1; 
 2272:         }
 2273:     }
 2274:  
 2275: # Notify homeserver to grep it
 2276: #
 2277:     my $docuhome=&homeserver($docuname,$docudom);	
 2278:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2279:     if ($fetchresult eq 'ok') {
 2280:         if ($fetchthumb) {
 2281:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2282:             if ($thumbresult ne 'ok') {
 2283:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2284:                          $docuhome.': '.$thumbresult);
 2285:             }
 2286:         }
 2287: #
 2288: # Return the URL to it
 2289:         return '/uploaded/'.$path.$file;
 2290:     } else {
 2291:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2292: 		 ': '.$fetchresult);
 2293:         return '/adm/notfound.html';
 2294:     }
 2295: }
 2296: 
 2297: sub extract_embedded_items {
 2298:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 2299:     my @state = ();
 2300:     my %javafiles = (
 2301:                       codebase => '',
 2302:                       code => '',
 2303:                       archive => ''
 2304:                     );
 2305:     my %mediafiles = (
 2306:                       src => '',
 2307:                       movie => '',
 2308:                      );
 2309:     my $p;
 2310:     if ($content) {
 2311:         $p = HTML::LCParser->new($content);
 2312:     } else {
 2313:         $p = HTML::LCParser->new($fullpath);
 2314:     }
 2315:     while (my $t=$p->get_token()) {
 2316: 	if ($t->[0] eq 'S') {
 2317: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2318: 	    push(@state, $tagname);
 2319:             if (lc($tagname) eq 'allow') {
 2320:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2321:             }
 2322: 	    if (lc($tagname) eq 'img') {
 2323: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2324: 	    }
 2325: 	    if (lc($tagname) eq 'a') {
 2326: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2327: 	    }
 2328:             if (lc($tagname) eq 'script') {
 2329:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2330:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2331:                 } else {
 2332:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2333:                 }
 2334:             }
 2335:             if (lc($tagname) eq 'link') {
 2336:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2337:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2338:                 }
 2339:             }
 2340: 	    if (lc($tagname) eq 'object' ||
 2341: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2342: 		foreach my $item (keys(%javafiles)) {
 2343: 		    $javafiles{$item} = '';
 2344: 		}
 2345: 	    }
 2346: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2347: 		my $name = lc($attr->{'name'});
 2348: 		foreach my $item (keys(%javafiles)) {
 2349: 		    if ($name eq $item) {
 2350: 			$javafiles{$item} = $attr->{'value'};
 2351: 			last;
 2352: 		    }
 2353: 		}
 2354: 		foreach my $item (keys(%mediafiles)) {
 2355: 		    if ($name eq $item) {
 2356: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2357: 			last;
 2358: 		    }
 2359: 		}
 2360: 	    }
 2361: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2362: 		foreach my $item (keys(%javafiles)) {
 2363: 		    if ($attr->{$item}) {
 2364: 			$javafiles{$item} = $attr->{$item};
 2365: 			last;
 2366: 		    }
 2367: 		}
 2368: 		foreach my $item (keys(%mediafiles)) {
 2369: 		    if ($attr->{$item}) {
 2370: 			&add_filetype($allfiles,$attr->{$item},$item);
 2371: 			last;
 2372: 		    }
 2373: 		}
 2374: 	    }
 2375: 	} elsif ($t->[0] eq 'E') {
 2376: 	    my ($tagname) = ($t->[1]);
 2377: 	    if ($javafiles{'codebase'} ne '') {
 2378: 		$javafiles{'codebase'} .= '/';
 2379: 	    }  
 2380: 	    if (lc($tagname) eq 'applet' ||
 2381: 		lc($tagname) eq 'object' ||
 2382: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2383: 		) {
 2384: 		foreach my $item (keys(%javafiles)) {
 2385: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2386: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2387: 			&add_filetype($allfiles,$file,$item);
 2388: 		    }
 2389: 		}
 2390: 	    } 
 2391: 	    pop @state;
 2392: 	}
 2393:     }
 2394:     return 'ok';
 2395: }
 2396: 
 2397: sub add_filetype {
 2398:     my ($allfiles,$file,$type)=@_;
 2399:     if (exists($allfiles->{$file})) {
 2400: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2401: 	    push(@{$allfiles->{$file}}, &escape($type));
 2402: 	}
 2403:     } else {
 2404: 	@{$allfiles->{$file}} = (&escape($type));
 2405:     }
 2406: }
 2407: 
 2408: sub removeuploadedurl {
 2409:     my ($url)=@_;	
 2410:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 2411:     return &removeuserfile($uname,$udom,$fname);
 2412: }
 2413: 
 2414: sub removeuserfile {
 2415:     my ($docuname,$docudom,$fname)=@_;
 2416:     my $home=&homeserver($docuname,$docudom);    
 2417:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2418:     if ($result eq 'ok') {	
 2419:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2420:             my $metafile = $fname.'.meta';
 2421:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2422: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2423:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 2424:             my $sqlresult = 
 2425:                 &update_portfolio_table($docuname,$docudom,$file,
 2426:                                         'portfolio_metadata',$group,
 2427:                                         'delete');
 2428:         }
 2429:     }
 2430:     return $result;
 2431: }
 2432: 
 2433: sub mkdiruserfile {
 2434:     my ($docuname,$docudom,$dir)=@_;
 2435:     my $home=&homeserver($docuname,$docudom);
 2436:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2437: }
 2438: 
 2439: sub renameuserfile {
 2440:     my ($docuname,$docudom,$old,$new)=@_;
 2441:     my $home=&homeserver($docuname,$docudom);
 2442:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2443:                         &escape("$old").':'.&escape("$new"),$home);
 2444:     if ($result eq 'ok') {
 2445:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2446:             my $oldmeta = $old.'.meta';
 2447:             my $newmeta = $new.'.meta';
 2448:             my $metaresult = 
 2449:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2450: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2451:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2452:             my $sqlresult = 
 2453:                 &update_portfolio_table($docuname,$docudom,$file,
 2454:                                         'portfolio_metadata',$group,
 2455:                                         'delete');
 2456:         }
 2457:     }
 2458:     return $result;
 2459: }
 2460: 
 2461: # ------------------------------------------------------------------------- Log
 2462: 
 2463: sub log {
 2464:     my ($dom,$nam,$hom,$what)=@_;
 2465:     return critical("log:$dom:$nam:$what",$hom);
 2466: }
 2467: 
 2468: # ------------------------------------------------------------------ Course Log
 2469: #
 2470: # This routine flushes several buffers of non-mission-critical nature
 2471: #
 2472: 
 2473: sub flushcourselogs {
 2474:     &logthis('Flushing log buffers');
 2475: #
 2476: # course logs
 2477: # This is a log of all transactions in a course, which can be used
 2478: # for data mining purposes
 2479: #
 2480: # It also collects the courseid database, which lists last transaction
 2481: # times and course titles for all courseids
 2482: #
 2483:     my %courseidbuffer=();
 2484:     foreach my $crsid (keys(%courselogs)) {
 2485:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2486: 		          &escape($courselogs{$crsid}),
 2487: 		          $coursehombuf{$crsid}) eq 'ok') {
 2488: 	    delete $courselogs{$crsid};
 2489:         } else {
 2490:             &logthis('Failed to flush log buffer for '.$crsid);
 2491:             if (length($courselogs{$crsid})>40000) {
 2492:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2493:                         " exceeded maximum size, deleting.</font>");
 2494:                delete $courselogs{$crsid};
 2495:             }
 2496:         }
 2497:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2498:             'description' => $coursedescrbuf{$crsid},
 2499:             'inst_code'    => $courseinstcodebuf{$crsid},
 2500:             'type'        => $coursetypebuf{$crsid},
 2501:             'owner'       => $courseownerbuf{$crsid},
 2502:         };
 2503:     }
 2504: #
 2505: # Write course id database (reverse lookup) to homeserver of courses 
 2506: # Is used in pickcourse
 2507: #
 2508:     foreach my $crs_home (keys(%courseidbuffer)) {
 2509:         my $response = &courseidput(&host_domain($crs_home),
 2510:                                     $courseidbuffer{$crs_home},
 2511:                                     $crs_home,'timeonly');
 2512:     }
 2513: #
 2514: # File accesses
 2515: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2516: #
 2517:     foreach my $entry (keys(%accesshash)) {
 2518:         if ($entry =~ /___count$/) {
 2519:             my ($dom,$name);
 2520:             ($dom,$name,undef)=
 2521: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2522:             if (! defined($dom) || $dom eq '' || 
 2523:                 ! defined($name) || $name eq '') {
 2524:                 my $cid = $env{'request.course.id'};
 2525:                 $dom  = $env{'request.'.$cid.'.domain'};
 2526:                 $name = $env{'request.'.$cid.'.num'};
 2527:             }
 2528:             my $value = $accesshash{$entry};
 2529:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2530:             my %temphash=($url => $value);
 2531:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2532:             if ($result eq 'ok') {
 2533:                 delete $accesshash{$entry};
 2534:             } elsif ($result eq 'unknown_cmd') {
 2535:                 # Target server has old code running on it.
 2536:                 my %temphash=($entry => $value);
 2537:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2538:                     delete $accesshash{$entry};
 2539:                 }
 2540:             }
 2541:         } else {
 2542:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2543:             my %temphash=($entry => $accesshash{$entry});
 2544:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2545:                 delete $accesshash{$entry};
 2546:             }
 2547:         }
 2548:     }
 2549: #
 2550: # Roles
 2551: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2552: #
 2553:     foreach my $entry (keys(%userrolehash)) {
 2554:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2555: 	    split(/\:/,$entry);
 2556:         if (&Apache::lonnet::put('nohist_userroles',
 2557:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2558:                 $rudom,$runame) eq 'ok') {
 2559: 	    delete $userrolehash{$entry};
 2560:         }
 2561:     }
 2562: #
 2563: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2564: #
 2565:     my %domrolebuffer = ();
 2566:     foreach my $entry (keys(%domainrolehash)) {
 2567:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2568:         if ($domrolebuffer{$rudom}) {
 2569:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2570:                       '='.&escape($domainrolehash{$entry});
 2571:         } else {
 2572:             $domrolebuffer{$rudom}.=&escape($entry).
 2573:                       '='.&escape($domainrolehash{$entry});
 2574:         }
 2575:         delete $domainrolehash{$entry};
 2576:     }
 2577:     foreach my $dom (keys(%domrolebuffer)) {
 2578: 	my %servers = &get_servers($dom,'library');
 2579: 	foreach my $tryserver (keys(%servers)) {
 2580: 	    unless (&reply('domroleput:'.$dom.':'.
 2581: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2582: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2583: 	    }
 2584:         }
 2585:     }
 2586:     $dumpcount++;
 2587: }
 2588: 
 2589: sub courselog {
 2590:     my $what=shift;
 2591:     $what=time.':'.$what;
 2592:     unless ($env{'request.course.id'}) { return ''; }
 2593:     $coursedombuf{$env{'request.course.id'}}=
 2594:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2595:     $coursenumbuf{$env{'request.course.id'}}=
 2596:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2597:     $coursehombuf{$env{'request.course.id'}}=
 2598:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2599:     $coursedescrbuf{$env{'request.course.id'}}=
 2600:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2601:     $courseinstcodebuf{$env{'request.course.id'}}=
 2602:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2603:     $courseownerbuf{$env{'request.course.id'}}=
 2604:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2605:     $coursetypebuf{$env{'request.course.id'}}=
 2606:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2607:     if (defined $courselogs{$env{'request.course.id'}}) {
 2608: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2609:     } else {
 2610: 	$courselogs{$env{'request.course.id'}}.=$what;
 2611:     }
 2612:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2613: 	&flushcourselogs();
 2614:     }
 2615: }
 2616: 
 2617: sub courseacclog {
 2618:     my $fnsymb=shift;
 2619:     unless ($env{'request.course.id'}) { return ''; }
 2620:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2621:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2622:         $what.=':POST';
 2623:         # FIXME: Probably ought to escape things....
 2624: 	foreach my $key (keys(%env)) {
 2625:             if ($key=~/^form\.(.*)/) {
 2626:                 my $formitem = $1;
 2627:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 2628:                     $what.=':'.$formitem.'='.$env{$key};
 2629:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 2630:                     $what.=':'.$formitem.'='.$env{$key};
 2631:                 }
 2632:             }
 2633:         }
 2634:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2635:         # FIXME: We should not be depending on a form parameter that someone
 2636:         # editing lonsearchcat.pm might change in the future.
 2637:         if ($env{'form.phase'} eq 'course_search') {
 2638:             $what.= ':POST';
 2639:             # FIXME: Probably ought to escape things....
 2640:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2641:                                  'crsdiscuss') {
 2642:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2643:             }
 2644:         }
 2645:     }
 2646:     &courselog($what);
 2647: }
 2648: 
 2649: sub countacc {
 2650:     my $url=&declutter(shift);
 2651:     return if (! defined($url) || $url eq '');
 2652:     unless ($env{'request.course.id'}) { return ''; }
 2653:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2654:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2655:     $accesshash{$key}++;
 2656: }
 2657: 
 2658: sub linklog {
 2659:     my ($from,$to)=@_;
 2660:     $from=&declutter($from);
 2661:     $to=&declutter($to);
 2662:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2663:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2664: }
 2665:   
 2666: sub userrolelog {
 2667:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2668:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2669:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2670:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2671:         ($trole=~/^ta/)) {
 2672:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2673:        $userrolehash
 2674:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2675:                     =$tend.':'.$tstart;
 2676:     }
 2677:     if (($env{'request.role'} =~ /dc\./) &&
 2678: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2679: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2680: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
 2681:        $userrolehash
 2682:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2683:                     =$tend.':'.$tstart;
 2684:     }
 2685:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2686:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2687:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2688:         ($trole=~/^sc/)) {
 2689:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2690:        $domainrolehash
 2691:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2692:                     = $tend.':'.$tstart;
 2693:     }
 2694: }
 2695: 
 2696: sub courserolelog {
 2697:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 2698:     if (($trole eq 'cc') || ($trole eq 'in') ||
 2699:         ($trole eq 'ep') || ($trole eq 'ad') ||
 2700:         ($trole eq 'ta') || ($trole eq 'st') ||
 2701:         ($trole=~/^cr/) || ($trole eq 'gr')) {
 2702:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 2703:             my $cdom = $1;
 2704:             my $cnum = $2;
 2705:             my $sec = $3;
 2706:             my $namespace = 'rolelog';
 2707:             my %storehash = (
 2708:                                role    => $trole,
 2709:                                start   => $tstart,
 2710:                                end     => $tend,
 2711:                                selfenroll => $selfenroll,
 2712:                                context    => $context,
 2713:                             );
 2714:             if ($trole eq 'gr') {
 2715:                 $namespace = 'groupslog';
 2716:                 $storehash{'group'} = $sec;
 2717:             } else {
 2718:                 $storehash{'section'} = $sec;
 2719:             }
 2720:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 2721:             if (($trole ne 'st') || ($sec ne '')) {
 2722:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 2723:             }
 2724:         }
 2725:     }
 2726:     return;
 2727: }
 2728: 
 2729: sub get_course_adv_roles {
 2730:     my ($cid,$codes) = @_;
 2731:     $cid=$env{'request.course.id'} unless (defined($cid));
 2732:     my %coursehash=&coursedescription($cid);
 2733:     my $crstype = &Apache::loncommon::course_type($cid);
 2734:     my %nothide=();
 2735:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2736:         if ($user !~ /:/) {
 2737: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2738:         } else {
 2739:             $nothide{$user}=1;
 2740:         }
 2741:     }
 2742:     my %returnhash=();
 2743:     my %dumphash=
 2744:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2745:     my $now=time;
 2746:     my %privileged;
 2747:     foreach my $entry (keys(%dumphash)) {
 2748: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2749:         if (($tstart) && ($tstart<0)) { next; }
 2750:         if (($tend) && ($tend<$now)) { next; }
 2751:         if (($tstart) && ($now<$tstart)) { next; }
 2752:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2753: 	if ($username eq '' || $domain eq '') { next; }
 2754:         unless (ref($privileged{$domain}) eq 'HASH') {
 2755:             my %dompersonnel =
 2756:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 2757:             $privileged{$domain} = {};
 2758:             foreach my $server (keys(%dompersonnel)) {
 2759:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 2760:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 2761:                         my ($trole,$uname,$udom) = split(/:/,$user);
 2762:                         $privileged{$udom}{$uname} = 1;
 2763:                     }
 2764:                 }
 2765:             }
 2766:         }
 2767:         if ((exists($privileged{$domain}{$username})) && 
 2768:             (!$nothide{$username.':'.$domain})) { next; }
 2769: 	if ($role eq 'cr') { next; }
 2770:         if ($codes) {
 2771:             if ($section) { $role .= ':'.$section; }
 2772:             if ($returnhash{$role}) {
 2773:                 $returnhash{$role}.=','.$username.':'.$domain;
 2774:             } else {
 2775:                 $returnhash{$role}=$username.':'.$domain;
 2776:             }
 2777:         } else {
 2778:             my $key=&plaintext($role,$crstype);
 2779:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 2780:             if ($returnhash{$key}) {
 2781: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2782:             } else {
 2783:                 $returnhash{$key}=$username.':'.$domain;
 2784:             }
 2785:         }
 2786:     }
 2787:     return %returnhash;
 2788: }
 2789: 
 2790: sub get_my_roles {
 2791:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2792:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2793:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2794:     my (%dumphash,%nothide);
 2795:     if ($context eq 'userroles') { 
 2796:         %dumphash = &dump('roles',$udom,$uname);
 2797:     } else {
 2798:         %dumphash=
 2799:             &dump('nohist_userroles',$udom,$uname);
 2800:         if ($hidepriv) {
 2801:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2802:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2803:                 if ($user !~ /:/) {
 2804:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2805:                 } else {
 2806:                     $nothide{$user} = 1;
 2807:                 }
 2808:             }
 2809:         }
 2810:     }
 2811:     my %returnhash=();
 2812:     my $now=time;
 2813:     my %privileged;
 2814:     foreach my $entry (keys(%dumphash)) {
 2815:         my ($role,$tend,$tstart);
 2816:         if ($context eq 'userroles') {
 2817: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2818:         } else {
 2819:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2820:         }
 2821:         if (($tstart) && ($tstart<0)) { next; }
 2822:         my $status = 'active';
 2823:         if (($tend) && ($tend<=$now)) {
 2824:             $status = 'previous';
 2825:         } 
 2826:         if (($tstart) && ($now<$tstart)) {
 2827:             $status = 'future';
 2828:         }
 2829:         if (ref($types) eq 'ARRAY') {
 2830:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2831:                 next;
 2832:             } 
 2833:         } else {
 2834:             if ($status ne 'active') {
 2835:                 next;
 2836:             }
 2837:         }
 2838:         my ($rolecode,$username,$domain,$section,$area);
 2839:         if ($context eq 'userroles') {
 2840:             ($area,$rolecode) = split(/_/,$entry);
 2841:             (undef,$domain,$username,$section) = split(/\//,$area);
 2842:         } else {
 2843:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2844:         }
 2845:         if (ref($roledoms) eq 'ARRAY') {
 2846:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2847:                 next;
 2848:             }
 2849:         }
 2850:         if (ref($roles) eq 'ARRAY') {
 2851:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2852:                 if ($role =~ /^cr\//) {
 2853:                     if (!grep(/^cr$/,@{$roles})) {
 2854:                         next;
 2855:                     }
 2856:                 } else {
 2857:                     next;
 2858:                 }
 2859:             }
 2860:         }
 2861:         if ($hidepriv) {
 2862:             if ($context eq 'userroles') {
 2863:                 if ((&privileged($username,$domain)) &&
 2864:                     (!$nothide{$username.':'.$domain})) {
 2865:                     next;
 2866:                 }
 2867:             } else {
 2868:                 unless (ref($privileged{$domain}) eq 'HASH') {
 2869:                     my %dompersonnel =
 2870:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 2871:                     $privileged{$domain} = {};
 2872:                     if (keys(%dompersonnel)) {
 2873:                         foreach my $server (keys(%dompersonnel)) {
 2874:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 2875:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 2876:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 2877:                                     $privileged{$udom}{$uname} = $trole;
 2878:                                 }
 2879:                             }
 2880:                         }
 2881:                     }
 2882:                 }
 2883:                 if (exists($privileged{$domain}{$username})) {
 2884:                     if (!$nothide{$username.':'.$domain}) {
 2885:                         next;
 2886:                     }
 2887:                 }
 2888:             }
 2889:         }
 2890:         if ($withsec) {
 2891:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2892:                 $tstart.':'.$tend;
 2893:         } else {
 2894:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2895:         }
 2896:     }
 2897:     return %returnhash;
 2898: }
 2899: 
 2900: # ----------------------------------------------------- Frontpage Announcements
 2901: #
 2902: #
 2903: 
 2904: sub postannounce {
 2905:     my ($server,$text)=@_;
 2906:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2907:     unless ($text=~/\w/) { $text=''; }
 2908:     return &reply('setannounce:'.&escape($text),$server);
 2909: }
 2910: 
 2911: sub getannounce {
 2912: 
 2913:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2914: 	my $announcement='';
 2915: 	while (my $line = <$fh>) { $announcement .= $line; }
 2916: 	close($fh);
 2917: 	if ($announcement=~/\w/) { 
 2918: 	    return 
 2919:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2920:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2921: 	} else {
 2922: 	    return '';
 2923: 	}
 2924:     } else {
 2925: 	return '';
 2926:     }
 2927: }
 2928: 
 2929: # ---------------------------------------------------------- Course ID routines
 2930: # Deal with domain's nohist_courseid.db files
 2931: #
 2932: 
 2933: sub courseidput {
 2934:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2935:     my $outcome;
 2936:     if ($caller eq 'timeonly') {
 2937:         my $cids = '';
 2938:         foreach my $item (keys(%$storehash)) {
 2939:             $cids.=&escape($item).'&';
 2940:         }
 2941:         $cids=~s/\&$//;
 2942:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 2943:                           $coursehome);       
 2944:     } else {
 2945:         my $items = '';
 2946:         foreach my $item (keys(%$storehash)) {
 2947:             $items.= &escape($item).'='.
 2948:                      &freeze_escape($$storehash{$item}).'&';
 2949:         }
 2950:         $items=~s/\&$//;
 2951:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 2952:                           $coursehome);
 2953:     }
 2954:     if ($outcome eq 'unknown_cmd') {
 2955:         my $what;
 2956:         foreach my $cid (keys(%$storehash)) {
 2957:             $what .= &escape($cid).'=';
 2958:             foreach my $item ('description','inst_code','owner','type') {
 2959:                 $what .= &escape($storehash->{$cid}{$item}).':';
 2960:             }
 2961:             $what =~ s/\:$/&/;
 2962:         }
 2963:         $what =~ s/\&$//;  
 2964:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2965:     } else {
 2966:         return $outcome;
 2967:     }
 2968: }
 2969: 
 2970: sub courseiddump {
 2971:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 2972:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 2973:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,$cloneonly)=@_;
 2974:     my $as_hash = 1;
 2975:     my %returnhash;
 2976:     if (!$domfilter) { $domfilter=''; }
 2977:     my %libserv = &all_library();
 2978:     foreach my $tryserver (keys(%libserv)) {
 2979:         if ( (  $hostidflag == 1 
 2980: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2981: 	     || (!defined($hostidflag)) ) {
 2982: 
 2983: 	    if (($domfilter eq '') ||
 2984: 		(&host_domain($tryserver) eq $domfilter)) {
 2985:                 my $rep = 
 2986:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 2987:                          $sincefilter.':'.&escape($descfilter).':'.
 2988:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 2989:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 2990:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 2991:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 2992:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
 2993:                          &escape($cc_clone).':'.$cloneonly,$tryserver);
 2994:                 my @pairs=split(/\&/,$rep);
 2995:                 foreach my $item (@pairs) {
 2996:                     my ($key,$value)=split(/\=/,$item,2);
 2997:                     $key = &unescape($key);
 2998:                     next if ($key =~ /^error: 2 /);
 2999:                     my $result = &thaw_unescape($value);
 3000:                     if (ref($result) eq 'HASH') {
 3001:                         $returnhash{$key}=$result;
 3002:                     } else {
 3003:                         my @responses = split(/:/,$value);
 3004:                         my @items = ('description','inst_code','owner','type');
 3005:                         for (my $i=0; $i<@responses; $i++) {
 3006:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 3007:                         }
 3008:                     }
 3009:                 }
 3010:             }
 3011:         }
 3012:     }
 3013:     return %returnhash;
 3014: }
 3015: 
 3016: # ---------------------------------------------------------- DC e-mail
 3017: 
 3018: sub dcmailput {
 3019:     my ($domain,$msgid,$message,$server)=@_;
 3020:     my $status = &Apache::lonnet::critical(
 3021:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 3022:        &escape($message),$server);
 3023:     return $status;
 3024: }
 3025: 
 3026: sub dcmaildump {
 3027:     my ($dom,$startdate,$enddate,$senders) = @_;
 3028:     my %returnhash=();
 3029: 
 3030:     if (defined(&domain($dom,'primary'))) {
 3031:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 3032:                                                          &escape($enddate).':';
 3033: 	my @esc_senders=map { &escape($_)} @$senders;
 3034: 	$cmd.=&escape(join('&',@esc_senders));
 3035: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 3036:             my ($key,$value) = split(/\=/,$line,2);
 3037:             if (($key) && ($value)) {
 3038:                 $returnhash{&unescape($key)} = &unescape($value);
 3039:             }
 3040:         }
 3041:     }
 3042:     return %returnhash;
 3043: }
 3044: # ---------------------------------------------------------- Domain roles
 3045: 
 3046: sub get_domain_roles {
 3047:     my ($dom,$roles,$startdate,$enddate)=@_;
 3048:     if (undef($startdate) || $startdate eq '') {
 3049:         $startdate = '.';
 3050:     }
 3051:     if (undef($enddate) || $enddate eq '') {
 3052:         $enddate = '.';
 3053:     }
 3054:     my $rolelist;
 3055:     if (ref($roles) eq 'ARRAY') {
 3056:         $rolelist = join(':',@{$roles});
 3057:     }
 3058:     my %personnel = ();
 3059: 
 3060:     my %servers = &get_servers($dom,'library');
 3061:     foreach my $tryserver (keys(%servers)) {
 3062: 	%{$personnel{$tryserver}}=();
 3063: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 3064: 					    &escape($startdate).':'.
 3065: 					    &escape($enddate).':'.
 3066: 					    &escape($rolelist), $tryserver))) {
 3067: 	    my ($key,$value) = split(/\=/,$line,2);
 3068: 	    if (($key) && ($value)) {
 3069: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 3070: 	    }
 3071: 	}
 3072:     }
 3073:     return %personnel;
 3074: }
 3075: 
 3076: # ----------------------------------------------------------- Check out an item
 3077: 
 3078: sub get_first_access {
 3079:     my ($type,$argsymb)=@_;
 3080:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3081:     if ($argsymb) { $symb=$argsymb; }
 3082:     my ($map,$id,$res)=&decode_symb($symb);
 3083:     if ($type eq 'course') {
 3084: 	$res='course';
 3085:     } elsif ($type eq 'map') {
 3086: 	$res=&symbread($map);
 3087:     } else {
 3088: 	$res=$symb;
 3089:     }
 3090:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 3091:     return $times{"$courseid\0$res"};
 3092: }
 3093: 
 3094: sub set_first_access {
 3095:     my ($type)=@_;
 3096:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3097:     my ($map,$id,$res)=&decode_symb($symb);
 3098:     if ($type eq 'course') {
 3099: 	$res='course';
 3100:     } elsif ($type eq 'map') {
 3101: 	$res=&symbread($map);
 3102:     } else {
 3103: 	$res=$symb;
 3104:     }
 3105:     my $firstaccess=&get_first_access($type,$symb);
 3106:     if (!$firstaccess) {
 3107: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 3108:     }
 3109:     return 'already_set';
 3110: }
 3111: 
 3112: sub checkout {
 3113:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 3114:     my $now=time;
 3115:     my $lonhost=$perlvar{'lonHostID'};
 3116:     my $infostr=&escape(
 3117:                  'CHECKOUTTOKEN&'.
 3118:                  $tuname.'&'.
 3119:                  $tudom.'&'.
 3120:                  $tcrsid.'&'.
 3121:                  $symb.'&'.
 3122: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 3123:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 3124:     if ($token=~/^error\:/) { 
 3125:         &logthis("<font color=\"blue\">WARNING: ".
 3126:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 3127:                  "</font>");
 3128:         return ''; 
 3129:     }
 3130: 
 3131:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 3132:     $token=~tr/a-z/A-Z/;
 3133: 
 3134:     my %infohash=('resource.0.outtoken' => $token,
 3135:                   'resource.0.checkouttime' => $now,
 3136:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 3137: 
 3138:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3139:        return '';
 3140:     } else {
 3141:         &logthis("<font color=\"blue\">WARNING: ".
 3142:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 3143:                  "</font>");
 3144:     }    
 3145: 
 3146:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3147:                          &escape('Checkout '.$infostr.' - '.
 3148:                                                  $token)) ne 'ok') {
 3149: 	return '';
 3150:     } else {
 3151:         &logthis("<font color=\"blue\">WARNING: ".
 3152:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 3153:                  "</font>");
 3154:     }
 3155:     return $token;
 3156: }
 3157: 
 3158: # ------------------------------------------------------------ Check in an item
 3159: 
 3160: sub checkin {
 3161:     my $token=shift;
 3162:     my $now=time;
 3163:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 3164:     $lonhost=~tr/A-Z/a-z/;
 3165:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 3166:     $dtoken=~s/\W/\_/g;
 3167:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 3168:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 3169: 
 3170:     unless (($tuname) && ($tudom)) {
 3171:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 3172:         return '';
 3173:     }
 3174:     
 3175:     unless (&allowed('mgr',$tcrsid)) {
 3176:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 3177:                  $env{'user.name'}.' - '.$env{'user.domain'});
 3178:         return '';
 3179:     }
 3180: 
 3181:     my %infohash=('resource.0.intoken' => $token,
 3182:                   'resource.0.checkintime' => $now,
 3183:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 3184: 
 3185:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3186:        return '';
 3187:     }    
 3188: 
 3189:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3190:                          &escape('Checkin - '.$token)) ne 'ok') {
 3191: 	return '';
 3192:     }
 3193: 
 3194:     return ($symb,$tuname,$tudom,$tcrsid);    
 3195: }
 3196: 
 3197: # --------------------------------------------- Set Expire Date for Spreadsheet
 3198: 
 3199: sub expirespread {
 3200:     my ($uname,$udom,$stype,$usymb)=@_;
 3201:     my $cid=$env{'request.course.id'}; 
 3202:     if ($cid) {
 3203:        my $now=time;
 3204:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3205:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3206:                             $env{'course.'.$cid.'.num'}.
 3207: 	        	    ':nohist_expirationdates:'.
 3208:                             &escape($key).'='.$now,
 3209:                             $env{'course.'.$cid.'.home'})
 3210:     }
 3211:     return 'ok';
 3212: }
 3213: 
 3214: # ----------------------------------------------------- Devalidate Spreadsheets
 3215: 
 3216: sub devalidate {
 3217:     my ($symb,$uname,$udom)=@_;
 3218:     my $cid=$env{'request.course.id'}; 
 3219:     if ($cid) {
 3220:         # delete the stored spreadsheets for
 3221:         # - the student level sheet of this user in course's homespace
 3222:         # - the assessment level sheet for this resource 
 3223:         #   for this user in user's homespace
 3224: 	# - current conditional state info
 3225: 	my $key=$uname.':'.$udom.':';
 3226:         my $status=
 3227: 	    &del('nohist_calculatedsheets',
 3228: 		 [$key.'studentcalc:'],
 3229: 		 $env{'course.'.$cid.'.domain'},
 3230: 		 $env{'course.'.$cid.'.num'})
 3231: 		.' '.
 3232: 	    &del('nohist_calculatedsheets_'.$cid,
 3233: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3234:         unless ($status eq 'ok ok') {
 3235:            &logthis('Could not devalidate spreadsheet '.
 3236:                     $uname.' at '.$udom.' for '.
 3237: 		    $symb.': '.$status);
 3238:         }
 3239: 	&delenv('user.state.'.$cid);
 3240:     }
 3241: }
 3242: 
 3243: sub get_scalar {
 3244:     my ($string,$end) = @_;
 3245:     my $value;
 3246:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3247: 	$value = $1;
 3248:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3249: 	$value = $1;
 3250:     }
 3251:     return &unescape($value);
 3252: }
 3253: 
 3254: sub array2str {
 3255:   my (@array) = @_;
 3256:   my $result=&arrayref2str(\@array);
 3257:   $result=~s/^__ARRAY_REF__//;
 3258:   $result=~s/__END_ARRAY_REF__$//;
 3259:   return $result;
 3260: }
 3261: 
 3262: sub arrayref2str {
 3263:   my ($arrayref) = @_;
 3264:   my $result='__ARRAY_REF__';
 3265:   foreach my $elem (@$arrayref) {
 3266:     if(ref($elem) eq 'ARRAY') {
 3267:       $result.=&arrayref2str($elem).'&';
 3268:     } elsif(ref($elem) eq 'HASH') {
 3269:       $result.=&hashref2str($elem).'&';
 3270:     } elsif(ref($elem)) {
 3271:       #print("Got a ref of ".(ref($elem))." skipping.");
 3272:     } else {
 3273:       $result.=&escape($elem).'&';
 3274:     }
 3275:   }
 3276:   $result=~s/\&$//;
 3277:   $result .= '__END_ARRAY_REF__';
 3278:   return $result;
 3279: }
 3280: 
 3281: sub hash2str {
 3282:   my (%hash) = @_;
 3283:   my $result=&hashref2str(\%hash);
 3284:   $result=~s/^__HASH_REF__//;
 3285:   $result=~s/__END_HASH_REF__$//;
 3286:   return $result;
 3287: }
 3288: 
 3289: sub hashref2str {
 3290:   my ($hashref)=@_;
 3291:   my $result='__HASH_REF__';
 3292:   foreach my $key (sort(keys(%$hashref))) {
 3293:     if (ref($key) eq 'ARRAY') {
 3294:       $result.=&arrayref2str($key).'=';
 3295:     } elsif (ref($key) eq 'HASH') {
 3296:       $result.=&hashref2str($key).'=';
 3297:     } elsif (ref($key)) {
 3298:       $result.='=';
 3299:       #print("Got a ref of ".(ref($key))." skipping.");
 3300:     } else {
 3301: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3302:     }
 3303: 
 3304:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3305:       $result.=&arrayref2str($hashref->{$key}).'&';
 3306:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3307:       $result.=&hashref2str($hashref->{$key}).'&';
 3308:     } elsif(ref($hashref->{$key})) {
 3309:        $result.='&';
 3310:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3311:     } else {
 3312:       $result.=&escape($hashref->{$key}).'&';
 3313:     }
 3314:   }
 3315:   $result=~s/\&$//;
 3316:   $result .= '__END_HASH_REF__';
 3317:   return $result;
 3318: }
 3319: 
 3320: sub str2hash {
 3321:     my ($string)=@_;
 3322:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3323:     return %$hash;
 3324: }
 3325: 
 3326: sub str2hashref {
 3327:   my ($string) = @_;
 3328: 
 3329:   my %hash;
 3330: 
 3331:   if($string !~ /^__HASH_REF__/) {
 3332:       if (! ($string eq '' || !defined($string))) {
 3333: 	  $hash{'error'}='Not hash reference';
 3334:       }
 3335:       return (\%hash, $string);
 3336:   }
 3337: 
 3338:   $string =~ s/^__HASH_REF__//;
 3339: 
 3340:   while($string !~ /^__END_HASH_REF__/) {
 3341:       #key
 3342:       my $key='';
 3343:       if($string =~ /^__HASH_REF__/) {
 3344:           ($key, $string)=&str2hashref($string);
 3345:           if(defined($key->{'error'})) {
 3346:               $hash{'error'}='Bad data';
 3347:               return (\%hash, $string);
 3348:           }
 3349:       } elsif($string =~ /^__ARRAY_REF__/) {
 3350:           ($key, $string)=&str2arrayref($string);
 3351:           if($key->[0] eq 'Array reference error') {
 3352:               $hash{'error'}='Bad data';
 3353:               return (\%hash, $string);
 3354:           }
 3355:       } else {
 3356:           $string =~ s/^(.*?)=//;
 3357: 	  $key=&unescape($1);
 3358:       }
 3359:       $string =~ s/^=//;
 3360: 
 3361:       #value
 3362:       my $value='';
 3363:       if($string =~ /^__HASH_REF__/) {
 3364:           ($value, $string)=&str2hashref($string);
 3365:           if(defined($value->{'error'})) {
 3366:               $hash{'error'}='Bad data';
 3367:               return (\%hash, $string);
 3368:           }
 3369:       } elsif($string =~ /^__ARRAY_REF__/) {
 3370:           ($value, $string)=&str2arrayref($string);
 3371:           if($value->[0] eq 'Array reference error') {
 3372:               $hash{'error'}='Bad data';
 3373:               return (\%hash, $string);
 3374:           }
 3375:       } else {
 3376: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3377:       }
 3378:       $string =~ s/^&//;
 3379: 
 3380:       $hash{$key}=$value;
 3381:   }
 3382: 
 3383:   $string =~ s/^__END_HASH_REF__//;
 3384: 
 3385:   return (\%hash, $string);
 3386: }
 3387: 
 3388: sub str2array {
 3389:     my ($string)=@_;
 3390:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3391:     return @$array;
 3392: }
 3393: 
 3394: sub str2arrayref {
 3395:   my ($string) = @_;
 3396:   my @array;
 3397: 
 3398:   if($string !~ /^__ARRAY_REF__/) {
 3399:       if (! ($string eq '' || !defined($string))) {
 3400: 	  $array[0]='Array reference error';
 3401:       }
 3402:       return (\@array, $string);
 3403:   }
 3404: 
 3405:   $string =~ s/^__ARRAY_REF__//;
 3406: 
 3407:   while($string !~ /^__END_ARRAY_REF__/) {
 3408:       my $value='';
 3409:       if($string =~ /^__HASH_REF__/) {
 3410:           ($value, $string)=&str2hashref($string);
 3411:           if(defined($value->{'error'})) {
 3412:               $array[0] ='Array reference error';
 3413:               return (\@array, $string);
 3414:           }
 3415:       } elsif($string =~ /^__ARRAY_REF__/) {
 3416:           ($value, $string)=&str2arrayref($string);
 3417:           if($value->[0] eq 'Array reference error') {
 3418:               $array[0] ='Array reference error';
 3419:               return (\@array, $string);
 3420:           }
 3421:       } else {
 3422: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3423:       }
 3424:       $string =~ s/^&//;
 3425: 
 3426:       push(@array, $value);
 3427:   }
 3428: 
 3429:   $string =~ s/^__END_ARRAY_REF__//;
 3430: 
 3431:   return (\@array, $string);
 3432: }
 3433: 
 3434: # -------------------------------------------------------------------Temp Store
 3435: 
 3436: sub tmpreset {
 3437:   my ($symb,$namespace,$domain,$stuname) = @_;
 3438:   if (!$symb) {
 3439:     $symb=&symbread();
 3440:     if (!$symb) { $symb= $env{'request.url'}; }
 3441:   }
 3442:   $symb=escape($symb);
 3443: 
 3444:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3445:   $namespace=~s/\//\_/g;
 3446:   $namespace=~s/\W//g;
 3447: 
 3448:   if (!$domain) { $domain=$env{'user.domain'}; }
 3449:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3450:   if ($domain eq 'public' && $stuname eq 'public') {
 3451:       $stuname=$ENV{'REMOTE_ADDR'};
 3452:   }
 3453:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3454:   my %hash;
 3455:   if (tie(%hash,'GDBM_File',
 3456: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3457: 	  &GDBM_WRCREAT(),0640)) {
 3458:     foreach my $key (keys(%hash)) {
 3459:       if ($key=~ /:$symb/) {
 3460: 	delete($hash{$key});
 3461:       }
 3462:     }
 3463:   }
 3464: }
 3465: 
 3466: sub tmpstore {
 3467:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3468: 
 3469:   if (!$symb) {
 3470:     $symb=&symbread();
 3471:     if (!$symb) { $symb= $env{'request.url'}; }
 3472:   }
 3473:   $symb=escape($symb);
 3474: 
 3475:   if (!$namespace) {
 3476:     # I don't think we would ever want to store this for a course.
 3477:     # it seems this will only be used if we don't have a course.
 3478:     #$namespace=$env{'request.course.id'};
 3479:     #if (!$namespace) {
 3480:       $namespace=$env{'request.state'};
 3481:     #}
 3482:   }
 3483:   $namespace=~s/\//\_/g;
 3484:   $namespace=~s/\W//g;
 3485:   if (!$domain) { $domain=$env{'user.domain'}; }
 3486:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3487:   if ($domain eq 'public' && $stuname eq 'public') {
 3488:       $stuname=$ENV{'REMOTE_ADDR'};
 3489:   }
 3490:   my $now=time;
 3491:   my %hash;
 3492:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3493:   if (tie(%hash,'GDBM_File',
 3494: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3495: 	  &GDBM_WRCREAT(),0640)) {
 3496:     $hash{"version:$symb"}++;
 3497:     my $version=$hash{"version:$symb"};
 3498:     my $allkeys=''; 
 3499:     foreach my $key (keys(%$storehash)) {
 3500:       $allkeys.=$key.':';
 3501:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3502:     }
 3503:     $hash{"$version:$symb:timestamp"}=$now;
 3504:     $allkeys.='timestamp';
 3505:     $hash{"$version:keys:$symb"}=$allkeys;
 3506:     if (untie(%hash)) {
 3507:       return 'ok';
 3508:     } else {
 3509:       return "error:$!";
 3510:     }
 3511:   } else {
 3512:     return "error:$!";
 3513:   }
 3514: }
 3515: 
 3516: # -----------------------------------------------------------------Temp Restore
 3517: 
 3518: sub tmprestore {
 3519:   my ($symb,$namespace,$domain,$stuname) = @_;
 3520: 
 3521:   if (!$symb) {
 3522:     $symb=&symbread();
 3523:     if (!$symb) { $symb= $env{'request.url'}; }
 3524:   }
 3525:   $symb=escape($symb);
 3526: 
 3527:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3528: 
 3529:   if (!$domain) { $domain=$env{'user.domain'}; }
 3530:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3531:   if ($domain eq 'public' && $stuname eq 'public') {
 3532:       $stuname=$ENV{'REMOTE_ADDR'};
 3533:   }
 3534:   my %returnhash;
 3535:   $namespace=~s/\//\_/g;
 3536:   $namespace=~s/\W//g;
 3537:   my %hash;
 3538:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3539:   if (tie(%hash,'GDBM_File',
 3540: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3541: 	  &GDBM_READER(),0640)) {
 3542:     my $version=$hash{"version:$symb"};
 3543:     $returnhash{'version'}=$version;
 3544:     my $scope;
 3545:     for ($scope=1;$scope<=$version;$scope++) {
 3546:       my $vkeys=$hash{"$scope:keys:$symb"};
 3547:       my @keys=split(/:/,$vkeys);
 3548:       my $key;
 3549:       $returnhash{"$scope:keys"}=$vkeys;
 3550:       foreach $key (@keys) {
 3551: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3552: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3553:       }
 3554:     }
 3555:     if (!(untie(%hash))) {
 3556:       return "error:$!";
 3557:     }
 3558:   } else {
 3559:     return "error:$!";
 3560:   }
 3561:   return %returnhash;
 3562: }
 3563: 
 3564: # ----------------------------------------------------------------------- Store
 3565: 
 3566: sub store {
 3567:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3568:     my $home='';
 3569: 
 3570:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3571: 
 3572:     $symb=&symbclean($symb);
 3573:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3574: 
 3575:     if (!$domain) { $domain=$env{'user.domain'}; }
 3576:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3577: 
 3578:     &devalidate($symb,$stuname,$domain);
 3579: 
 3580:     $symb=escape($symb);
 3581:     if (!$namespace) { 
 3582:        unless ($namespace=$env{'request.course.id'}) { 
 3583:           return ''; 
 3584:        } 
 3585:     }
 3586:     if (!$home) { $home=$env{'user.home'}; }
 3587: 
 3588:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3589:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3590: 
 3591:     my $namevalue='';
 3592:     foreach my $key (keys(%$storehash)) {
 3593:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3594:     }
 3595:     $namevalue=~s/\&$//;
 3596:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3597:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3598: }
 3599: 
 3600: # -------------------------------------------------------------- Critical Store
 3601: 
 3602: sub cstore {
 3603:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3604:     my $home='';
 3605: 
 3606:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3607: 
 3608:     $symb=&symbclean($symb);
 3609:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3610: 
 3611:     if (!$domain) { $domain=$env{'user.domain'}; }
 3612:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3613: 
 3614:     &devalidate($symb,$stuname,$domain);
 3615: 
 3616:     $symb=escape($symb);
 3617:     if (!$namespace) { 
 3618:        unless ($namespace=$env{'request.course.id'}) { 
 3619:           return ''; 
 3620:        } 
 3621:     }
 3622:     if (!$home) { $home=$env{'user.home'}; }
 3623: 
 3624:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3625:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3626: 
 3627:     my $namevalue='';
 3628:     foreach my $key (keys(%$storehash)) {
 3629:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3630:     }
 3631:     $namevalue=~s/\&$//;
 3632:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3633:     return critical
 3634:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3635: }
 3636: 
 3637: # --------------------------------------------------------------------- Restore
 3638: 
 3639: sub restore {
 3640:     my ($symb,$namespace,$domain,$stuname) = @_;
 3641:     my $home='';
 3642: 
 3643:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3644: 
 3645:     if (!$symb) {
 3646:       unless ($symb=escape(&symbread())) { return ''; }
 3647:     } else {
 3648:       $symb=&escape(&symbclean($symb));
 3649:     }
 3650:     if (!$namespace) { 
 3651:        unless ($namespace=$env{'request.course.id'}) { 
 3652:           return ''; 
 3653:        } 
 3654:     }
 3655:     if (!$domain) { $domain=$env{'user.domain'}; }
 3656:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3657:     if (!$home) { $home=$env{'user.home'}; }
 3658:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3659: 
 3660:     my %returnhash=();
 3661:     foreach my $line (split(/\&/,$answer)) {
 3662: 	my ($name,$value)=split(/\=/,$line);
 3663:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3664:     }
 3665:     my $version;
 3666:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3667:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3668:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3669:        }
 3670:     }
 3671:     return %returnhash;
 3672: }
 3673: 
 3674: # ---------------------------------------------------------- Course Description
 3675: 
 3676: sub coursedescription {
 3677:     my ($courseid,$args)=@_;
 3678:     $courseid=~s/^\///;
 3679:     $courseid=~s/\_/\//g;
 3680:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3681:     my $chome=&homeserver($cnum,$cdomain);
 3682:     my $normalid=$cdomain.'_'.$cnum;
 3683:     # need to always cache even if we get errors otherwise we keep 
 3684:     # trying and trying and trying to get the course description.
 3685:     my %envhash=();
 3686:     my %returnhash=();
 3687:     
 3688:     my $expiretime=600;
 3689:     if ($env{'request.course.id'} eq $normalid) {
 3690: 	$expiretime=120;
 3691:     }
 3692: 
 3693:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3694:     if (!$args->{'freshen_cache'}
 3695: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3696: 	foreach my $key (keys(%env)) {
 3697: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3698: 	    my ($setting) = $1;
 3699: 	    $returnhash{$setting} = $env{$key};
 3700: 	}
 3701: 	return %returnhash;
 3702:     }
 3703: 
 3704:     # get the data agin
 3705:     if (!$args->{'one_time'}) {
 3706: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3707:     }
 3708: 
 3709:     if ($chome ne 'no_host') {
 3710:        %returnhash=&dump('environment',$cdomain,$cnum);
 3711:        if (!exists($returnhash{'con_lost'})) {
 3712:            $returnhash{'home'}= $chome;
 3713: 	   $returnhash{'domain'} = $cdomain;
 3714: 	   $returnhash{'num'} = $cnum;
 3715:            if (!defined($returnhash{'type'})) {
 3716:                $returnhash{'type'} = 'Course';
 3717:            }
 3718:            while (my ($name,$value) = each %returnhash) {
 3719:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3720:            }
 3721:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3722:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3723: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3724:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3725:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3726:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3727:        }
 3728:     }
 3729:     if (!$args->{'one_time'}) {
 3730: 	&appenv(\%envhash);
 3731:     }
 3732:     return %returnhash;
 3733: }
 3734: 
 3735: # -------------------------------------------------See if a user is privileged
 3736: 
 3737: sub privileged {
 3738:     my ($username,$domain)=@_;
 3739:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3740: 			&homeserver($username,$domain));
 3741:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3742:     my $now=time;
 3743:     if ($rolesdump ne '') {
 3744:         foreach my $entry (split(/&/,$rolesdump)) {
 3745: 	    if ($entry!~/^rolesdef_/) {
 3746: 		my ($area,$role)=split(/=/,$entry);
 3747: 		$area=~s/\_\w\w$//;
 3748: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3749: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3750: 		    my $active=1;
 3751: 		    if ($tend) {
 3752: 			if ($tend<$now) { $active=0; }
 3753: 		    }
 3754: 		    if ($tstart) {
 3755: 			if ($tstart>$now) { $active=0; }
 3756: 		    }
 3757: 		    if ($active) { return 1; }
 3758: 		}
 3759: 	    }
 3760: 	}
 3761:     }
 3762:     return 0;
 3763: }
 3764: 
 3765: # -------------------------------------------------------- Get user privileges
 3766: 
 3767: sub rolesinit {
 3768:     my ($domain,$username,$authhost)=@_;
 3769:     my %userroles;
 3770:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3771:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
 3772:     my %allroles=();
 3773:     my %allgroups=();   
 3774:     my $now=time;
 3775:     %userroles = ('user.login.time' => $now);
 3776:     my $group_privs;
 3777: 
 3778:     if ($rolesdump ne '') {
 3779:         foreach my $entry (split(/&/,$rolesdump)) {
 3780: 	  if ($entry!~/^rolesdef_/) {
 3781:             my ($area,$role)=split(/=/,$entry);
 3782: 	    $area=~s/\_\w\w$//;
 3783:             my ($trole,$tend,$tstart,$group_privs);
 3784: 	    if ($role=~/^cr/) { 
 3785: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3786: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3787: 		    ($tend,$tstart)=split('_',$trest);
 3788: 		} else {
 3789: 		    $trole=$role;
 3790: 		}
 3791:             } elsif ($role =~ m|^gr/|) {
 3792:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3793:                 ($trole,$group_privs) = split(/\//,$trole);
 3794:                 $group_privs = &unescape($group_privs);
 3795: 	    } else {
 3796: 		($trole,$tend,$tstart)=split(/_/,$role);
 3797: 	    }
 3798: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3799: 					 $username);
 3800: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3801:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3802:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3803:             if (($area ne '') && ($trole ne '')) {
 3804: 		my $spec=$trole.'.'.$area;
 3805: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3806: 		if ($trole =~ /^cr\//) {
 3807:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3808:                 } elsif ($trole eq 'gr') {
 3809:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3810: 		} else {
 3811:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3812: 		}
 3813:             }
 3814:           }
 3815:         }
 3816:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3817:         $userroles{'user.adv'}    = $adv;
 3818: 	$userroles{'user.author'} = $author;
 3819:         $env{'user.adv'}=$adv;
 3820:     }
 3821:     return \%userroles;  
 3822: }
 3823: 
 3824: sub set_arearole {
 3825:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3826: # log the associated role with the area
 3827:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3828:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3829: }
 3830: 
 3831: sub custom_roleprivs {
 3832:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3833:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3834:     my $homsvr=homeserver($rauthor,$rdomain);
 3835:     if (&hostname($homsvr) ne '') {
 3836:         my ($rdummy,$roledef)=
 3837:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3838:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3839:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3840:             if (defined($syspriv)) {
 3841:                 $$allroles{'cm./'}.=':'.$syspriv;
 3842:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3843:             }
 3844:             if ($tdomain ne '') {
 3845:                 if (defined($dompriv)) {
 3846:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3847:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3848:                 }
 3849:                 if (($trest ne '') && (defined($coursepriv))) {
 3850:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3851:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3852:                 }
 3853:             }
 3854:         }
 3855:     }
 3856: }
 3857: 
 3858: sub group_roleprivs {
 3859:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3860:     my $access = 1;
 3861:     my $now = time;
 3862:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3863:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3864:     if ($access) {
 3865:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3866:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3867:     }
 3868: }
 3869: 
 3870: sub standard_roleprivs {
 3871:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3872:     if (defined($pr{$trole.':s'})) {
 3873:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3874:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3875:     }
 3876:     if ($tdomain ne '') {
 3877:         if (defined($pr{$trole.':d'})) {
 3878:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3879:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3880:         }
 3881:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3882:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3883:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3884:         }
 3885:     }
 3886: }
 3887: 
 3888: sub set_userprivs {
 3889:     my ($userroles,$allroles,$allgroups) = @_; 
 3890:     my $author=0;
 3891:     my $adv=0;
 3892:     my %grouproles = ();
 3893:     if (keys(%{$allgroups}) > 0) {
 3894:         foreach my $role (keys(%{$allroles})) {
 3895:             my ($trole,$area,$sec,$extendedarea);
 3896:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3897:                 $trole = $1;
 3898:                 $area = $2;
 3899:                 $sec = $3;
 3900:                 $extendedarea = $area.$sec;
 3901:                 if (exists($$allgroups{$area})) {
 3902:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3903:                         my $spec = $trole.'.'.$extendedarea;
 3904:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3905:                                                 $$allgroups{$area}{$group};
 3906:                     }
 3907:                 }
 3908:             }
 3909:         }
 3910:     }
 3911:     foreach my $group (keys(%grouproles)) {
 3912:         $$allroles{$group} = $grouproles{$group};
 3913:     }
 3914:     foreach my $role (keys(%{$allroles})) {
 3915:         my %thesepriv;
 3916:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3917:         foreach my $item (split(/:/,$$allroles{$role})) {
 3918:             if ($item ne '') {
 3919:                 my ($privilege,$restrictions)=split(/&/,$item);
 3920:                 if ($restrictions eq '') {
 3921:                     $thesepriv{$privilege}='F';
 3922:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3923:                     $thesepriv{$privilege}.=$restrictions;
 3924:                 }
 3925:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3926:             }
 3927:         }
 3928:         my $thesestr='';
 3929:         foreach my $priv (keys(%thesepriv)) {
 3930: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3931: 	}
 3932:         $userroles->{'user.priv.'.$role} = $thesestr;
 3933:     }
 3934:     return ($author,$adv);
 3935: }
 3936: 
 3937: sub role_status {
 3938:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 3939:     my @pwhere = ();
 3940:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 3941:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 3942:         unless (!defined($$role) || $$role eq '') {
 3943:             $$where=join('.',@pwhere);
 3944:             $$trolecode=$$role.'.'.$$where;
 3945:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 3946:             $$tstatus='is';
 3947:             if ($$tstart && $$tstart>$then) {
 3948:                 $$tstatus='future';
 3949:                 if ($$tstart && $$tstart>$refresh) {
 3950:                     if ($$tstart<$now) {
 3951:                         if (($$where ne '') && ($$role ne '')) {
 3952:                             my (%allroles,%allgroups,$group_privs);
 3953:                             my %userroles = (
 3954:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 3955:                             );
 3956:                             my $spec=$$role.'.'.$$where;
 3957:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 3958:                             if ($$role eq 'gr') {
 3959:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 3960:                                                     $env{'user.name'})=@_;
 3961:                                 my ($trole) = split('_',$role,1);
 3962:                                 (undef,my $group_privs) = split(/\//,$trole);
 3963:                                 $group_privs = &unescape($group_privs);
 3964:                             }
 3965:                             if ($$role =~ /^cr\//) {
 3966:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 3967:                             } elsif ($$role eq 'gr') {
 3968:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 3969:                                                     $env{'user.name'});
 3970:                                 my $trole = split('_',$rolehash{$$where.'_'.$$role},1);
 3971:                                 (undef,my $group_privs) = split(/\//,$trole);
 3972:                                 $group_privs = &unescape($group_privs);
 3973:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 3974:                             } else {
 3975:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 3976:                             }
 3977:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3978:                             &appenv(\%userroles,[$$role,'cm']);
 3979:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 3980:                             $$tstatus = 'is';
 3981:                         }
 3982:                     }
 3983:                 }
 3984:             }
 3985:             if ($$tend) {
 3986:                 if ($$tend<$then) {
 3987:                     $$tstatus='expired';
 3988:                 } elsif ($$tend<$now) {
 3989:                     $$tstatus='will_not';
 3990:                 }
 3991:             }
 3992:         }
 3993:     }
 3994: }
 3995: 
 3996: sub check_adhoc_privs {
 3997:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
 3998:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 3999:     if ($env{$cckey}) {
 4000:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 4001:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 4002:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 4003:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
 4004:         }
 4005:     } else {
 4006:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
 4007:     }
 4008: }
 4009: 
 4010: sub set_adhoc_privileges {
 4011: # role can be cc or ca
 4012:     my ($dcdom,$pickedcourse,$role) = @_;
 4013:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 4014:     my $spec = $role.'.'.$area;
 4015:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 4016:                                   $env{'user.name'});
 4017:     my %ccrole = ();
 4018:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 4019:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 4020:     &appenv(\%userroles,[$role,'cm']);
 4021:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4022:     &appenv( {'request.role'        => $spec,
 4023:               'request.role.domain' => $dcdom,
 4024:               'request.course.sec'  => ''
 4025:              }
 4026:            );
 4027:     my $tadv=0;
 4028:     if (&allowed('adv') eq 'F') { $tadv=1; }
 4029:     &appenv({'request.role.adv'    => $tadv});
 4030: }
 4031: 
 4032: # --------------------------------------------------------------- get interface
 4033: 
 4034: sub get {
 4035:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4036:    my $items='';
 4037:    foreach my $item (@$storearr) {
 4038:        $items.=&escape($item).'&';
 4039:    }
 4040:    $items=~s/\&$//;
 4041:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4042:    if (!$uname) { $uname=$env{'user.name'}; }
 4043:    my $uhome=&homeserver($uname,$udomain);
 4044: 
 4045:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 4046:    my @pairs=split(/\&/,$rep);
 4047:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 4048:      return @pairs;
 4049:    }
 4050:    my %returnhash=();
 4051:    my $i=0;
 4052:    foreach my $item (@$storearr) {
 4053:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4054:       $i++;
 4055:    }
 4056:    return %returnhash;
 4057: }
 4058: 
 4059: # --------------------------------------------------------------- del interface
 4060: 
 4061: sub del {
 4062:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4063:    my $items='';
 4064:    foreach my $item (@$storearr) {
 4065:        $items.=&escape($item).'&';
 4066:    }
 4067: 
 4068:    $items=~s/\&$//;
 4069:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4070:    if (!$uname) { $uname=$env{'user.name'}; }
 4071:    my $uhome=&homeserver($uname,$udomain);
 4072:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 4073: }
 4074: 
 4075: # -------------------------------------------------------------- dump interface
 4076: 
 4077: sub dump {
 4078:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4079:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4080:     if (!$uname) { $uname=$env{'user.name'}; }
 4081:     my $uhome=&homeserver($uname,$udomain);
 4082:     if ($regexp) {
 4083: 	$regexp=&escape($regexp);
 4084:     } else {
 4085: 	$regexp='.';
 4086:     }
 4087:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4088:     my @pairs=split(/\&/,$rep);
 4089:     my %returnhash=();
 4090:     foreach my $item (@pairs) {
 4091: 	my ($key,$value)=split(/=/,$item,2);
 4092: 	$key = &unescape($key);
 4093: 	next if ($key =~ /^error: 2 /);
 4094: 	$returnhash{$key}=&thaw_unescape($value);
 4095:     }
 4096:     return %returnhash;
 4097: }
 4098: 
 4099: # --------------------------------------------------------- dumpstore interface
 4100: 
 4101: sub dumpstore {
 4102:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4103:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4104:    if (!$uname) { $uname=$env{'user.name'}; }
 4105:    my $uhome=&homeserver($uname,$udomain);
 4106:    if ($regexp) {
 4107:        $regexp=&escape($regexp);
 4108:    } else {
 4109:        $regexp='.';
 4110:    }
 4111:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4112:    my @pairs=split(/\&/,$rep);
 4113:    my %returnhash=();
 4114:    foreach my $item (@pairs) {
 4115:        my ($key,$value)=split(/=/,$item,2);
 4116:        next if ($key =~ /^error: 2 /);
 4117:        $returnhash{$key}=&thaw_unescape($value);
 4118:    }
 4119:    return %returnhash;
 4120: }
 4121: 
 4122: # -------------------------------------------------------------- keys interface
 4123: 
 4124: sub getkeys {
 4125:    my ($namespace,$udomain,$uname)=@_;
 4126:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4127:    if (!$uname) { $uname=$env{'user.name'}; }
 4128:    my $uhome=&homeserver($uname,$udomain);
 4129:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 4130:    my @keyarray=();
 4131:    foreach my $key (split(/\&/,$rep)) {
 4132:       next if ($key =~ /^error: 2 /);
 4133:       push(@keyarray,&unescape($key));
 4134:    }
 4135:    return @keyarray;
 4136: }
 4137: 
 4138: # --------------------------------------------------------------- currentdump
 4139: sub currentdump {
 4140:    my ($courseid,$sdom,$sname)=@_;
 4141:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 4142:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 4143:    $sname    = $env{'user.name'}         if (! defined($sname));
 4144:    my $uhome = &homeserver($sname,$sdom);
 4145:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 4146:    return if ($rep =~ /^(error:|no_such_host)/);
 4147:    #
 4148:    my %returnhash=();
 4149:    #
 4150:    if ($rep eq "unknown_cmd") { 
 4151:        # an old lond will not know currentdump
 4152:        # Do a dump and make it look like a currentdump
 4153:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 4154:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 4155:        my %hash = @tmp;
 4156:        @tmp=();
 4157:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 4158:    } else {
 4159:        my @pairs=split(/\&/,$rep);
 4160:        foreach my $pair (@pairs) {
 4161:            my ($key,$value)=split(/=/,$pair,2);
 4162:            my ($symb,$param) = split(/:/,$key);
 4163:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 4164:                                                         &thaw_unescape($value);
 4165:        }
 4166:    }
 4167:    return %returnhash;
 4168: }
 4169: 
 4170: sub convert_dump_to_currentdump{
 4171:     my %hash = %{shift()};
 4172:     my %returnhash;
 4173:     # Code ripped from lond, essentially.  The only difference
 4174:     # here is the unescaping done by lonnet::dump().  Conceivably
 4175:     # we might run in to problems with parameter names =~ /^v\./
 4176:     while (my ($key,$value) = each(%hash)) {
 4177:         my ($v,$symb,$param) = split(/:/,$key);
 4178: 	$symb  = &unescape($symb);
 4179: 	$param = &unescape($param);
 4180:         next if ($v eq 'version' || $symb eq 'keys');
 4181:         next if (exists($returnhash{$symb}) &&
 4182:                  exists($returnhash{$symb}->{$param}) &&
 4183:                  $returnhash{$symb}->{'v.'.$param} > $v);
 4184:         $returnhash{$symb}->{$param}=$value;
 4185:         $returnhash{$symb}->{'v.'.$param}=$v;
 4186:     }
 4187:     #
 4188:     # Remove all of the keys in the hashes which keep track of
 4189:     # the version of the parameter.
 4190:     while (my ($symb,$param_hash) = each(%returnhash)) {
 4191:         # use a foreach because we are going to delete from the hash.
 4192:         foreach my $key (keys(%$param_hash)) {
 4193:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 4194:         }
 4195:     }
 4196:     return \%returnhash;
 4197: }
 4198: 
 4199: # ------------------------------------------------------ critical inc interface
 4200: 
 4201: sub cinc {
 4202:     return &inc(@_,'critical');
 4203: }
 4204: 
 4205: # --------------------------------------------------------------- inc interface
 4206: 
 4207: sub inc {
 4208:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 4209:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4210:     if (!$uname) { $uname=$env{'user.name'}; }
 4211:     my $uhome=&homeserver($uname,$udomain);
 4212:     my $items='';
 4213:     if (! ref($store)) {
 4214:         # got a single value, so use that instead
 4215:         $items = &escape($store).'=&';
 4216:     } elsif (ref($store) eq 'SCALAR') {
 4217:         $items = &escape($$store).'=&';        
 4218:     } elsif (ref($store) eq 'ARRAY') {
 4219:         $items = join('=&',map {&escape($_);} @{$store});
 4220:     } elsif (ref($store) eq 'HASH') {
 4221:         while (my($key,$value) = each(%{$store})) {
 4222:             $items.= &escape($key).'='.&escape($value).'&';
 4223:         }
 4224:     }
 4225:     $items=~s/\&$//;
 4226:     if ($critical) {
 4227: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 4228:     } else {
 4229: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 4230:     }
 4231: }
 4232: 
 4233: # --------------------------------------------------------------- put interface
 4234: 
 4235: sub put {
 4236:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4237:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4238:    if (!$uname) { $uname=$env{'user.name'}; }
 4239:    my $uhome=&homeserver($uname,$udomain);
 4240:    my $items='';
 4241:    foreach my $item (keys(%$storehash)) {
 4242:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4243:    }
 4244:    $items=~s/\&$//;
 4245:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4246: }
 4247: 
 4248: # ------------------------------------------------------------ newput interface
 4249: 
 4250: sub newput {
 4251:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4252:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4253:    if (!$uname) { $uname=$env{'user.name'}; }
 4254:    my $uhome=&homeserver($uname,$udomain);
 4255:    my $items='';
 4256:    foreach my $key (keys(%$storehash)) {
 4257:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4258:    }
 4259:    $items=~s/\&$//;
 4260:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 4261: }
 4262: 
 4263: # ---------------------------------------------------------  putstore interface
 4264: 
 4265: sub putstore {
 4266:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4267:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4268:    if (!$uname) { $uname=$env{'user.name'}; }
 4269:    my $uhome=&homeserver($uname,$udomain);
 4270:    my $items='';
 4271:    foreach my $key (keys(%$storehash)) {
 4272:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 4273:    }
 4274:    $items=~s/\&$//;
 4275:    my $esc_symb=&escape($symb);
 4276:    my $esc_v=&escape($version);
 4277:    my $reply =
 4278:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 4279: 	      $uhome);
 4280:    if ($reply eq 'unknown_cmd') {
 4281:        # gfall back to way things use to be done
 4282:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 4283: 			    $uname);
 4284:    }
 4285:    return $reply;
 4286: }
 4287: 
 4288: sub old_putstore {
 4289:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4290:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4291:     if (!$uname) { $uname=$env{'user.name'}; }
 4292:     my $uhome=&homeserver($uname,$udomain);
 4293:     my %newstorehash;
 4294:     foreach my $item (keys(%$storehash)) {
 4295: 	my $key = $version.':'.&escape($symb).':'.$item;
 4296: 	$newstorehash{$key} = $storehash->{$item};
 4297:     }
 4298:     my $items='';
 4299:     my %allitems = ();
 4300:     foreach my $item (keys(%newstorehash)) {
 4301: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 4302: 	    my $key = $1.':keys:'.$2;
 4303: 	    $allitems{$key} .= $3.':';
 4304: 	}
 4305: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 4306:     }
 4307:     foreach my $item (keys(%allitems)) {
 4308: 	$allitems{$item} =~ s/\:$//;
 4309: 	$items.= $item.'='.$allitems{$item}.'&';
 4310:     }
 4311:     $items=~s/\&$//;
 4312:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4313: }
 4314: 
 4315: # ------------------------------------------------------ critical put interface
 4316: 
 4317: sub cput {
 4318:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4319:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4320:    if (!$uname) { $uname=$env{'user.name'}; }
 4321:    my $uhome=&homeserver($uname,$udomain);
 4322:    my $items='';
 4323:    foreach my $item (keys(%$storehash)) {
 4324:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4325:    }
 4326:    $items=~s/\&$//;
 4327:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 4328: }
 4329: 
 4330: # -------------------------------------------------------------- eget interface
 4331: 
 4332: sub eget {
 4333:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4334:    my $items='';
 4335:    foreach my $item (@$storearr) {
 4336:        $items.=&escape($item).'&';
 4337:    }
 4338:    $items=~s/\&$//;
 4339:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4340:    if (!$uname) { $uname=$env{'user.name'}; }
 4341:    my $uhome=&homeserver($uname,$udomain);
 4342:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 4343:    my @pairs=split(/\&/,$rep);
 4344:    my %returnhash=();
 4345:    my $i=0;
 4346:    foreach my $item (@$storearr) {
 4347:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4348:       $i++;
 4349:    }
 4350:    return %returnhash;
 4351: }
 4352: 
 4353: # ------------------------------------------------------------ tmpput interface
 4354: sub tmpput {
 4355:     my ($storehash,$server,$context)=@_;
 4356:     my $items='';
 4357:     foreach my $item (keys(%$storehash)) {
 4358: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4359:     }
 4360:     $items=~s/\&$//;
 4361:     if (defined($context)) {
 4362:         $items .= ':'.&escape($context);
 4363:     }
 4364:     return &reply("tmpput:$items",$server);
 4365: }
 4366: 
 4367: # ------------------------------------------------------------ tmpget interface
 4368: sub tmpget {
 4369:     my ($token,$server)=@_;
 4370:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4371:     my $rep=&reply("tmpget:$token",$server);
 4372:     my %returnhash;
 4373:     foreach my $item (split(/\&/,$rep)) {
 4374: 	my ($key,$value)=split(/=/,$item);
 4375:         next if ($key =~ /^error: 2 /);
 4376: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 4377:     }
 4378:     return %returnhash;
 4379: }
 4380: 
 4381: # ------------------------------------------------------------ tmpget interface
 4382: sub tmpdel {
 4383:     my ($token,$server)=@_;
 4384:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4385:     return &reply("tmpdel:$token",$server);
 4386: }
 4387: 
 4388: # -------------------------------------------------- portfolio access checking
 4389: 
 4390: sub portfolio_access {
 4391:     my ($requrl) = @_;
 4392:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4393:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4394:     if ($result) {
 4395:         my %setters;
 4396:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4397:             my ($startblock,$endblock) =
 4398:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4399:             if ($startblock && $endblock) {
 4400:                 return 'B';
 4401:             }
 4402:         } else {
 4403:             my ($startblock,$endblock) =
 4404:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4405:             if ($startblock && $endblock) {
 4406:                 return 'B';
 4407:             }
 4408:         }
 4409:     }
 4410:     if ($result eq 'ok') {
 4411:        return 'F';
 4412:     } elsif ($result =~ /^[^:]+:guest_/) {
 4413:        return 'A';
 4414:     }
 4415:     return '';
 4416: }
 4417: 
 4418: sub get_portfolio_access {
 4419:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4420: 
 4421:     if (!ref($access_hash)) {
 4422: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4423: 	my %access_controls = &get_access_controls($current_perms,$group,
 4424: 						   $file_name);
 4425: 	$access_hash = $access_controls{$file_name};
 4426:     }
 4427: 
 4428:     my ($public,$guest,@domains,@users,@courses,@groups);
 4429:     my $now = time;
 4430:     if (ref($access_hash) eq 'HASH') {
 4431:         foreach my $key (keys(%{$access_hash})) {
 4432:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4433:             if ($start > $now) {
 4434:                 next;
 4435:             }
 4436:             if ($end && $end<$now) {
 4437:                 next;
 4438:             }
 4439:             if ($scope eq 'public') {
 4440:                 $public = $key;
 4441:                 last;
 4442:             } elsif ($scope eq 'guest') {
 4443:                 $guest = $key;
 4444:             } elsif ($scope eq 'domains') {
 4445:                 push(@domains,$key);
 4446:             } elsif ($scope eq 'users') {
 4447:                 push(@users,$key);
 4448:             } elsif ($scope eq 'course') {
 4449:                 push(@courses,$key);
 4450:             } elsif ($scope eq 'group') {
 4451:                 push(@groups,$key);
 4452:             }
 4453:         }
 4454:         if ($public) {
 4455:             return 'ok';
 4456:         }
 4457:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4458:             if ($guest) {
 4459:                 return $guest;
 4460:             }
 4461:         } else {
 4462:             if (@domains > 0) {
 4463:                 foreach my $domkey (@domains) {
 4464:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4465:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4466:                             return 'ok';
 4467:                         }
 4468:                     }
 4469:                 }
 4470:             }
 4471:             if (@users > 0) {
 4472:                 foreach my $userkey (@users) {
 4473:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4474:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4475:                             if (ref($item) eq 'HASH') {
 4476:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4477:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4478:                                     return 'ok';
 4479:                                 }
 4480:                             }
 4481:                         }
 4482:                     } 
 4483:                 }
 4484:             }
 4485:             my %roleshash;
 4486:             my @courses_and_groups = @courses;
 4487:             push(@courses_and_groups,@groups); 
 4488:             if (@courses_and_groups > 0) {
 4489:                 my (%allgroups,%allroles); 
 4490:                 my ($start,$end,$role,$sec,$group);
 4491:                 foreach my $envkey (%env) {
 4492:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4493:                         my $cid = $2.'_'.$3; 
 4494:                         if ($1 eq 'gr') {
 4495:                             $group = $4;
 4496:                             $allgroups{$cid}{$group} = $env{$envkey};
 4497:                         } else {
 4498:                             if ($4 eq '') {
 4499:                                 $sec = 'none';
 4500:                             } else {
 4501:                                 $sec = $4;
 4502:                             }
 4503:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4504:                         }
 4505:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4506:                         my $cid = $2.'_'.$3;
 4507:                         if ($4 eq '') {
 4508:                             $sec = 'none';
 4509:                         } else {
 4510:                             $sec = $4;
 4511:                         }
 4512:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4513:                     }
 4514:                 }
 4515:                 if (keys(%allroles) == 0) {
 4516:                     return;
 4517:                 }
 4518:                 foreach my $key (@courses_and_groups) {
 4519:                     my %content = %{$$access_hash{$key}};
 4520:                     my $cnum = $content{'number'};
 4521:                     my $cdom = $content{'domain'};
 4522:                     my $cid = $cdom.'_'.$cnum;
 4523:                     if (!exists($allroles{$cid})) {
 4524:                         next;
 4525:                     }    
 4526:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4527:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4528:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4529:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4530:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4531:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4532:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4533:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4534:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4535:                                         if (grep/^all$/,@sections) {
 4536:                                             return 'ok';
 4537:                                         } else {
 4538:                                             if (grep/^$sec$/,@sections) {
 4539:                                                 return 'ok';
 4540:                                             }
 4541:                                         }
 4542:                                     }
 4543:                                 }
 4544:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4545:                                     if (grep/^none$/,@groups) {
 4546:                                         return 'ok';
 4547:                                     }
 4548:                                 } else {
 4549:                                     if (grep/^all$/,@groups) {
 4550:                                         return 'ok';
 4551:                                     } 
 4552:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4553:                                         if (grep/^$group$/,@groups) {
 4554:                                             return 'ok';
 4555:                                         }
 4556:                                     }
 4557:                                 } 
 4558:                             }
 4559:                         }
 4560:                     }
 4561:                 }
 4562:             }
 4563:             if ($guest) {
 4564:                 return $guest;
 4565:             }
 4566:         }
 4567:     }
 4568:     return;
 4569: }
 4570: 
 4571: sub course_group_datechecker {
 4572:     my ($dates,$now,$status) = @_;
 4573:     my ($start,$end) = split(/\./,$dates);
 4574:     if (!$start && !$end) {
 4575:         return 'ok';
 4576:     }
 4577:     if (grep/^active$/,@{$status}) {
 4578:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4579:             return 'ok';
 4580:         }
 4581:     }
 4582:     if (grep/^previous$/,@{$status}) {
 4583:         if ($end > $now ) {
 4584:             return 'ok';
 4585:         }
 4586:     }
 4587:     if (grep/^future$/,@{$status}) {
 4588:         if ($start > $now) {
 4589:             return 'ok';
 4590:         }
 4591:     }
 4592:     return; 
 4593: }
 4594: 
 4595: sub parse_portfolio_url {
 4596:     my ($url) = @_;
 4597: 
 4598:     my ($type,$udom,$unum,$group,$file_name);
 4599:     
 4600:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4601: 	$type = 1;
 4602:         $udom = $1;
 4603:         $unum = $2;
 4604:         $file_name = $3;
 4605:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4606: 	$type = 2;
 4607:         $udom = $1;
 4608:         $unum = $2;
 4609:         $group = $3;
 4610:         $file_name = $3.'/'.$4;
 4611:     }
 4612:     if (wantarray) {
 4613: 	return ($type,$udom,$unum,$file_name,$group);
 4614:     }
 4615:     return $type;
 4616: }
 4617: 
 4618: sub is_portfolio_url {
 4619:     my ($url) = @_;
 4620:     return scalar(&parse_portfolio_url($url));
 4621: }
 4622: 
 4623: sub is_portfolio_file {
 4624:     my ($file) = @_;
 4625:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4626:         return 1;
 4627:     }
 4628:     return;
 4629: }
 4630: 
 4631: sub usertools_access {
 4632:     my ($uname,$udom,$tool,$action,$context) = @_;
 4633:     my ($access,%tools);
 4634:     if ($context eq '') {
 4635:         $context = 'tools';
 4636:     }
 4637:     if ($context eq 'requestcourses') {
 4638:         %tools = (
 4639:                       official   => 1,
 4640:                       unofficial => 1,
 4641:                       community  => 1,
 4642:                  );
 4643:     } else {
 4644:         %tools = (
 4645:                       aboutme   => 1,
 4646:                       blog      => 1,
 4647:                       portfolio => 1,
 4648:                  );
 4649:     }
 4650:     return if (!defined($tools{$tool}));
 4651: 
 4652:     if ((!defined($udom)) || (!defined($uname))) {
 4653:         $udom = $env{'user.domain'};
 4654:         $uname = $env{'user.name'};
 4655:     }
 4656: 
 4657:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4658:         if ($action ne 'reload') {
 4659:             if ($context eq 'requestcourses') {
 4660:                 return $env{'environment.canrequest.'.$tool};
 4661:             } else {
 4662:                 return $env{'environment.availabletools.'.$tool};
 4663:             }
 4664:         }
 4665:     }
 4666: 
 4667:     my ($toolstatus,$inststatus);
 4668: 
 4669:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 4670:          ($action ne 'reload')) {
 4671:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 4672:         $inststatus = $env{'environment.inststatus'};
 4673:     } else {
 4674:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool);
 4675:         $toolstatus = $userenv{$context.'.'.$tool};
 4676:         $inststatus = $userenv{'inststatus'};
 4677:     }
 4678: 
 4679:     if ($toolstatus ne '') {
 4680:         if ($toolstatus) {
 4681:             $access = 1;
 4682:         } else {
 4683:             $access = 0;
 4684:         }
 4685:         return $access;
 4686:     }
 4687: 
 4688:     my $is_adv = &is_advanced_user($udom,$uname);
 4689:     my %domdef = &get_domain_defaults($udom);
 4690:     if (ref($domdef{$tool}) eq 'HASH') {
 4691:         if ($is_adv) {
 4692:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 4693:                 if ($domdef{$tool}{'_LC_adv'}) { 
 4694:                     $access = 1;
 4695:                 } else {
 4696:                     $access = 0;
 4697:                 }
 4698:                 return $access;
 4699:             }
 4700:         }
 4701:         if ($inststatus ne '') {
 4702:             my ($hasaccess,$hasnoaccess);
 4703:             foreach my $affiliation (split(/:/,$inststatus)) {
 4704:                 if ($domdef{$tool}{$affiliation} ne '') { 
 4705:                     if ($domdef{$tool}{$affiliation}) {
 4706:                         $hasaccess = 1;
 4707:                     } else {
 4708:                         $hasnoaccess = 1;
 4709:                     }
 4710:                 }
 4711:             }
 4712:             if ($hasaccess || $hasnoaccess) {
 4713:                 if ($hasaccess) {
 4714:                     $access = 1;
 4715:                 } elsif ($hasnoaccess) {
 4716:                     $access = 0; 
 4717:                 }
 4718:                 return $access;
 4719:             }
 4720:         } else {
 4721:             if ($domdef{$tool}{'default'} ne '') {
 4722:                 if ($domdef{$tool}{'default'}) {
 4723:                     $access = 1;
 4724:                 } elsif ($domdef{$tool}{'default'} == 0) {
 4725:                     $access = 0;
 4726:                 }
 4727:                 return $access;
 4728:             }
 4729:         }
 4730:     } else {
 4731:         if ($context eq 'tools') {
 4732:             $access = 1;
 4733:         } else {
 4734:             $access = 0;
 4735:         }
 4736:         return $access;
 4737:     }
 4738: }
 4739: 
 4740: sub is_advanced_user {
 4741:     my ($udom,$uname) = @_;
 4742:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 4743:     my %allroles;
 4744:     my $is_adv;
 4745:     foreach my $role (keys(%roleshash)) {
 4746:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 4747:         my $area = '/'.$tdomain.'/'.$trest;
 4748:         if ($sec ne '') {
 4749:             $area .= '/'.$sec;
 4750:         }
 4751:         if (($area ne '') && ($trole ne '')) {
 4752:             my $spec=$trole.'.'.$area;
 4753:             if ($trole =~ /^cr\//) {
 4754:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4755:             } elsif ($trole ne 'gr') {
 4756:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4757:             }
 4758:         }
 4759:     }
 4760:     foreach my $role (keys(%allroles)) {
 4761:         last if ($is_adv);
 4762:         foreach my $item (split(/:/,$allroles{$role})) {
 4763:             if ($item ne '') {
 4764:                 my ($privilege,$restrictions)=split(/&/,$item);
 4765:                 if ($privilege eq 'adv') {
 4766:                     $is_adv = 1;
 4767:                     last;
 4768:                 }
 4769:             }
 4770:         }
 4771:     }
 4772:     return $is_adv;
 4773: }
 4774: 
 4775: # ---------------------------------------------- Custom access rule evaluation
 4776: 
 4777: sub customaccess {
 4778:     my ($priv,$uri)=@_;
 4779:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4780:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4781:     $udom = &LONCAPA::clean_domain($udom);
 4782:     $ucrs = &LONCAPA::clean_username($ucrs);
 4783:     my $access=0;
 4784:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4785: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4786: 	if ($type eq 'user') {
 4787: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4788: 		my ($tdom,$tuname)=split(m{/},$scope);
 4789: 		if ($tdom) {
 4790: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4791: 		}
 4792: 		if ($tuname) {
 4793: 		    if ($tuname ne $env{'user.name'}) { next; }
 4794: 		}
 4795: 		$access=($effect eq 'allow');
 4796: 		last;
 4797: 	    }
 4798: 	} else {
 4799: 	    if ($role) {
 4800: 		if ($role ne $urole) { next; }
 4801: 	    }
 4802: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4803: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4804: 		if ($tdom) {
 4805: 		    if ($tdom ne $udom) { next; }
 4806: 		}
 4807: 		if ($tcrs) {
 4808: 		    if ($tcrs ne $ucrs) { next; }
 4809: 		}
 4810: 		if ($tsec) {
 4811: 		    if ($tsec ne $usec) { next; }
 4812: 		}
 4813: 		$access=($effect eq 'allow');
 4814: 		last;
 4815: 	    }
 4816: 	    if ($realm eq '' && $role eq '') {
 4817: 		$access=($effect eq 'allow');
 4818: 	    }
 4819: 	}
 4820:     }
 4821:     return $access;
 4822: }
 4823: 
 4824: # ------------------------------------------------- Check for a user privilege
 4825: 
 4826: sub allowed {
 4827:     my ($priv,$uri,$symb,$role)=@_;
 4828:     my $ver_orguri=$uri;
 4829:     $uri=&deversion($uri);
 4830:     my $orguri=$uri;
 4831:     $uri=&declutter($uri);
 4832: 
 4833:     if ($priv eq 'evb') {
 4834: # Evade communication block restrictions for specified role in a course
 4835:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4836:             return $1;
 4837:         } else {
 4838:             return;
 4839:         }
 4840:     }
 4841: 
 4842:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4843: # Free bre access to adm and meta resources
 4844:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4845: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4846: 	&& ($priv eq 'bre')) {
 4847: 	return 'F';
 4848:     }
 4849: 
 4850: # Free bre access to user's own portfolio contents
 4851:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4852:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4853: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4854:         my %setters;
 4855:         my ($startblock,$endblock) = 
 4856:             &Apache::loncommon::blockcheck(\%setters,'port');
 4857:         if ($startblock && $endblock) {
 4858:             return 'B';
 4859:         } else {
 4860:             return 'F';
 4861:         }
 4862:     }
 4863: 
 4864: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4865:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4866:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4867:         if (exists($env{'request.course.id'})) {
 4868:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4869:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4870:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4871:                 my $courseprivid=$env{'request.course.id'};
 4872:                 $courseprivid=~s/\_/\//;
 4873:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4874:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4875:                     return $1; 
 4876:                 } else {
 4877:                     if ($env{'request.course.sec'}) {
 4878:                         $courseprivid.='/'.$env{'request.course.sec'};
 4879:                     }
 4880:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4881:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4882:                         return $2;
 4883:                     }
 4884:                 }
 4885:             }
 4886:         }
 4887:     }
 4888: 
 4889: # Free bre to public access
 4890: 
 4891:     if ($priv eq 'bre') {
 4892:         my $copyright=&metadata($uri,'copyright');
 4893: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4894:            return 'F'; 
 4895:         }
 4896:         if ($copyright eq 'priv') {
 4897:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4898: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4899: 		return '';
 4900:             }
 4901:         }
 4902:         if ($copyright eq 'domain') {
 4903:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4904: 	    unless (($env{'user.domain'} eq $1) ||
 4905:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4906: 		return '';
 4907:             }
 4908:         }
 4909:         if ($env{'request.role'}=~ /li\.\//) {
 4910:             # Library role, so allow browsing of resources in this domain.
 4911:             return 'F';
 4912:         }
 4913:         if ($copyright eq 'custom') {
 4914: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4915:         }
 4916:     }
 4917:     # Domain coordinator is trying to create a course
 4918:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4919:         # uri is the requested domain in this case.
 4920:         # comparison to 'request.role.domain' shows if the user has selected
 4921:         # a role of dc for the domain in question.
 4922:         return 'F' if ($uri eq $env{'request.role.domain'});
 4923:     }
 4924: 
 4925:     my $thisallowed='';
 4926:     my $statecond=0;
 4927:     my $courseprivid='';
 4928: 
 4929: # Course
 4930: 
 4931:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4932:        $thisallowed.=$1;
 4933:     }
 4934: 
 4935: # Domain
 4936: 
 4937:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4938:        =~/\Q$priv\E\&([^\:]*)/) {
 4939:        $thisallowed.=$1;
 4940:     }
 4941: 
 4942: # Course: uri itself is a course
 4943:     my $courseuri=$uri;
 4944:     $courseuri=~s/\_(\d)/\/$1/;
 4945:     $courseuri=~s/^([^\/])/\/$1/;
 4946: 
 4947:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 4948:        =~/\Q$priv\E\&([^\:]*)/) {
 4949:        $thisallowed.=$1;
 4950:     }
 4951: 
 4952: # URI is an uploaded document for this course, default permissions don't matter
 4953: # not allowing 'edit' access (editupload) to uploaded course docs
 4954:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 4955: 	$thisallowed='';
 4956:         my ($match)=&is_on_map($uri);
 4957:         if ($match) {
 4958:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 4959:                   =~/\Q$priv\E\&([^\:]*)/) {
 4960:                 $thisallowed.=$1;
 4961:             }
 4962:         } else {
 4963:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 4964:             if ($refuri) {
 4965:                 if ($refuri =~ m|^/adm/|) {
 4966:                     $thisallowed='F';
 4967:                 } else {
 4968:                     $refuri=&declutter($refuri);
 4969:                     my ($match) = &is_on_map($refuri);
 4970:                     if ($match) {
 4971:                         $thisallowed='F';
 4972:                     }
 4973:                 }
 4974:             }
 4975:         }
 4976:     }
 4977: 
 4978:     if ($priv eq 'bre'
 4979: 	&& $thisallowed ne 'F' 
 4980: 	&& $thisallowed ne '2'
 4981: 	&& &is_portfolio_url($uri)) {
 4982: 	$thisallowed = &portfolio_access($uri);
 4983:     }
 4984:     
 4985: # Full access at system, domain or course-wide level? Exit.
 4986:     if ($thisallowed=~/F/) {
 4987: 	return 'F';
 4988:     }
 4989: 
 4990: # If this is generating or modifying users, exit with special codes
 4991: 
 4992:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4993: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4994: 	    my ($audom,$auname)=split('/',$uri);
 4995: # no author name given, so this just checks on the general right to make a co-author in this domain
 4996: 	    unless ($auname) { return $thisallowed; }
 4997: # an author name is given, so we are about to actually make a co-author for a certain account
 4998: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4999: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 5000: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 5001: 	}
 5002: 	return $thisallowed;
 5003:     }
 5004: #
 5005: # Gathered so far: system, domain and course wide privileges
 5006: #
 5007: # Course: See if uri or referer is an individual resource that is part of 
 5008: # the course
 5009: 
 5010:     if ($env{'request.course.id'}) {
 5011: 
 5012:        $courseprivid=$env{'request.course.id'};
 5013:        if ($env{'request.course.sec'}) {
 5014:           $courseprivid.='/'.$env{'request.course.sec'};
 5015:        }
 5016:        $courseprivid=~s/\_/\//;
 5017:        my $checkreferer=1;
 5018:        my ($match,$cond)=&is_on_map($uri);
 5019:        if ($match) {
 5020:            $statecond=$cond;
 5021:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 5022:                =~/\Q$priv\E\&([^\:]*)/) {
 5023:                $thisallowed.=$1;
 5024:                $checkreferer=0;
 5025:            }
 5026:        }
 5027:        
 5028:        if ($checkreferer) {
 5029: 	  my $refuri=$env{'httpref.'.$orguri};
 5030:             unless ($refuri) {
 5031:                 foreach my $key (keys(%env)) {
 5032: 		    if ($key=~/^httpref\..*\*/) {
 5033: 			my $pattern=$key;
 5034:                         $pattern=~s/^httpref\.\/res\///;
 5035:                         $pattern=~s/\*/\[\^\/\]\+/g;
 5036:                         $pattern=~s/\//\\\//g;
 5037:                         if ($orguri=~/$pattern/) {
 5038: 			    $refuri=$env{$key};
 5039:                         }
 5040:                     }
 5041:                 }
 5042:             }
 5043: 
 5044:          if ($refuri) { 
 5045: 	  $refuri=&declutter($refuri);
 5046:           my ($match,$cond)=&is_on_map($refuri);
 5047:             if ($match) {
 5048:               my $refstatecond=$cond;
 5049:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 5050:                   =~/\Q$priv\E\&([^\:]*)/) {
 5051:                   $thisallowed.=$1;
 5052:                   $uri=$refuri;
 5053:                   $statecond=$refstatecond;
 5054:               }
 5055:           }
 5056:         }
 5057:        }
 5058:    }
 5059: 
 5060: #
 5061: # Gathered now: all privileges that could apply, and condition number
 5062: # 
 5063: #
 5064: # Full or no access?
 5065: #
 5066: 
 5067:     if ($thisallowed=~/F/) {
 5068: 	return 'F';
 5069:     }
 5070: 
 5071:     unless ($thisallowed) {
 5072:         return '';
 5073:     }
 5074: 
 5075: # Restrictions exist, deal with them
 5076: #
 5077: #   C:according to course preferences
 5078: #   R:according to resource settings
 5079: #   L:unless locked
 5080: #   X:according to user session state
 5081: #
 5082: 
 5083: # Possibly locked functionality, check all courses
 5084: # Locks might take effect only after 10 minutes cache expiration for other
 5085: # courses, and 2 minutes for current course
 5086: 
 5087:     my $envkey;
 5088:     if ($thisallowed=~/L/) {
 5089:         foreach $envkey (keys(%env)) {
 5090:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 5091:                my $courseid=$2;
 5092:                my $roleid=$1.'.'.$2;
 5093:                $courseid=~s/^\///;
 5094:                my $expiretime=600;
 5095:                if ($env{'request.role'} eq $roleid) {
 5096: 		  $expiretime=120;
 5097:                }
 5098: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 5099:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 5100:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 5101: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 5102:                }
 5103:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5104:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 5105: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 5106:                        &log($env{'user.domain'},$env{'user.name'},
 5107:                             $env{'user.home'},
 5108:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 5109:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5110:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5111: 		       return '';
 5112:                    }
 5113:                }
 5114:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5115:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 5116: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 5117:                        &log($env{'user.domain'},$env{'user.name'},
 5118:                             $env{'user.home'},
 5119:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 5120:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5121:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5122: 		       return '';
 5123:                    }
 5124:                }
 5125: 	   }
 5126:        }
 5127:     }
 5128:    
 5129: #
 5130: # Rest of the restrictions depend on selected course
 5131: #
 5132: 
 5133:     unless ($env{'request.course.id'}) {
 5134: 	if ($thisallowed eq 'A') {
 5135: 	    return 'A';
 5136:         } elsif ($thisallowed eq 'B') {
 5137:             return 'B';
 5138: 	} else {
 5139: 	    return '1';
 5140: 	}
 5141:     }
 5142: 
 5143: #
 5144: # Now user is definitely in a course
 5145: #
 5146: 
 5147: 
 5148: # Course preferences
 5149: 
 5150:    if ($thisallowed=~/C/) {
 5151:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5152:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 5153:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 5154: 	   =~/\Q$rolecode\E/) {
 5155: 	   if ($priv ne 'pch') { 
 5156: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5157: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 5158: 			$env{'request.course.id'});
 5159: 	   }
 5160:            return '';
 5161:        }
 5162: 
 5163:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 5164: 	   =~/\Q$unamedom\E/) {
 5165: 	   if ($priv ne 'pch') { 
 5166: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 5167: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 5168: 			$env{'request.course.id'});
 5169: 	   }
 5170:            return '';
 5171:        }
 5172:    }
 5173: 
 5174: # Resource preferences
 5175: 
 5176:    if ($thisallowed=~/R/) {
 5177:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5178:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 5179: 	   if ($priv ne 'pch') { 
 5180: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5181: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 5182: 	   }
 5183: 	   return '';
 5184:        }
 5185:    }
 5186: 
 5187: # Restricted by state or randomout?
 5188: 
 5189:    if ($thisallowed=~/X/) {
 5190:       if ($env{'acc.randomout'}) {
 5191: 	 if (!$symb) { $symb=&symbread($uri,1); }
 5192:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 5193:             return ''; 
 5194:          }
 5195:       }
 5196:       if (&condval($statecond)) {
 5197: 	 return '2';
 5198:       } else {
 5199:          return '';
 5200:       }
 5201:    }
 5202: 
 5203:     if ($thisallowed eq 'A') {
 5204: 	return 'A';
 5205:     } elsif ($thisallowed eq 'B') {
 5206:         return 'B';
 5207:     }
 5208:    return 'F';
 5209: }
 5210: 
 5211: sub split_uri_for_cond {
 5212:     my $uri=&deversion(&declutter(shift));
 5213:     my @uriparts=split(/\//,$uri);
 5214:     my $filename=pop(@uriparts);
 5215:     my $pathname=join('/',@uriparts);
 5216:     return ($pathname,$filename);
 5217: }
 5218: # --------------------------------------------------- Is a resource on the map?
 5219: 
 5220: sub is_on_map {
 5221:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 5222:     #Trying to find the conditional for the file
 5223:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 5224: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 5225:     if ($match) {
 5226: 	return (1,$1);
 5227:     } else {
 5228: 	return (0,0);
 5229:     }
 5230: }
 5231: 
 5232: # --------------------------------------------------------- Get symb from alias
 5233: 
 5234: sub get_symb_from_alias {
 5235:     my $symb=shift;
 5236:     my ($map,$resid,$url)=&decode_symb($symb);
 5237: # Already is a symb
 5238:     if ($url) { return $symb; }
 5239: # Must be an alias
 5240:     my $aliassymb='';
 5241:     my %bighash;
 5242:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5243:                             &GDBM_READER(),0640)) {
 5244:         my $rid=$bighash{'mapalias_'.$symb};
 5245: 	if ($rid) {
 5246: 	    my ($mapid,$resid)=split(/\./,$rid);
 5247: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 5248: 				    $resid,$bighash{'src_'.$rid});
 5249: 	}
 5250:         untie %bighash;
 5251:     }
 5252:     return $aliassymb;
 5253: }
 5254: 
 5255: # ----------------------------------------------------------------- Define Role
 5256: 
 5257: sub definerole {
 5258:   if (allowed('mcr','/')) {
 5259:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 5260:     foreach my $role (split(':',$sysrole)) {
 5261: 	my ($crole,$cqual)=split(/\&/,$role);
 5262:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 5263:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 5264: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5265:                return "refused:s:$crole&$cqual"; 
 5266:             }
 5267:         }
 5268:     }
 5269:     foreach my $role (split(':',$domrole)) {
 5270: 	my ($crole,$cqual)=split(/\&/,$role);
 5271:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 5272:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 5273: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 5274:                return "refused:d:$crole&$cqual"; 
 5275:             }
 5276:         }
 5277:     }
 5278:     foreach my $role (split(':',$courole)) {
 5279: 	my ($crole,$cqual)=split(/\&/,$role);
 5280:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 5281:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 5282: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5283:                return "refused:c:$crole&$cqual"; 
 5284:             }
 5285:         }
 5286:     }
 5287:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5288:                 "$env{'user.domain'}:$env{'user.name'}:".
 5289: 	        "rolesdef_$rolename=".
 5290:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 5291:     return reply($command,$env{'user.home'});
 5292:   } else {
 5293:     return 'refused';
 5294:   }
 5295: }
 5296: 
 5297: # ---------------- Make a metadata query against the network of library servers
 5298: 
 5299: sub metadata_query {
 5300:     my ($query,$custom,$customshow,$server_array)=@_;
 5301:     my %rhash;
 5302:     my %libserv = &all_library();
 5303:     my @server_list = (defined($server_array) ? @$server_array
 5304:                                               : keys(%libserv) );
 5305:     for my $server (@server_list) {
 5306: 	unless ($custom or $customshow) {
 5307: 	    my $reply=&reply("querysend:".&escape($query),$server);
 5308: 	    $rhash{$server}=$reply;
 5309: 	}
 5310: 	else {
 5311: 	    my $reply=&reply("querysend:".&escape($query).':'.
 5312: 			     &escape($custom).':'.&escape($customshow),
 5313: 			     $server);
 5314: 	    $rhash{$server}=$reply;
 5315: 	}
 5316:     }
 5317:     return \%rhash;
 5318: }
 5319: 
 5320: # ----------------------------------------- Send log queries and wait for reply
 5321: 
 5322: sub log_query {
 5323:     my ($uname,$udom,$query,%filters)=@_;
 5324:     my $uhome=&homeserver($uname,$udom);
 5325:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 5326:     my $uhost=&hostname($uhome);
 5327:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 5328:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 5329:                        $uhome);
 5330:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 5331:     return get_query_reply($queryid);
 5332: }
 5333: 
 5334: # -------------------------- Update MySQL table for portfolio file
 5335: 
 5336: sub update_portfolio_table {
 5337:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 5338:     if ($group ne '') {
 5339:         $file_name =~s /^\Q$group\E//;
 5340:     }
 5341:     my $homeserver = &homeserver($uname,$udom);
 5342:     my $queryid=
 5343:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 5344:                ':'.&escape($file_name).':'.$action,$homeserver);
 5345:     my $reply = &get_query_reply($queryid);
 5346:     return $reply;
 5347: }
 5348: 
 5349: # -------------------------- Update MySQL allusers table
 5350: 
 5351: sub update_allusers_table {
 5352:     my ($uname,$udom,$names) = @_;
 5353:     my $homeserver = &homeserver($uname,$udom);
 5354:     my $queryid=
 5355:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 5356:                'lastname='.&escape($names->{'lastname'}).'%%'.
 5357:                'firstname='.&escape($names->{'firstname'}).'%%'.
 5358:                'middlename='.&escape($names->{'middlename'}).'%%'.
 5359:                'generation='.&escape($names->{'generation'}).'%%'.
 5360:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 5361:                'id='.&escape($names->{'id'}),$homeserver);
 5362:     my $reply = &get_query_reply($queryid);
 5363:     return $reply;
 5364: }
 5365: 
 5366: # ------- Request retrieval of institutional classlists for course(s)
 5367: 
 5368: sub fetch_enrollment_query {
 5369:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 5370:     my $homeserver;
 5371:     my $maxtries = 1;
 5372:     if ($context eq 'automated') {
 5373:         $homeserver = $perlvar{'lonHostID'};
 5374:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 5375:     } else {
 5376:         $homeserver = &homeserver($cnum,$dom);
 5377:     }
 5378:     my $host=&hostname($homeserver);
 5379:     my $cmd = '';
 5380:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5381:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5382:     }
 5383:     $cmd =~ s/%%$//;
 5384:     $cmd = &escape($cmd);
 5385:     my $query = 'fetchenrollment';
 5386:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 5387:     unless ($queryid=~/^\Q$host\E\_/) { 
 5388:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 5389:         return 'error: '.$queryid;
 5390:     }
 5391:     my $reply = &get_query_reply($queryid);
 5392:     my $tries = 1;
 5393:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5394:         $reply = &get_query_reply($queryid);
 5395:         $tries ++;
 5396:     }
 5397:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5398:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5399:     } else {
 5400:         my @responses = split(/:/,$reply);
 5401:         if ($homeserver eq $perlvar{'lonHostID'}) {
 5402:             foreach my $line (@responses) {
 5403:                 my ($key,$value) = split(/=/,$line,2);
 5404:                 $$replyref{$key} = $value;
 5405:             }
 5406:         } else {
 5407:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 5408:             foreach my $line (@responses) {
 5409:                 my ($key,$value) = split(/=/,$line);
 5410:                 $$replyref{$key} = $value;
 5411:                 if ($value > 0) {
 5412:                     foreach my $item (@{$$affiliatesref{$key}}) {
 5413:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 5414:                         my $destname = $pathname.'/'.$filename;
 5415:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 5416:                         if ($xml_classlist =~ /^error/) {
 5417:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 5418:                         } else {
 5419:                             if ( open(FILE,">$destname") ) {
 5420:                                 print FILE &unescape($xml_classlist);
 5421:                                 close(FILE);
 5422:                             } else {
 5423:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 5424:                             }
 5425:                         }
 5426:                     }
 5427:                 }
 5428:             }
 5429:         }
 5430:         return 'ok';
 5431:     }
 5432:     return 'error';
 5433: }
 5434: 
 5435: sub get_query_reply {
 5436:     my $queryid=shift;
 5437:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 5438:     my $reply='';
 5439:     for (1..100) {
 5440: 	sleep 2;
 5441:         if (-e $replyfile.'.end') {
 5442: 	    if (open(my $fh,$replyfile)) {
 5443: 		$reply = join('',<$fh>);
 5444: 		close($fh);
 5445: 	   } else { return 'error: reply_file_error'; }
 5446:            return &unescape($reply);
 5447: 	}
 5448:     }
 5449:     return 'timeout:'.$queryid;
 5450: }
 5451: 
 5452: sub courselog_query {
 5453: #
 5454: # possible filters:
 5455: # url: url or symb
 5456: # username
 5457: # domain
 5458: # action: view, submit, grade
 5459: # start: timestamp
 5460: # end: timestamp
 5461: #
 5462:     my (%filters)=@_;
 5463:     unless ($env{'request.course.id'}) { return 'no_course'; }
 5464:     if ($filters{'url'}) {
 5465: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 5466:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 5467:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 5468:     }
 5469:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5470:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5471:     return &log_query($cname,$cdom,'courselog',%filters);
 5472: }
 5473: 
 5474: sub userlog_query {
 5475: #
 5476: # possible filters:
 5477: # action: log check role
 5478: # start: timestamp
 5479: # end: timestamp
 5480: #
 5481:     my ($uname,$udom,%filters)=@_;
 5482:     return &log_query($uname,$udom,'userlog',%filters);
 5483: }
 5484: 
 5485: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 5486: 
 5487: sub auto_run {
 5488:     my ($cnum,$cdom) = @_;
 5489:     my $response = 0;
 5490:     my $settings;
 5491:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 5492:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5493:         $settings = $domconfig{'autoenroll'};
 5494:         if ($settings->{'run'} eq '1') {
 5495:             $response = 1;
 5496:         }
 5497:     } else {
 5498:         my $homeserver;
 5499:         if (&is_course($cdom,$cnum)) {
 5500:             $homeserver = &homeserver($cnum,$cdom);
 5501:         } else {
 5502:             $homeserver = &domain($cdom,'primary');
 5503:         }
 5504:         if ($homeserver ne 'no_host') {
 5505:             $response = &reply('autorun:'.$cdom,$homeserver);
 5506:         }
 5507:     }
 5508:     return $response;
 5509: }
 5510: 
 5511: sub auto_get_sections {
 5512:     my ($cnum,$cdom,$inst_coursecode) = @_;
 5513:     my $homeserver;
 5514:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 5515:         $homeserver = &homeserver($cnum,$cdom);
 5516:     }
 5517:     if (!defined($homeserver)) { 
 5518:         if ($cdom =~ /^$match_domain$/) {
 5519:             $homeserver = &domain($cdom,'primary');
 5520:         }
 5521:     }
 5522:     my @secs;
 5523:     if (defined($homeserver)) {
 5524:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 5525:         unless ($response eq 'refused') {
 5526:             @secs = split(/:/,$response);
 5527:         }
 5528:     }
 5529:     return @secs;
 5530: }
 5531: 
 5532: sub auto_new_course {
 5533:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 5534:     my $homeserver = &homeserver($cnum,$cdom);
 5535:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 5536:     return $response;
 5537: }
 5538: 
 5539: sub auto_validate_courseID {
 5540:     my ($cnum,$cdom,$inst_course_id) = @_;
 5541:     my $homeserver = &homeserver($cnum,$cdom);
 5542:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5543:     return $response;
 5544: }
 5545: 
 5546: sub auto_validate_instcode {
 5547:     my ($cnum,$cdom,$instcode,$owner) = @_;
 5548:     my ($homeserver,$response);
 5549:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5550:         $homeserver = &homeserver($cnum,$cdom);
 5551:     }
 5552:     if (!defined($homeserver)) {
 5553:         if ($cdom =~ /^$match_domain$/) {
 5554:             $homeserver = &domain($cdom,'primary');
 5555:         }
 5556:     }
 5557:     my $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 5558:                            &escape($instcode).':'.&escape($owner),$homeserver));
 5559:     return $response;
 5560: }
 5561: 
 5562: sub auto_create_password {
 5563:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5564:     my ($homeserver,$response);
 5565:     my $create_passwd = 0;
 5566:     my $authchk = '';
 5567:     if ($udom =~ /^$match_domain$/) {
 5568:         $homeserver = &domain($udom,'primary');
 5569:     }
 5570:     if ($homeserver eq '') {
 5571:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5572:             $homeserver = &homeserver($cnum,$cdom);
 5573:         }
 5574:     }
 5575:     if ($homeserver eq '') {
 5576:         $authchk = 'nodomain';
 5577:     } else {
 5578:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5579:         if ($response eq 'refused') {
 5580:             $authchk = 'refused';
 5581:         } else {
 5582:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5583:         }
 5584:     }
 5585:     return ($authparam,$create_passwd,$authchk);
 5586: }
 5587: 
 5588: sub auto_photo_permission {
 5589:     my ($cnum,$cdom,$students) = @_;
 5590:     my $homeserver = &homeserver($cnum,$cdom);
 5591:     my ($outcome,$perm_reqd,$conditions) = 
 5592: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5593:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5594: 	return (undef,undef);
 5595:     }
 5596:     return ($outcome,$perm_reqd,$conditions);
 5597: }
 5598: 
 5599: sub auto_checkphotos {
 5600:     my ($uname,$udom,$pid) = @_;
 5601:     my $homeserver = &homeserver($uname,$udom);
 5602:     my ($result,$resulttype);
 5603:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5604: 				   &escape($uname).':'.&escape($pid),
 5605: 				   $homeserver));
 5606:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5607: 	return (undef,undef);
 5608:     }
 5609:     if ($outcome) {
 5610:         ($result,$resulttype) = split(/:/,$outcome);
 5611:     } 
 5612:     return ($result,$resulttype);
 5613: }
 5614: 
 5615: sub auto_photochoice {
 5616:     my ($cnum,$cdom) = @_;
 5617:     my $homeserver = &homeserver($cnum,$cdom);
 5618:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5619: 						       &escape($cdom),
 5620: 						       $homeserver)));
 5621:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5622: 	return (undef,undef);
 5623:     }
 5624:     return ($update,$comment);
 5625: }
 5626: 
 5627: sub auto_photoupdate {
 5628:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5629:     my $homeserver = &homeserver($cnum,$dom);
 5630:     my $host=&hostname($homeserver);
 5631:     my $cmd = '';
 5632:     my $maxtries = 1;
 5633:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5634:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5635:     }
 5636:     $cmd =~ s/%%$//;
 5637:     $cmd = &escape($cmd);
 5638:     my $query = 'institutionalphotos';
 5639:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5640:     unless ($queryid=~/^\Q$host\E\_/) {
 5641:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5642:         return 'error: '.$queryid;
 5643:     }
 5644:     my $reply = &get_query_reply($queryid);
 5645:     my $tries = 1;
 5646:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5647:         $reply = &get_query_reply($queryid);
 5648:         $tries ++;
 5649:     }
 5650:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5651:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5652:     } else {
 5653:         my @responses = split(/:/,$reply);
 5654:         my $outcome = shift(@responses); 
 5655:         foreach my $item (@responses) {
 5656:             my ($key,$value) = split(/=/,$item);
 5657:             $$photo{$key} = $value;
 5658:         }
 5659:         return $outcome;
 5660:     }
 5661:     return 'error';
 5662: }
 5663: 
 5664: sub auto_instcode_format {
 5665:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5666: 	$cat_order) = @_;
 5667:     my $courses = '';
 5668:     my @homeservers;
 5669:     if ($caller eq 'global') {
 5670: 	my %servers = &get_servers($codedom,'library');
 5671: 	foreach my $tryserver (keys(%servers)) {
 5672: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5673: 		push(@homeservers,$tryserver);
 5674: 	    }
 5675:         }
 5676:     } else {
 5677:         push(@homeservers,&homeserver($caller,$codedom));
 5678:     }
 5679:     foreach my $code (keys(%{$instcodes})) {
 5680:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5681:     }
 5682:     chop($courses);
 5683:     my $ok_response = 0;
 5684:     my $response;
 5685:     while (@homeservers > 0 && $ok_response == 0) {
 5686:         my $server = shift(@homeservers); 
 5687:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5688:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5689:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5690: 		split(/:/,$response);
 5691:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5692:             push(@{$codetitles},&str2array($codetitles_str));
 5693:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5694:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5695:             $ok_response = 1;
 5696:         }
 5697:     }
 5698:     if ($ok_response) {
 5699:         return 'ok';
 5700:     } else {
 5701:         return $response;
 5702:     }
 5703: }
 5704: 
 5705: sub auto_instcode_defaults {
 5706:     my ($domain,$returnhash,$code_order) = @_;
 5707:     my @homeservers;
 5708: 
 5709:     my %servers = &get_servers($domain,'library');
 5710:     foreach my $tryserver (keys(%servers)) {
 5711: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5712: 	    push(@homeservers,$tryserver);
 5713: 	}
 5714:     }
 5715: 
 5716:     my $response;
 5717:     foreach my $server (@homeservers) {
 5718:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5719:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5720: 	
 5721: 	foreach my $pair (split(/\&/,$response)) {
 5722: 	    my ($name,$value)=split(/\=/,$pair);
 5723: 	    if ($name eq 'code_order') {
 5724: 		@{$code_order} = split(/\&/,&unescape($value));
 5725: 	    } else {
 5726: 		$returnhash->{&unescape($name)}=&unescape($value);
 5727: 	    }
 5728: 	}
 5729: 	return 'ok';
 5730:     }
 5731: 
 5732:     return $response;
 5733: }
 5734: 
 5735: sub auto_possible_instcodes {
 5736:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 5737:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 5738:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 5739:         return;
 5740:     }
 5741:     my (@homeservers,$uhome);
 5742:     if (defined(&domain($domain,'primary'))) {
 5743:         $uhome=&domain($domain,'primary');
 5744:         push(@homeservers,&domain($domain,'primary'));
 5745:     } else {
 5746:         my %servers = &get_servers($domain,'library');
 5747:         foreach my $tryserver (keys(%servers)) {
 5748:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5749:                 push(@homeservers,$tryserver);
 5750:             }
 5751:         }
 5752:     }
 5753:     my $response;
 5754:     foreach my $server (@homeservers) {
 5755:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 5756:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5757:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 5758:             split(':',$response);
 5759:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 5760:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 5761:         foreach my $item (split('&',$cat_title)) {   
 5762:             my ($name,$value)=split('=',$item);
 5763:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 5764:         }
 5765:         foreach my $item (split('&',$cat_order)) {
 5766:             my ($name,$value)=split('=',$item);
 5767:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 5768:         }
 5769:         return 'ok';
 5770:     }
 5771:     return $response;
 5772: }
 5773: 
 5774: sub auto_courserequest_checks {
 5775:     my ($dom) = @_;
 5776:     my %validations;
 5777:     return %validations; 
 5778: }
 5779: 
 5780: sub auto_validate_class_sec {
 5781:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5782:     my $homeserver = &homeserver($cnum,$cdom);
 5783:     my $ownerlist;
 5784:     if (ref($owners) eq 'ARRAY') {
 5785:         $ownerlist = join(',',@{$owners});
 5786:     } else {
 5787:         $ownerlist = $owners;
 5788:     }
 5789:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 5790:                         &escape($ownerlist).':'.$cdom,$homeserver);
 5791:     return $response;
 5792: }
 5793: 
 5794: # ------------------------------------------------------- Course Group routines
 5795: 
 5796: sub get_coursegroups {
 5797:     my ($cdom,$cnum,$group,$namespace) = @_;
 5798:     return(&dump($namespace,$cdom,$cnum,$group));
 5799: }
 5800: 
 5801: sub modify_coursegroup {
 5802:     my ($cdom,$cnum,$groupsettings) = @_;
 5803:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 5804: }
 5805: 
 5806: sub toggle_coursegroup_status {
 5807:     my ($cdom,$cnum,$group,$action) = @_;
 5808:     my ($from_namespace,$to_namespace);
 5809:     if ($action eq 'delete') {
 5810:         $from_namespace = 'coursegroups';
 5811:         $to_namespace = 'deleted_groups';
 5812:     } else {
 5813:         $from_namespace = 'deleted_groups';
 5814:         $to_namespace = 'coursegroups';
 5815:     }
 5816:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 5817:     if (my $tmp = &error(%curr_group)) {
 5818:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 5819:         return ('read error',$tmp);
 5820:     } else {
 5821:         my %savedsettings = %curr_group; 
 5822:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 5823:         my $deloutcome;
 5824:         if ($result eq 'ok') {
 5825:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 5826:         } else {
 5827:             return ('write error',$result);
 5828:         }
 5829:         if ($deloutcome eq 'ok') {
 5830:             return 'ok';
 5831:         } else {
 5832:             return ('delete error',$deloutcome);
 5833:         }
 5834:     }
 5835: }
 5836: 
 5837: sub modify_group_roles {
 5838:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 5839:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 5840:     my $role = 'gr/'.&escape($userprivs);
 5841:     my ($uname,$udom) = split(/:/,$user);
 5842:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 5843:     if ($result eq 'ok') {
 5844:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 5845:     }
 5846:     return $result;
 5847: }
 5848: 
 5849: sub modify_coursegroup_membership {
 5850:     my ($cdom,$cnum,$membership) = @_;
 5851:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 5852:     return $result;
 5853: }
 5854: 
 5855: sub get_active_groups {
 5856:     my ($udom,$uname,$cdom,$cnum) = @_;
 5857:     my $now = time;
 5858:     my %groups = ();
 5859:     foreach my $key (keys(%env)) {
 5860:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 5861:             my ($start,$end) = split(/\./,$env{$key});
 5862:             if (($end!=0) && ($end<$now)) { next; }
 5863:             if (($start!=0) && ($start>$now)) { next; }
 5864:             if ($1 eq $cdom && $2 eq $cnum) {
 5865:                 $groups{$3} = $env{$key} ;
 5866:             }
 5867:         }
 5868:     }
 5869:     return %groups;
 5870: }
 5871: 
 5872: sub get_group_membership {
 5873:     my ($cdom,$cnum,$group) = @_;
 5874:     return(&dump('groupmembership',$cdom,$cnum,$group));
 5875: }
 5876: 
 5877: sub get_users_groups {
 5878:     my ($udom,$uname,$courseid) = @_;
 5879:     my @usersgroups;
 5880:     my $cachetime=1800;
 5881: 
 5882:     my $hashid="$udom:$uname:$courseid";
 5883:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 5884:     if (defined($cached)) {
 5885:         @usersgroups = split(/:/,$grouplist);
 5886:     } else {  
 5887:         $grouplist = '';
 5888:         my $courseurl = &courseid_to_courseurl($courseid);
 5889:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 5890:         my $access_end = $env{'course.'.$courseid.
 5891:                               '.default_enrollment_end_date'};
 5892:         my $now = time;
 5893:         foreach my $key (keys(%roleshash)) {
 5894:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 5895:                 my $group = $1;
 5896:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 5897:                     my $start = $2;
 5898:                     my $end = $1;
 5899:                     if ($start == -1) { next; } # deleted from group
 5900:                     if (($start!=0) && ($start>$now)) { next; }
 5901:                     if (($end!=0) && ($end<$now)) {
 5902:                         if ($access_end && $access_end < $now) {
 5903:                             if ($access_end - $end < 86400) {
 5904:                                 push(@usersgroups,$group);
 5905:                             }
 5906:                         }
 5907:                         next;
 5908:                     }
 5909:                     push(@usersgroups,$group);
 5910:                 }
 5911:             }
 5912:         }
 5913:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 5914:         $grouplist = join(':',@usersgroups);
 5915:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 5916:     }
 5917:     return @usersgroups;
 5918: }
 5919: 
 5920: sub devalidate_getgroups_cache {
 5921:     my ($udom,$uname,$cdom,$cnum)=@_;
 5922:     my $courseid = $cdom.'_'.$cnum;
 5923: 
 5924:     my $hashid="$udom:$uname:$courseid";
 5925:     &devalidate_cache_new('getgroups',$hashid);
 5926: }
 5927: 
 5928: # ------------------------------------------------------------------ Plain Text
 5929: 
 5930: sub plaintext {
 5931:     my ($short,$type,$cid,$forcedefault) = @_;
 5932:     if ($short =~ /^cr/) {
 5933: 	return (split('/',$short))[-1];
 5934:     }
 5935:     if (!defined($cid)) {
 5936:         $cid = $env{'request.course.id'};
 5937:     }
 5938:     if (defined($cid) && ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '')) {
 5939:         unless ($forcedefault) {
 5940:             my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 5941:             &Apache::lonlocal::mt_escape(\$roletext);
 5942:             return &Apache::lonlocal::mt($roletext);
 5943:         }
 5944:     }
 5945:     my %rolenames = (
 5946:                       Course    => 'std',
 5947:                       Community => 'alt1',
 5948:                     );
 5949:     if (defined($type) && 
 5950:          defined($rolenames{$type}) && 
 5951:          defined($prp{$short}{$rolenames{$type}})) {
 5952:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 5953:     } else {
 5954:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 5955:     }
 5956: }
 5957: 
 5958: # ----------------------------------------------------------------- Assign Role
 5959: 
 5960: sub assignrole {
 5961:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 5962:         $context)=@_;
 5963:     my $mrole;
 5964:     if ($role =~ /^cr\//) {
 5965:         my $cwosec=$url;
 5966:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5967: 	unless (&allowed('ccr',$cwosec)) {
 5968:            &logthis('Refused custom assignrole: '.
 5969:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5970: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 5971:            return 'refused'; 
 5972:         }
 5973:         $mrole='cr';
 5974:     } elsif ($role =~ /^gr\//) {
 5975:         my $cwogrp=$url;
 5976:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 5977:         unless (&allowed('mdg',$cwogrp)) {
 5978:             &logthis('Refused group assignrole: '.
 5979:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5980:                     $env{'user.name'}.' at '.$env{'user.domain'});
 5981:             return 'refused';
 5982:         }
 5983:         $mrole='gr';
 5984:     } else {
 5985:         my $cwosec=$url;
 5986:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5987:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 5988:             my $refused;
 5989:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 5990:                 if (!(&allowed('c'.$role,$url))) {
 5991:                     $refused = 1;
 5992:                 }
 5993:             } else {
 5994:                 $refused = 1;
 5995:             }
 5996:             if ($refused) {
 5997:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5998:                     $refused = '';
 5999:                 } else {
 6000:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 6001:                              ' '.$role.' '.$end.' '.$start.' by '.
 6002: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 6003:                     return 'refused';
 6004:                 }
 6005:             }
 6006:         }
 6007:         $mrole=$role;
 6008:     }
 6009:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 6010:                 "$udom:$uname:$url".'_'."$mrole=$role";
 6011:     if ($end) { $command.='_'.$end; }
 6012:     if ($start) {
 6013: 	if ($end) { 
 6014:            $command.='_'.$start; 
 6015:         } else {
 6016:            $command.='_0_'.$start;
 6017:         }
 6018:     }
 6019:     my $origstart = $start;
 6020:     my $origend = $end;
 6021:     my $delflag;
 6022: # actually delete
 6023:     if ($deleteflag) {
 6024: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 6025: # modify command to delete the role
 6026:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 6027:                 "$udom:$uname:$url".'_'."$mrole";
 6028: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 6029: # set start and finish to negative values for userrolelog
 6030:            $start=-1;
 6031:            $end=-1;
 6032:            $delflag = 1;
 6033:         }
 6034:     }
 6035: # send command
 6036:     my $answer=&reply($command,&homeserver($uname,$udom));
 6037: # log new user role if status is ok
 6038:     if ($answer eq 'ok') {
 6039: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 6040: # for course roles, perform group memberships changes triggered by role change.
 6041:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 6042:         unless ($role =~ /^gr/) {
 6043:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 6044:                                              $origstart,$selfenroll,$context);
 6045:         }
 6046:     }
 6047:     return $answer;
 6048: }
 6049: 
 6050: # -------------------------------------------------- Modify user authentication
 6051: # Overrides without validation
 6052: 
 6053: sub modifyuserauth {
 6054:     my ($udom,$uname,$umode,$upass)=@_;
 6055:     my $uhome=&homeserver($uname,$udom);
 6056:     unless (&allowed('mau',$udom)) { return 'refused'; }
 6057:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 6058:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 6059:              ' in domain '.$env{'request.role.domain'});  
 6060:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 6061: 		     &escape($upass),$uhome);
 6062:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 6063:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 6064:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 6065:     &log($udom,,$uname,$uhome,
 6066:         'Authentication changed by '.$env{'user.domain'}.', '.
 6067:                                      $env{'user.name'}.', '.$umode.
 6068:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 6069:     unless ($reply eq 'ok') {
 6070:         &logthis('Authentication mode error: '.$reply);
 6071: 	return 'error: '.$reply;
 6072:     }   
 6073:     return 'ok';
 6074: }
 6075: 
 6076: # --------------------------------------------------------------- Modify a user
 6077: 
 6078: sub modifyuser {
 6079:     my ($udom,    $uname, $uid,
 6080:         $umode,   $upass, $first,
 6081:         $middle,  $last,  $gene,
 6082:         $forceid, $desiredhome, $email, $inststatus)=@_;
 6083:     $udom= &LONCAPA::clean_domain($udom);
 6084:     $uname=&LONCAPA::clean_username($uname);
 6085:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 6086:              $umode.', '.$first.', '.$middle.', '.
 6087: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 6088:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 6089:                                      ' desiredhome not specified'). 
 6090:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 6091:              ' in domain '.$env{'request.role.domain'});
 6092:     my $uhome=&homeserver($uname,$udom,'true');
 6093: # ----------------------------------------------------------------- Create User
 6094:     if (($uhome eq 'no_host') && 
 6095: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 6096:         my $unhome='';
 6097:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 6098:             $unhome = $desiredhome;
 6099: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 6100: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 6101:         } else { # load balancing routine for determining $unhome
 6102:             my $loadm=10000000;
 6103: 	    my %servers = &get_servers($udom,'library');
 6104: 	    foreach my $tryserver (keys(%servers)) {
 6105: 		my $answer=reply('load',$tryserver);
 6106: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 6107: 		    $loadm=$answer;
 6108: 		    $unhome=$tryserver;
 6109: 		}
 6110: 	    }
 6111:         }
 6112:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 6113: 	    return 'error: unable to find a home server for '.$uname.
 6114:                    ' in domain '.$udom;
 6115:         }
 6116:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 6117:                          &escape($upass),$unhome);
 6118: 	unless ($reply eq 'ok') {
 6119:             return 'error: '.$reply;
 6120:         }   
 6121:         $uhome=&homeserver($uname,$udom,'true');
 6122:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 6123: 	    return 'error: unable verify users home machine.';
 6124:         }
 6125:     }   # End of creation of new user
 6126: # ---------------------------------------------------------------------- Add ID
 6127:     if ($uid) {
 6128:        $uid=~tr/A-Z/a-z/;
 6129:        my %uidhash=&idrget($udom,$uname);
 6130:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 6131:          && (!$forceid)) {
 6132: 	  unless ($uid eq $uidhash{$uname}) {
 6133: 	      return 'error: user id "'.$uid.'" does not match '.
 6134:                   'current user id "'.$uidhash{$uname}.'".';
 6135:           }
 6136:        } else {
 6137: 	  &idput($udom,($uname => $uid));
 6138:        }
 6139:     }
 6140: # -------------------------------------------------------------- Add names, etc
 6141:     my @tmp=&get('environment',
 6142: 		   ['firstname','middlename','lastname','generation','id',
 6143:                     'permanentemail','inststatus'],
 6144: 		   $udom,$uname);
 6145:     my %names;
 6146:     if ($tmp[0] =~ m/^error:.*/) { 
 6147:         %names=(); 
 6148:     } else {
 6149:         %names = @tmp;
 6150:     }
 6151: #
 6152: # Make sure to not trash student environment if instructor does not bother
 6153: # to supply name and email information
 6154: #
 6155:     if ($first)  { $names{'firstname'}  = $first; }
 6156:     if (defined($middle)) { $names{'middlename'} = $middle; }
 6157:     if ($last)   { $names{'lastname'}   = $last; }
 6158:     if (defined($gene))   { $names{'generation'} = $gene; }
 6159:     if ($email) {
 6160:        $email=~s/[^\w\@\.\-\,]//gs;
 6161:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 6162:     }
 6163:     if ($uid) { $names{'id'}  = $uid; }
 6164:     if (defined($inststatus)) {
 6165:         $names{'inststatus'} = '';
 6166:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 6167:         if (ref($usertypes) eq 'HASH') {
 6168:             my @okstatuses; 
 6169:             foreach my $item (split(/:/,$inststatus)) {
 6170:                 if (defined($usertypes->{$item})) {
 6171:                     push(@okstatuses,$item);  
 6172:                 }
 6173:             }
 6174:             if (@okstatuses) {
 6175:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 6176:             }
 6177:         }
 6178:     }
 6179:     my $reply = &put('environment', \%names, $udom,$uname);
 6180:     if ($reply ne 'ok') { return 'error: '.$reply; }
 6181:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 6182:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 6183:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 6184:                  $umode.', '.$first.', '.$middle.', '.
 6185: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
 6186:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 6187:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 6188:     } else {
 6189:         $logmsg .= ' during self creation';
 6190:     }
 6191:     &logthis($logmsg);
 6192:     return 'ok';
 6193: }
 6194: 
 6195: # -------------------------------------------------------------- Modify student
 6196: 
 6197: sub modifystudent {
 6198:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 6199:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 6200:         $selfenroll,$context,$inststatus)=@_;
 6201:     if (!$cid) {
 6202: 	unless ($cid=$env{'request.course.id'}) {
 6203: 	    return 'not_in_class';
 6204: 	}
 6205:     }
 6206: # --------------------------------------------------------------- Make the user
 6207:     my $reply=&modifyuser
 6208: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 6209:          $desiredhome,$email,$inststatus);
 6210:     unless ($reply eq 'ok') { return $reply; }
 6211:     # This will cause &modify_student_enrollment to get the uid from the
 6212:     # students environment
 6213:     $uid = undef if (!$forceid);
 6214:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 6215: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 6216:     return $reply;
 6217: }
 6218: 
 6219: sub modify_student_enrollment {
 6220:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 6221:     my ($cdom,$cnum,$chome);
 6222:     if (!$cid) {
 6223: 	unless ($cid=$env{'request.course.id'}) {
 6224: 	    return 'not_in_class';
 6225: 	}
 6226: 	$cdom=$env{'course.'.$cid.'.domain'};
 6227: 	$cnum=$env{'course.'.$cid.'.num'};
 6228:     } else {
 6229: 	($cdom,$cnum)=split(/_/,$cid);
 6230:     }
 6231:     $chome=$env{'course.'.$cid.'.home'};
 6232:     if (!$chome) {
 6233: 	$chome=&homeserver($cnum,$cdom);
 6234:     }
 6235:     if (!$chome) { return 'unknown_course'; }
 6236:     # Make sure the user exists
 6237:     my $uhome=&homeserver($uname,$udom);
 6238:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6239: 	return 'error: no such user';
 6240:     }
 6241:     # Get student data if we were not given enough information
 6242:     if (!defined($first)  || $first  eq '' || 
 6243:         !defined($last)   || $last   eq '' || 
 6244:         !defined($uid)    || $uid    eq '' || 
 6245:         !defined($middle) || $middle eq '' || 
 6246:         !defined($gene)   || $gene   eq '') {
 6247:         # They did not supply us with enough data to enroll the student, so
 6248:         # we need to pick up more information.
 6249:         my %tmp = &get('environment',
 6250:                        ['firstname','middlename','lastname', 'generation','id']
 6251:                        ,$udom,$uname);
 6252: 
 6253:         #foreach my $key (keys(%tmp)) {
 6254:         #    &logthis("key $key = ".$tmp{$key});
 6255:         #}
 6256:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 6257:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 6258:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 6259:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 6260:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 6261:     }
 6262:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 6263:     my $reply=cput('classlist',
 6264: 		   {"$uname:$udom" => 
 6265: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 6266: 		   $cdom,$cnum);
 6267:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 6268: 	return 'error: '.$reply;
 6269:     } else {
 6270: 	&devalidate_getsection_cache($udom,$uname,$cid);
 6271:     }
 6272:     # Add student role to user
 6273:     my $uurl='/'.$cid;
 6274:     $uurl=~s/\_/\//g;
 6275:     if ($usec) {
 6276: 	$uurl.='/'.$usec;
 6277:     }
 6278:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 6279: }
 6280: 
 6281: sub format_name {
 6282:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 6283:     my $name;
 6284:     if ($first ne 'lastname') {
 6285: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 6286:     } else {
 6287: 	if ($lastname=~/\S/) {
 6288: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 6289: 	    $name=~s/\s+,/,/;
 6290: 	} else {
 6291: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 6292: 	}
 6293:     }
 6294:     $name=~s/^\s+//;
 6295:     $name=~s/\s+$//;
 6296:     $name=~s/\s+/ /g;
 6297:     return $name;
 6298: }
 6299: 
 6300: # ------------------------------------------------- Write to course preferences
 6301: 
 6302: sub writecoursepref {
 6303:     my ($courseid,%prefs)=@_;
 6304:     $courseid=~s/^\///;
 6305:     $courseid=~s/\_/\//g;
 6306:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6307:     my $chome=homeserver($cnum,$cdomain);
 6308:     if (($chome eq '') || ($chome eq 'no_host')) { 
 6309: 	return 'error: no such course';
 6310:     }
 6311:     my $cstring='';
 6312:     foreach my $pref (keys(%prefs)) {
 6313: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 6314:     }
 6315:     $cstring=~s/\&$//;
 6316:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 6317: }
 6318: 
 6319: # ---------------------------------------------------------- Make/modify course
 6320: 
 6321: sub createcourse {
 6322:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 6323:         $course_owner,$crstype)=@_;
 6324:     $url=&declutter($url);
 6325:     my $cid='';
 6326:     unless (&allowed('ccc',$udom)) {
 6327:         return 'refused';
 6328:     }
 6329: # ------------------------------------------------------------------- Create ID
 6330:    my $uname=int(1+rand(9)).
 6331:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6332:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6333:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6334: # ----------------------------------------------- Make sure that does not exist
 6335:    my $uhome=&homeserver($uname,$udom,'true');
 6336:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6337:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6338:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6339:        $uhome=&homeserver($uname,$udom,'true');       
 6340:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6341:            return 'error: unable to generate unique course-ID';
 6342:        } 
 6343:    }
 6344: # ------------------------------------------------ Check supplied server name
 6345:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 6346:     if (! &is_library($course_server)) {
 6347:         return 'error:bad server name '.$course_server;
 6348:     }
 6349: # ------------------------------------------------------------- Make the course
 6350:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 6351:                       $course_server);
 6352:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 6353:     $uhome=&homeserver($uname,$udom,'true');
 6354:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6355: 	return 'error: no such course';
 6356:     }
 6357: # ----------------------------------------------------------------- Course made
 6358: # log existence
 6359:     my $newcourse = {
 6360:                     $udom.'_'.$uname => {
 6361:                                      description => $description,
 6362:                                      inst_code   => $inst_code,
 6363:                                      owner       => $course_owner,
 6364:                                      type        => $crstype,
 6365:                                                 },
 6366:                     };
 6367:     &courseidput($udom,$newcourse,$uhome,'notime');
 6368: # set toplevel url
 6369:     my $topurl=$url;
 6370:     unless ($nonstandard) {
 6371: # ------------------------------------------ For standard courses, make top url
 6372:         my $mapurl=&clutter($url);
 6373:         if ($mapurl eq '/res/') { $mapurl=''; }
 6374:         $env{'form.initmap'}=(<<ENDINITMAP);
 6375: <map>
 6376: <resource id="1" type="start"></resource>
 6377: <resource id="2" src="$mapurl"></resource>
 6378: <resource id="3" type="finish"></resource>
 6379: <link index="1" from="1" to="2"></link>
 6380: <link index="2" from="2" to="3"></link>
 6381: </map>
 6382: ENDINITMAP
 6383:         $topurl=&declutter(
 6384:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 6385:                           );
 6386:     }
 6387: # ----------------------------------------------------------- Write preferences
 6388:     &writecoursepref($udom.'_'.$uname,
 6389:                      ('description' => $description,
 6390:                       'url'         => $topurl));
 6391:     return '/'.$udom.'/'.$uname;
 6392: }
 6393: 
 6394: sub is_course {
 6395:     my ($cdom,$cnum) = @_;
 6396:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 6397: 				undef,'.');
 6398:     if (exists($courses{$cdom.'_'.$cnum})) {
 6399:         return 1;
 6400:     }
 6401:     return 0;
 6402: }
 6403: 
 6404: # ---------------------------------------------------------- Assign Custom Role
 6405: 
 6406: sub assigncustomrole {
 6407:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 6408:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 6409:                        $end,$start,$deleteflag,$selfenroll,$context);
 6410: }
 6411: 
 6412: # ----------------------------------------------------------------- Revoke Role
 6413: 
 6414: sub revokerole {
 6415:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 6416:     my $now=time;
 6417:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 6418: }
 6419: 
 6420: # ---------------------------------------------------------- Revoke Custom Role
 6421: 
 6422: sub revokecustomrole {
 6423:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 6424:     my $now=time;
 6425:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 6426:            $deleteflag,$selfenroll,$context);
 6427: }
 6428: 
 6429: # ------------------------------------------------------------ Disk usage
 6430: sub diskusage {
 6431:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 6432:     $directorypath =~ s/\/$//;
 6433:     my $listing=&reply('du2:'.&escape($directorypath).':'
 6434:                        .&escape($getpropath).':'.&escape($uname).':'
 6435:                        .&escape($udom),homeserver($uname,$udom));
 6436:     if ($listing eq 'unknown_cmd') {
 6437:         if ($getpropath) {
 6438:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 6439:         }
 6440:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 6441:     }
 6442:     return $listing;
 6443: }
 6444: 
 6445: sub is_locked {
 6446:     my ($file_name, $domain, $user) = @_;
 6447:     my @check;
 6448:     my $is_locked;
 6449:     push @check, $file_name;
 6450:     my %locked = &get('file_permissions',\@check,
 6451: 		      $env{'user.domain'},$env{'user.name'});
 6452:     my ($tmp)=keys(%locked);
 6453:     if ($tmp=~/^error:/) { undef(%locked); }
 6454:     
 6455:     if (ref($locked{$file_name}) eq 'ARRAY') {
 6456:         $is_locked = 'false';
 6457:         foreach my $entry (@{$locked{$file_name}}) {
 6458:            if (ref($entry) eq 'ARRAY') { 
 6459:                $is_locked = 'true';
 6460:                last;
 6461:            }
 6462:        }
 6463:     } else {
 6464:         $is_locked = 'false';
 6465:     }
 6466: }
 6467: 
 6468: sub declutter_portfile {
 6469:     my ($file) = @_;
 6470:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 6471:     return $file;
 6472: }
 6473: 
 6474: # ------------------------------------------------------------- Mark as Read Only
 6475: 
 6476: sub mark_as_readonly {
 6477:     my ($domain,$user,$files,$what) = @_;
 6478:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6479:     my ($tmp)=keys(%current_permissions);
 6480:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6481:     foreach my $file (@{$files}) {
 6482: 	$file = &declutter_portfile($file);
 6483:         push(@{$current_permissions{$file}},$what);
 6484:     }
 6485:     &put('file_permissions',\%current_permissions,$domain,$user);
 6486:     return;
 6487: }
 6488: 
 6489: # ------------------------------------------------------------Save Selected Files
 6490: 
 6491: sub save_selected_files {
 6492:     my ($user, $path, @files) = @_;
 6493:     my $filename = $user."savedfiles";
 6494:     my @other_files = &files_not_in_path($user, $path);
 6495:     open (OUT, '>'.$tmpdir.$filename);
 6496:     foreach my $file (@files) {
 6497:         print (OUT $env{'form.currentpath'}.$file."\n");
 6498:     }
 6499:     foreach my $file (@other_files) {
 6500:         print (OUT $file."\n");
 6501:     }
 6502:     close (OUT);
 6503:     return 'ok';
 6504: }
 6505: 
 6506: sub clear_selected_files {
 6507:     my ($user) = @_;
 6508:     my $filename = $user."savedfiles";
 6509:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6510:     print (OUT undef);
 6511:     close (OUT);
 6512:     return ("ok");    
 6513: }
 6514: 
 6515: sub files_in_path {
 6516:     my ($user, $path) = @_;
 6517:     my $filename = $user."savedfiles";
 6518:     my %return_files;
 6519:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6520:     while (my $line_in = <IN>) {
 6521:         chomp ($line_in);
 6522:         my @paths_and_file = split (m!/!, $line_in);
 6523:         my $file_part = pop (@paths_and_file);
 6524:         my $path_part = join ('/', @paths_and_file);
 6525:         $path_part.='/';
 6526:         my $path_and_file = $path_part.$file_part;
 6527:         if ($path_part eq $path) {
 6528:             $return_files{$file_part}= 'selected';
 6529:         }
 6530:     }
 6531:     close (IN);
 6532:     return (\%return_files);
 6533: }
 6534: 
 6535: # called in portfolio select mode, to show files selected NOT in current directory
 6536: sub files_not_in_path {
 6537:     my ($user, $path) = @_;
 6538:     my $filename = $user."savedfiles";
 6539:     my @return_files;
 6540:     my $path_part;
 6541:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6542:     while (my $line = <IN>) {
 6543:         #ok, I know it's clunky, but I want it to work
 6544:         my @paths_and_file = split(m|/|, $line);
 6545:         my $file_part = pop(@paths_and_file);
 6546:         chomp($file_part);
 6547:         my $path_part = join('/', @paths_and_file);
 6548:         $path_part .= '/';
 6549:         my $path_and_file = $path_part.$file_part;
 6550:         if ($path_part ne $path) {
 6551:             push(@return_files, ($path_and_file));
 6552:         }
 6553:     }
 6554:     close(OUT);
 6555:     return (@return_files);
 6556: }
 6557: 
 6558: #----------------------------------------------Get portfolio file permissions
 6559: 
 6560: sub get_portfile_permissions {
 6561:     my ($domain,$user) = @_;
 6562:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6563:     my ($tmp)=keys(%current_permissions);
 6564:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6565:     return \%current_permissions;
 6566: }
 6567: 
 6568: #---------------------------------------------Get portfolio file access controls
 6569: 
 6570: sub get_access_controls {
 6571:     my ($current_permissions,$group,$file) = @_;
 6572:     my %access;
 6573:     my $real_file = $file;
 6574:     $file =~ s/\.meta$//;
 6575:     if (defined($file)) {
 6576:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 6577:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 6578:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 6579:             }
 6580:         }
 6581:     } else {
 6582:         foreach my $key (keys(%{$current_permissions})) {
 6583:             if ($key =~ /\0accesscontrol$/) {
 6584:                 if (defined($group)) {
 6585:                     if ($key !~ m-^\Q$group\E/-) {
 6586:                         next;
 6587:                     }
 6588:                 }
 6589:                 my ($fullpath) = split(/\0/,$key);
 6590:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 6591:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 6592:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 6593:                     }
 6594:                 }
 6595:             }
 6596:         }
 6597:     }
 6598:     return %access;
 6599: }
 6600: 
 6601: sub modify_access_controls {
 6602:     my ($file_name,$changes,$domain,$user)=@_;
 6603:     my ($outcome,$deloutcome);
 6604:     my %store_permissions;
 6605:     my %new_values;
 6606:     my %new_control;
 6607:     my %translation;
 6608:     my @deletions = ();
 6609:     my $now = time;
 6610:     if (exists($$changes{'activate'})) {
 6611:         if (ref($$changes{'activate'}) eq 'HASH') {
 6612:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 6613:             my $numnew = scalar(@newitems);
 6614:             for (my $i=0; $i<$numnew; $i++) {
 6615:                 my $newkey = $newitems[$i];
 6616:                 my $newid = &Apache::loncommon::get_cgi_id();
 6617:                 if ($newkey =~ /^\d+:/) { 
 6618:                     $newkey =~ s/^(\d+)/$newid/;
 6619:                     $translation{$1} = $newid;
 6620:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 6621:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 6622:                     $translation{$1} = $newid;
 6623:                 }
 6624:                 $new_values{$file_name."\0".$newkey} = 
 6625:                                           $$changes{'activate'}{$newitems[$i]};
 6626:                 $new_control{$newkey} = $now;
 6627:             }
 6628:         }
 6629:     }
 6630:     my %todelete;
 6631:     my %changed_items;
 6632:     foreach my $action ('delete','update') {
 6633:         if (exists($$changes{$action})) {
 6634:             if (ref($$changes{$action}) eq 'HASH') {
 6635:                 foreach my $key (keys(%{$$changes{$action}})) {
 6636:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 6637:                     if ($action eq 'delete') { 
 6638:                         $todelete{$itemnum} = 1;
 6639:                     } else {
 6640:                         $changed_items{$itemnum} = $key;
 6641:                     }
 6642:                 }
 6643:             }
 6644:         }
 6645:     }
 6646:     # get lock on access controls for file.
 6647:     my $lockhash = {
 6648:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 6649:                                                        ':'.$env{'user.domain'},
 6650:                    }; 
 6651:     my $tries = 0;
 6652:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6653:    
 6654:     while (($gotlock ne 'ok') && $tries <3) {
 6655:         $tries ++;
 6656:         sleep 1;
 6657:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6658:     }
 6659:     if ($gotlock eq 'ok') {
 6660:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 6661:         my ($tmp)=keys(%curr_permissions);
 6662:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 6663:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 6664:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 6665:             if (ref($curr_controls) eq 'HASH') {
 6666:                 foreach my $control_item (keys(%{$curr_controls})) {
 6667:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 6668:                     if (defined($todelete{$itemnum})) {
 6669:                         push(@deletions,$file_name."\0".$control_item);
 6670:                     } else {
 6671:                         if (defined($changed_items{$itemnum})) {
 6672:                             $new_control{$changed_items{$itemnum}} = $now;
 6673:                             push(@deletions,$file_name."\0".$control_item);
 6674:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 6675:                         } else {
 6676:                             $new_control{$control_item} = $$curr_controls{$control_item};
 6677:                         }
 6678:                     }
 6679:                 }
 6680:             }
 6681:         }
 6682:         my ($group);
 6683:         if (&is_course($domain,$user)) {
 6684:             ($group,my $file) = split(/\//,$file_name,2);
 6685:         }
 6686:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 6687:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 6688:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 6689:         #  remove lock
 6690:         my @del_lock = ($file_name."\0".'locked_access_records');
 6691:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 6692:         my $sqlresult =
 6693:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 6694:                                     $group);
 6695:     } else {
 6696:         $outcome = "error: could not obtain lockfile\n";  
 6697:     }
 6698:     return ($outcome,$deloutcome,\%new_values,\%translation);
 6699: }
 6700: 
 6701: sub make_public_indefinitely {
 6702:     my ($requrl) = @_;
 6703:     my $now = time;
 6704:     my $action = 'activate';
 6705:     my $aclnum = 0;
 6706:     if (&is_portfolio_url($requrl)) {
 6707:         my (undef,$udom,$unum,$file_name,$group) =
 6708:             &parse_portfolio_url($requrl);
 6709:         my $current_perms = &get_portfile_permissions($udom,$unum);
 6710:         my %access_controls = &get_access_controls($current_perms,
 6711:                                                    $group,$file_name);
 6712:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 6713:             my ($num,$scope,$end,$start) = 
 6714:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6715:             if ($scope eq 'public') {
 6716:                 if ($start <= $now && $end == 0) {
 6717:                     $action = 'none';
 6718:                 } else {
 6719:                     $action = 'update';
 6720:                     $aclnum = $num;
 6721:                 }
 6722:                 last;
 6723:             }
 6724:         }
 6725:         if ($action eq 'none') {
 6726:              return 'ok';
 6727:         } else {
 6728:             my %changes;
 6729:             my $newend = 0;
 6730:             my $newstart = $now;
 6731:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 6732:             $changes{$action}{$newkey} = {
 6733:                 type => 'public',
 6734:                 time => {
 6735:                     start => $newstart,
 6736:                     end   => $newend,
 6737:                 },
 6738:             };
 6739:             my ($outcome,$deloutcome,$new_values,$translation) =
 6740:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 6741:             return $outcome;
 6742:         }
 6743:     } else {
 6744:         return 'invalid';
 6745:     }
 6746: }
 6747: 
 6748: #------------------------------------------------------Get Marked as Read Only
 6749: 
 6750: sub get_marked_as_readonly {
 6751:     my ($domain,$user,$what,$group) = @_;
 6752:     my $current_permissions = &get_portfile_permissions($domain,$user);
 6753:     my @readonly_files;
 6754:     my $cmp1=$what;
 6755:     if (ref($what)) { $cmp1=join('',@{$what}) };
 6756:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6757:         if (defined($group)) {
 6758:             if ($file_name !~ m-^\Q$group\E/-) {
 6759:                 next;
 6760:             }
 6761:         }
 6762:         if (ref($value) eq "ARRAY"){
 6763:             foreach my $stored_what (@{$value}) {
 6764:                 my $cmp2=$stored_what;
 6765:                 if (ref($stored_what) eq 'ARRAY') {
 6766:                     $cmp2=join('',@{$stored_what});
 6767:                 }
 6768:                 if ($cmp1 eq $cmp2) {
 6769:                     push(@readonly_files, $file_name);
 6770:                     last;
 6771:                 } elsif (!defined($what)) {
 6772:                     push(@readonly_files, $file_name);
 6773:                     last;
 6774:                 }
 6775:             }
 6776:         }
 6777:     }
 6778:     return @readonly_files;
 6779: }
 6780: #-----------------------------------------------------------Get Marked as Read Only Hash
 6781: 
 6782: sub get_marked_as_readonly_hash {
 6783:     my ($current_permissions,$group,$what) = @_;
 6784:     my %readonly_files;
 6785:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6786:         if (defined($group)) {
 6787:             if ($file_name !~ m-^\Q$group\E/-) {
 6788:                 next;
 6789:             }
 6790:         }
 6791:         if (ref($value) eq "ARRAY"){
 6792:             foreach my $stored_what (@{$value}) {
 6793:                 if (ref($stored_what) eq 'ARRAY') {
 6794:                     foreach my $lock_descriptor(@{$stored_what}) {
 6795:                         if ($lock_descriptor eq 'graded') {
 6796:                             $readonly_files{$file_name} = 'graded';
 6797:                         } elsif ($lock_descriptor eq 'handback') {
 6798:                             $readonly_files{$file_name} = 'handback';
 6799:                         } else {
 6800:                             if (!exists($readonly_files{$file_name})) {
 6801:                                 $readonly_files{$file_name} = 'locked';
 6802:                             }
 6803:                         }
 6804:                     }
 6805:                 } 
 6806:             }
 6807:         } 
 6808:     }
 6809:     return %readonly_files;
 6810: }
 6811: # ------------------------------------------------------------ Unmark as Read Only
 6812: 
 6813: sub unmark_as_readonly {
 6814:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 6815:     # for portfolio submissions, $what contains [$symb,$crsid] 
 6816:     my ($domain,$user,$what,$file_name,$group) = @_;
 6817:     $file_name = &declutter_portfile($file_name);
 6818:     my $symb_crs = $what;
 6819:     if (ref($what)) { $symb_crs=join('',@$what); }
 6820:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 6821:     my ($tmp)=keys(%current_permissions);
 6822:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6823:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 6824:     foreach my $file (@readonly_files) {
 6825: 	my $clean_file = &declutter_portfile($file);
 6826: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 6827: 	my $current_locks = $current_permissions{$file};
 6828:         my @new_locks;
 6829:         my @del_keys;
 6830:         if (ref($current_locks) eq "ARRAY"){
 6831:             foreach my $locker (@{$current_locks}) {
 6832:                 my $compare=$locker;
 6833:                 if (ref($locker) eq 'ARRAY') {
 6834:                     $compare=join('',@{$locker});
 6835:                     if ($compare ne $symb_crs) {
 6836:                         push(@new_locks, $locker);
 6837:                     }
 6838:                 }
 6839:             }
 6840:             if (scalar(@new_locks) > 0) {
 6841:                 $current_permissions{$file} = \@new_locks;
 6842:             } else {
 6843:                 push(@del_keys, $file);
 6844:                 &del('file_permissions',\@del_keys, $domain, $user);
 6845:                 delete($current_permissions{$file});
 6846:             }
 6847:         }
 6848:     }
 6849:     &put('file_permissions',\%current_permissions,$domain,$user);
 6850:     return;
 6851: }
 6852: 
 6853: # ------------------------------------------------------------ Directory lister
 6854: 
 6855: sub dirlist {
 6856:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 6857:     $uri=~s/^\///;
 6858:     $uri=~s/\/$//;
 6859:     my ($udom, $uname);
 6860:     if ($getuserdir) {
 6861:         $udom = $userdomain;
 6862:         $uname = $username;
 6863:     } else {
 6864:         (undef,$udom,$uname)=split(/\//,$uri);
 6865:         if(defined($userdomain)) {
 6866:             $udom = $userdomain;
 6867:         }
 6868:         if(defined($username)) {
 6869:             $uname = $username;
 6870:         }
 6871:     }
 6872:     my ($dirRoot,$listing,@listing_results);
 6873: 
 6874:     $dirRoot = $perlvar{'lonDocRoot'};
 6875:     if (defined($getpropath)) {
 6876:         $dirRoot = &propath($udom,$uname);
 6877:         $dirRoot =~ s/\/$//;
 6878:     } elsif (defined($getuserdir)) {
 6879:         my $subdir=$uname.'__';
 6880:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 6881:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 6882:                    ."/$udom/$subdir/$uname";
 6883:     } elsif (defined($alternateRoot)) {
 6884:         $dirRoot = $alternateRoot;
 6885:     }
 6886: 
 6887:     if($udom) {
 6888:         if($uname) {
 6889:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 6890:                               .$getuserdir.':'.&escape($dirRoot)
 6891:                               .':'.&escape($uname).':'.&escape($udom),
 6892:                               &homeserver($uname,$udom));
 6893:             if ($listing eq 'unknown_cmd') {
 6894:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 6895:                                   &homeserver($uname,$udom));
 6896:             } else {
 6897:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6898:             }
 6899:             if ($listing eq 'unknown_cmd') {
 6900:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 6901: 				  &homeserver($uname,$udom));
 6902:                 @listing_results = split(/:/,$listing);
 6903:             } else {
 6904:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6905:             }
 6906:             return @listing_results;
 6907:         } elsif(!$alternateRoot) {
 6908:             my %allusers;
 6909: 	    my %servers = &get_servers($udom,'library');
 6910:  	    foreach my $tryserver (keys(%servers)) {
 6911:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 6912:                                   &escape($udom),$tryserver);
 6913:                 if ($listing eq 'unknown_cmd') {
 6914: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 6915: 				      $udom, $tryserver);
 6916:                 } else {
 6917:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 6918:                 }
 6919: 		if ($listing eq 'unknown_cmd') {
 6920: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 6921: 				      $udom, $tryserver);
 6922: 		    @listing_results = split(/:/,$listing);
 6923: 		} else {
 6924: 		    @listing_results =
 6925: 			map { &unescape($_); } split(/:/,$listing);
 6926: 		}
 6927: 		if ($listing_results[0] ne 'no_such_dir' && 
 6928: 		    $listing_results[0] ne 'empty'       &&
 6929: 		    $listing_results[0] ne 'con_lost') {
 6930: 		    foreach my $line (@listing_results) {
 6931: 			my ($entry) = split(/&/,$line,2);
 6932: 			$allusers{$entry} = 1;
 6933: 		    }
 6934: 		}
 6935:             }
 6936:             my $alluserstr='';
 6937:             foreach my $user (sort(keys(%allusers))) {
 6938:                 $alluserstr.=$user.'&user:';
 6939:             }
 6940:             $alluserstr=~s/:$//;
 6941:             return split(/:/,$alluserstr);
 6942:         } else {
 6943:             return ('missing user name');
 6944:         }
 6945:     } elsif(!defined($getpropath)) {
 6946:         my @all_domains = sort(&all_domains());
 6947:         foreach my $domain (@all_domains) {
 6948:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 6949:         }
 6950:         return @all_domains;
 6951:     } else {
 6952:         return ('missing domain');
 6953:     }
 6954: }
 6955: 
 6956: # --------------------------------------------- GetFileTimestamp
 6957: # This function utilizes dirlist and returns the date stamp for
 6958: # when it was last modified.  It will also return an error of -1
 6959: # if an error occurs
 6960: 
 6961: sub GetFileTimestamp {
 6962:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 6963:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 6964:     $studentName   = &LONCAPA::clean_username($studentName);
 6965:     my ($fileStat) = 
 6966:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
 6967:                                  undef,$getuserdir);
 6968:     my @stats = split('&', $fileStat);
 6969:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6970:         # @stats contains first the filename, then the stat output
 6971:         return $stats[10]; # so this is 10 instead of 9.
 6972:     } else {
 6973:         return -1;
 6974:     }
 6975: }
 6976: 
 6977: sub stat_file {
 6978:     my ($uri) = @_;
 6979:     $uri = &clutter_with_no_wrapper($uri);
 6980: 
 6981:     my ($udom,$uname,$file);
 6982:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 6983: 	($udom,$uname,$file) =
 6984: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 6985: 	$file = 'userfiles/'.$file;
 6986:     }
 6987:     if ($uri =~ m-^/res/-) {
 6988: 	($udom,$uname) = 
 6989: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 6990: 	$file = $uri;
 6991:     }
 6992: 
 6993:     if (!$udom || !$uname || !$file) {
 6994: 	# unable to handle the uri
 6995: 	return ();
 6996:     }
 6997:     my $getpropath;
 6998:     if ($file =~ /^userfiles\//) {
 6999:         $getpropath = 1;
 7000:     }
 7001:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
 7002:     my @stats = split('&', $result);
 7003:     
 7004:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 7005: 	shift(@stats); #filename is first
 7006: 	return @stats;
 7007:     }
 7008:     return ();
 7009: }
 7010: 
 7011: # -------------------------------------------------------- Value of a Condition
 7012: 
 7013: # gets the value of a specific preevaluated condition
 7014: #    stored in the string  $env{user.state.<cid>}
 7015: # or looks up a condition reference in the bighash and if if hasn't
 7016: # already been evaluated recurses into docondval to get the value of
 7017: # the condition, then memoizing it to 
 7018: #   $env{user.state.<cid>.<condition>}
 7019: sub directcondval {
 7020:     my $number=shift;
 7021:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 7022: 	&Apache::lonuserstate::evalstate();
 7023:     }
 7024:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 7025: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 7026:     } elsif ($number =~ /^_/) {
 7027: 	my $sub_condition;
 7028: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7029: 		&GDBM_READER(),0640)) {
 7030: 	    $sub_condition=$bighash{'conditions'.$number};
 7031: 	    untie(%bighash);
 7032: 	}
 7033: 	my $value = &docondval($sub_condition);
 7034: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 7035: 	return $value;
 7036:     }
 7037:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 7038:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 7039:     } else {
 7040:        return 2;
 7041:     }
 7042: }
 7043: 
 7044: # get the collection of conditions for this resource
 7045: sub condval {
 7046:     my $condidx=shift;
 7047:     my $allpathcond='';
 7048:     foreach my $cond (split(/\|/,$condidx)) {
 7049: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 7050: 	    $allpathcond.=
 7051: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 7052: 	}
 7053:     }
 7054:     $allpathcond=~s/\|$//;
 7055:     return &docondval($allpathcond);
 7056: }
 7057: 
 7058: #evaluates an expression of conditions
 7059: sub docondval {
 7060:     my ($allpathcond) = @_;
 7061:     my $result=0;
 7062:     if ($env{'request.course.id'}
 7063: 	&& defined($allpathcond)) {
 7064: 	my $operand='|';
 7065: 	my @stack;
 7066: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 7067: 	    if ($chunk eq '(') {
 7068: 		push @stack,($operand,$result);
 7069: 	    } elsif ($chunk eq ')') {
 7070: 		my $before=pop @stack;
 7071: 		if (pop @stack eq '&') {
 7072: 		    $result=$result>$before?$before:$result;
 7073: 		} else {
 7074: 		    $result=$result>$before?$result:$before;
 7075: 		}
 7076: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 7077: 		$operand=$chunk;
 7078: 	    } else {
 7079: 		my $new=directcondval($chunk);
 7080: 		if ($operand eq '&') {
 7081: 		    $result=$result>$new?$new:$result;
 7082: 		} else {
 7083: 		    $result=$result>$new?$result:$new;
 7084: 		}
 7085: 	    }
 7086: 	}
 7087:     }
 7088:     return $result;
 7089: }
 7090: 
 7091: # ---------------------------------------------------- Devalidate courseresdata
 7092: 
 7093: sub devalidatecourseresdata {
 7094:     my ($coursenum,$coursedomain)=@_;
 7095:     my $hashid=$coursenum.':'.$coursedomain;
 7096:     &devalidate_cache_new('courseres',$hashid);
 7097: }
 7098: 
 7099: 
 7100: # --------------------------------------------------- Course Resourcedata Query
 7101: #
 7102: #  Parameters:
 7103: #      $coursenum    - Number of the course.
 7104: #      $coursedomain - Domain at which the course was created.
 7105: #  Returns:
 7106: #     A hash of the course parameters along (I think) with timestamps
 7107: #     and version info.
 7108: 
 7109: sub get_courseresdata {
 7110:     my ($coursenum,$coursedomain)=@_;
 7111:     my $coursehom=&homeserver($coursenum,$coursedomain);
 7112:     my $hashid=$coursenum.':'.$coursedomain;
 7113:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 7114:     my %dumpreply;
 7115:     unless (defined($cached)) {
 7116: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 7117: 	$result=\%dumpreply;
 7118: 	my ($tmp) = keys(%dumpreply);
 7119: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 7120: 	    &do_cache_new('courseres',$hashid,$result,600);
 7121: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 7122: 	    return $tmp;
 7123: 	} elsif ($tmp =~ /^(error)/) {
 7124: 	    $result=undef;
 7125: 	    &do_cache_new('courseres',$hashid,$result,600);
 7126: 	}
 7127:     }
 7128:     return $result;
 7129: }
 7130: 
 7131: sub devalidateuserresdata {
 7132:     my ($uname,$udom)=@_;
 7133:     my $hashid="$udom:$uname";
 7134:     &devalidate_cache_new('userres',$hashid);
 7135: }
 7136: 
 7137: sub get_userresdata {
 7138:     my ($uname,$udom)=@_;
 7139:     #most student don\'t have any data set, check if there is some data
 7140:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 7141: 
 7142:     my $hashid="$udom:$uname";
 7143:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 7144:     if (!defined($cached)) {
 7145: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 7146: 	$result=\%resourcedata;
 7147: 	&do_cache_new('userres',$hashid,$result,600);
 7148:     }
 7149:     my ($tmp)=keys(%$result);
 7150:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 7151: 	return $result;
 7152:     }
 7153:     #error 2 occurs when the .db doesn't exist
 7154:     if ($tmp!~/error: 2 /) {
 7155: 	&logthis("<font color=\"blue\">WARNING:".
 7156: 		 " Trying to get resource data for ".
 7157: 		 $uname." at ".$udom.": ".
 7158: 		 $tmp."</font>");
 7159:     } elsif ($tmp=~/error: 2 /) {
 7160: 	#&EXT_cache_set($udom,$uname);
 7161: 	&do_cache_new('userres',$hashid,undef,600);
 7162: 	undef($tmp); # not really an error so don't send it back
 7163:     }
 7164:     return $tmp;
 7165: }
 7166: #----------------------------------------------- resdata - return resource data
 7167: #  Purpose:
 7168: #    Return resource data for either users or for a course.
 7169: #  Parameters:
 7170: #     $name      - Course/user name.
 7171: #     $domain    - Name of the domain the user/course is registered on.
 7172: #     $type      - Type of thing $name is (must be 'course' or 'user'
 7173: #     @which     - Array of names of resources desired.
 7174: #  Returns:
 7175: #     The value of the first reasource in @which that is found in the
 7176: #     resource hash.
 7177: #  Exceptional Conditions:
 7178: #     If the $type passed in is not valid (not the string 'course' or 
 7179: #     'user', an undefined  reference is returned.
 7180: #     If none of the resources are found, an undef is returned
 7181: sub resdata {
 7182:     my ($name,$domain,$type,@which)=@_;
 7183:     my $result;
 7184:     if ($type eq 'course') {
 7185: 	$result=&get_courseresdata($name,$domain);
 7186:     } elsif ($type eq 'user') {
 7187: 	$result=&get_userresdata($name,$domain);
 7188:     }
 7189:     if (!ref($result)) { return $result; }    
 7190:     foreach my $item (@which) {
 7191: 	if (defined($result->{$item->[0]})) {
 7192: 	    return [$result->{$item->[0]},$item->[1]];
 7193: 	}
 7194:     }
 7195:     return undef;
 7196: }
 7197: 
 7198: #
 7199: # EXT resource caching routines
 7200: #
 7201: 
 7202: sub clear_EXT_cache_status {
 7203:     &delenv('cache.EXT.');
 7204: }
 7205: 
 7206: sub EXT_cache_status {
 7207:     my ($target_domain,$target_user) = @_;
 7208:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7209:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 7210:         # We know already the user has no data
 7211:         return 1;
 7212:     } else {
 7213:         return 0;
 7214:     }
 7215: }
 7216: 
 7217: sub EXT_cache_set {
 7218:     my ($target_domain,$target_user) = @_;
 7219:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7220:     #&appenv({$cachename => time});
 7221: }
 7222: 
 7223: # --------------------------------------------------------- Value of a Variable
 7224: sub EXT {
 7225: 
 7226:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 7227:     unless ($varname) { return ''; }
 7228:     #get real user name/domain, courseid and symb
 7229:     my $courseid;
 7230:     my $publicuser;
 7231:     if ($symbparm) {
 7232: 	$symbparm=&get_symb_from_alias($symbparm);
 7233:     }
 7234:     if (!($uname && $udom)) {
 7235:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 7236:       if (!$symbparm) {	$symbparm=$cursymb; }
 7237:     } else {
 7238: 	$courseid=$env{'request.course.id'};
 7239:     }
 7240:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 7241:     my $rest;
 7242:     if (defined($therest[0])) {
 7243:        $rest=join('.',@therest);
 7244:     } else {
 7245:        $rest='';
 7246:     }
 7247: 
 7248:     my $qualifierrest=$qualifier;
 7249:     if ($rest) { $qualifierrest.='.'.$rest; }
 7250:     my $spacequalifierrest=$space;
 7251:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 7252:     if ($realm eq 'user') {
 7253: # --------------------------------------------------------------- user.resource
 7254: 	if ($space eq 'resource') {
 7255: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 7256: 		  || defined($Apache::lonhomework::parsing_a_task))
 7257: 		 &&
 7258: 		 ($symbparm eq &symbread()) ) {	
 7259: 		# if we are in the middle of processing the resource the
 7260: 		# get the value we are planning on committing
 7261:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 7262:                     return $Apache::lonhomework::results{$qualifierrest};
 7263:                 } else {
 7264:                     return $Apache::lonhomework::history{$qualifierrest};
 7265:                 }
 7266: 	    } else {
 7267: 		my %restored;
 7268: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 7269: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 7270: 		} else {
 7271: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 7272: 		}
 7273: 		return $restored{$qualifierrest};
 7274: 	    }
 7275: # ----------------------------------------------------------------- user.access
 7276:         } elsif ($space eq 'access') {
 7277: 	    # FIXME - not supporting calls for a specific user
 7278:             return &allowed($qualifier,$rest);
 7279: # ------------------------------------------ user.preferences, user.environment
 7280:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 7281: 	    if (($uname eq $env{'user.name'}) &&
 7282: 		($udom eq $env{'user.domain'})) {
 7283: 		return $env{join('.',('environment',$qualifierrest))};
 7284: 	    } else {
 7285: 		my %returnhash;
 7286: 		if (!$publicuser) {
 7287: 		    %returnhash=&userenvironment($udom,$uname,
 7288: 						 $qualifierrest);
 7289: 		}
 7290: 		return $returnhash{$qualifierrest};
 7291: 	    }
 7292: # ----------------------------------------------------------------- user.course
 7293:         } elsif ($space eq 'course') {
 7294: 	    # FIXME - not supporting calls for a specific user
 7295:             return $env{join('.',('request.course',$qualifier))};
 7296: # ------------------------------------------------------------------- user.role
 7297:         } elsif ($space eq 'role') {
 7298: 	    # FIXME - not supporting calls for a specific user
 7299:             my ($role,$where)=split(/\./,$env{'request.role'});
 7300:             if ($qualifier eq 'value') {
 7301: 		return $role;
 7302:             } elsif ($qualifier eq 'extent') {
 7303:                 return $where;
 7304:             }
 7305: # ----------------------------------------------------------------- user.domain
 7306:         } elsif ($space eq 'domain') {
 7307:             return $udom;
 7308: # ------------------------------------------------------------------- user.name
 7309:         } elsif ($space eq 'name') {
 7310:             return $uname;
 7311: # ---------------------------------------------------- Any other user namespace
 7312:         } else {
 7313: 	    my %reply;
 7314: 	    if (!$publicuser) {
 7315: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 7316: 	    }
 7317: 	    return $reply{$qualifierrest};
 7318:         }
 7319:     } elsif ($realm eq 'query') {
 7320: # ---------------------------------------------- pull stuff out of query string
 7321:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 7322: 						[$spacequalifierrest]);
 7323: 	return $env{'form.'.$spacequalifierrest}; 
 7324:    } elsif ($realm eq 'request') {
 7325: # ------------------------------------------------------------- request.browser
 7326:         if ($space eq 'browser') {
 7327: 	    if ($qualifier eq 'textremote') {
 7328: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 7329: 		    return 1;
 7330: 		} else {
 7331: 		    return 0;
 7332: 		}
 7333: 	    } else {
 7334: 		return $env{'browser.'.$qualifier};
 7335: 	    }
 7336: # ------------------------------------------------------------ request.filename
 7337:         } else {
 7338:             return $env{'request.'.$spacequalifierrest};
 7339:         }
 7340:     } elsif ($realm eq 'course') {
 7341: # ---------------------------------------------------------- course.description
 7342:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 7343:     } elsif ($realm eq 'resource') {
 7344: 
 7345: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 7346: 	    if (!$symbparm) { $symbparm=&symbread(); }
 7347: 	}
 7348: 
 7349: 	if ($space eq 'title') {
 7350: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 7351: 	    return &gettitle($symbparm);
 7352: 	}
 7353: 	
 7354: 	if ($space eq 'map') {
 7355: 	    my ($map) = &decode_symb($symbparm);
 7356: 	    return &symbread($map);
 7357: 	}
 7358: 	if ($space eq 'filename') {
 7359: 	    if ($symbparm) {
 7360: 		return &clutter((&decode_symb($symbparm))[2]);
 7361: 	    }
 7362: 	    return &hreflocation('',$env{'request.filename'});
 7363: 	}
 7364: 
 7365: 	my ($section, $group, @groups);
 7366: 	my ($courselevelm,$courselevel);
 7367: 	if ($symbparm && defined($courseid) && 
 7368: 	    $courseid eq $env{'request.course.id'}) {
 7369: 
 7370: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 7371: 
 7372: # ----------------------------------------------------- Cascading lookup scheme
 7373: 	    my $symbp=$symbparm;
 7374: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 7375: 
 7376: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 7377: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 7378: 
 7379: 	    if (($env{'user.name'} eq $uname) &&
 7380: 		($env{'user.domain'} eq $udom)) {
 7381: 		$section=$env{'request.course.sec'};
 7382:                 @groups = split(/:/,$env{'request.course.groups'});  
 7383:                 @groups=&sort_course_groups($courseid,@groups); 
 7384: 	    } else {
 7385: 		if (! defined($usection)) {
 7386: 		    $section=&getsection($udom,$uname,$courseid);
 7387: 		} else {
 7388: 		    $section = $usection;
 7389: 		}
 7390:                 @groups = &get_users_groups($udom,$uname,$courseid);
 7391: 	    }
 7392: 
 7393: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 7394: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 7395: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 7396: 
 7397: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 7398: 	    my $courselevelr=$courseid.'.'.$symbparm;
 7399: 	    $courselevelm=$courseid.'.'.$mapparm;
 7400: 
 7401: # ----------------------------------------------------------- first, check user
 7402: 
 7403: 	    my $userreply=&resdata($uname,$udom,'user',
 7404: 				       ([$courselevelr,'resource'],
 7405: 					[$courselevelm,'map'     ],
 7406: 					[$courselevel, 'course'  ]));
 7407: 	    if (defined($userreply)) { return &get_reply($userreply); }
 7408: 
 7409: # ------------------------------------------------ second, check some of course
 7410:             my $coursereply;
 7411:             if (@groups > 0) {
 7412:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 7413:                                        $mapparm,$spacequalifierrest);
 7414:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 7415:             }
 7416: 
 7417: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7418: 				  $env{'course.'.$courseid.'.domain'},
 7419: 				  'course',
 7420: 				  ([$seclevelr,   'resource'],
 7421: 				   [$seclevelm,   'map'     ],
 7422: 				   [$seclevel,    'course'  ],
 7423: 				   [$courselevelr,'resource']));
 7424: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7425: 
 7426: # ------------------------------------------------------ third, check map parms
 7427: 	    my %parmhash=();
 7428: 	    my $thisparm='';
 7429: 	    if (tie(%parmhash,'GDBM_File',
 7430: 		    $env{'request.course.fn'}.'_parms.db',
 7431: 		    &GDBM_READER(),0640)) {
 7432: 		$thisparm=$parmhash{$symbparm};
 7433: 		untie(%parmhash);
 7434: 	    }
 7435: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 7436: 	}
 7437: # ------------------------------------------ fourth, look in resource metadata
 7438: 
 7439: 	$spacequalifierrest=~s/\./\_/;
 7440: 	my $filename;
 7441: 	if (!$symbparm) { $symbparm=&symbread(); }
 7442: 	if ($symbparm) {
 7443: 	    $filename=(&decode_symb($symbparm))[2];
 7444: 	} else {
 7445: 	    $filename=$env{'request.filename'};
 7446: 	}
 7447: 	my $metadata=&metadata($filename,$spacequalifierrest);
 7448: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7449: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 7450: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7451: 
 7452: # ---------------------------------------------- fourth, look in rest of course
 7453: 	if ($symbparm && defined($courseid) && 
 7454: 	    $courseid eq $env{'request.course.id'}) {
 7455: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7456: 				     $env{'course.'.$courseid.'.domain'},
 7457: 				     'course',
 7458: 				     ([$courselevelm,'map'   ],
 7459: 				      [$courselevel, 'course']));
 7460: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7461: 	}
 7462: # ------------------------------------------------------------------ Cascade up
 7463: 	unless ($space eq '0') {
 7464: 	    my @parts=split(/_/,$space);
 7465: 	    my $id=pop(@parts);
 7466: 	    my $part=join('_',@parts);
 7467: 	    if ($part eq '') { $part='0'; }
 7468: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 7469: 				 $symbparm,$udom,$uname,$section,1);
 7470: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 7471: 	}
 7472: 	if ($recurse) { return undef; }
 7473: 	my $pack_def=&packages_tab_default($filename,$varname);
 7474: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 7475: # ---------------------------------------------------- Any other user namespace
 7476:     } elsif ($realm eq 'environment') {
 7477: # ----------------------------------------------------------------- environment
 7478: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 7479: 	    return $env{'environment.'.$spacequalifierrest};
 7480: 	} else {
 7481: 	    if ($uname eq 'anonymous' && $udom eq '') {
 7482: 		return '';
 7483: 	    }
 7484: 	    my %returnhash=&userenvironment($udom,$uname,
 7485: 					    $spacequalifierrest);
 7486: 	    return $returnhash{$spacequalifierrest};
 7487: 	}
 7488:     } elsif ($realm eq 'system') {
 7489: # ----------------------------------------------------------------- system.time
 7490: 	if ($space eq 'time') {
 7491: 	    return time;
 7492:         }
 7493:     } elsif ($realm eq 'server') {
 7494: # ----------------------------------------------------------------- system.time
 7495: 	if ($space eq 'name') {
 7496: 	    return $ENV{'SERVER_NAME'};
 7497:         }
 7498:     }
 7499:     return '';
 7500: }
 7501: 
 7502: sub get_reply {
 7503:     my ($reply_value) = @_;
 7504:     if (ref($reply_value) eq 'ARRAY') {
 7505:         if (wantarray) {
 7506: 	    return @$reply_value;
 7507:         }
 7508:         return $reply_value->[0];
 7509:     } else {
 7510:         return $reply_value;
 7511:     }
 7512: }
 7513: 
 7514: sub check_group_parms {
 7515:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 7516:     my @groupitems = ();
 7517:     my $resultitem;
 7518:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 7519:     foreach my $group (@{$groups}) {
 7520:         foreach my $level (@levels) {
 7521:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 7522:              push(@groupitems,[$item,$level->[1]]);
 7523:         }
 7524:     }
 7525:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 7526:                             $env{'course.'.$courseid.'.domain'},
 7527:                                      'course',@groupitems);
 7528:     return $coursereply;
 7529: }
 7530: 
 7531: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 7532:     my ($courseid,@groups) = @_;
 7533:     @groups = sort(@groups);
 7534:     return @groups;
 7535: }
 7536: 
 7537: sub packages_tab_default {
 7538:     my ($uri,$varname)=@_;
 7539:     my (undef,$part,$name)=split(/\./,$varname);
 7540: 
 7541:     my (@extension,@specifics,$do_default);
 7542:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 7543: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 7544: 	if ($pack_type eq 'default') {
 7545: 	    $do_default=1;
 7546: 	} elsif ($pack_type eq 'extension') {
 7547: 	    push(@extension,[$package,$pack_type,$pack_part]);
 7548: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 7549: 	    # only look at packages defaults for packages that this id is
 7550: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 7551: 	}
 7552:     }
 7553:     # first look for a package that matches the requested part id
 7554:     foreach my $package (@specifics) {
 7555: 	my (undef,$pack_type,$pack_part)=@{$package};
 7556: 	next if ($pack_part ne $part);
 7557: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7558: 	    return $packagetab{"$pack_type&$name&default"};
 7559: 	}
 7560:     }
 7561:     # look for any possible matching non extension_ package
 7562:     foreach my $package (@specifics) {
 7563: 	my (undef,$pack_type,$pack_part)=@{$package};
 7564: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7565: 	    return $packagetab{"$pack_type&$name&default"};
 7566: 	}
 7567: 	if ($pack_type eq 'part') { $pack_part='0'; }
 7568: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 7569: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 7570: 	}
 7571:     }
 7572:     # look for any posible extension_ match
 7573:     foreach my $package (@extension) {
 7574: 	my ($package,$pack_type)=@{$package};
 7575: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7576: 	    return $packagetab{"$pack_type&$name&default"};
 7577: 	}
 7578: 	if (defined($packagetab{$package."&$name&default"})) {
 7579: 	    return $packagetab{$package."&$name&default"};
 7580: 	}
 7581:     }
 7582:     # look for a global default setting
 7583:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 7584: 	return $packagetab{"default&$name&default"};
 7585:     }
 7586:     return undef;
 7587: }
 7588: 
 7589: sub add_prefix_and_part {
 7590:     my ($prefix,$part)=@_;
 7591:     my $keyroot;
 7592:     if (defined($prefix) && $prefix !~ /^__/) {
 7593: 	# prefix that has a part already
 7594: 	$keyroot=$prefix;
 7595:     } elsif (defined($prefix)) {
 7596: 	# prefix that is missing a part
 7597: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 7598:     } else {
 7599: 	# no prefix at all
 7600: 	if (defined($part)) { $keyroot='_'.$part; }
 7601:     }
 7602:     return $keyroot;
 7603: }
 7604: 
 7605: # ---------------------------------------------------------------- Get metadata
 7606: 
 7607: my %metaentry;
 7608: sub metadata {
 7609:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 7610:     $uri=&declutter($uri);
 7611:     # if it is a non metadata possible uri return quickly
 7612:     if (($uri eq '') || 
 7613: 	(($uri =~ m|^/*adm/|) && 
 7614: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 7615:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 7616: 	return undef;
 7617:     }
 7618:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 7619: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 7620: 	return undef;
 7621:     }
 7622:     my $filename=$uri;
 7623:     $uri=~s/\.meta$//;
 7624: #
 7625: # Is the metadata already cached?
 7626: # Look at timestamp of caching
 7627: # Everything is cached by the main uri, libraries are never directly cached
 7628: #
 7629:     if (!defined($liburi)) {
 7630: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 7631: 	if (defined($cached)) { return $result->{':'.$what}; }
 7632:     }
 7633:     {
 7634: #
 7635: # Is this a recursive call for a library?
 7636: #
 7637: #	if (! exists($metacache{$uri})) {
 7638: #	    $metacache{$uri}={};
 7639: #	}
 7640: 	my $cachetime = 60*60;
 7641:         if ($liburi) {
 7642: 	    $liburi=&declutter($liburi);
 7643:             $filename=$liburi;
 7644:         } else {
 7645: 	    &devalidate_cache_new('meta',$uri);
 7646: 	    undef(%metaentry);
 7647: 	}
 7648:         my %metathesekeys=();
 7649:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 7650: 	my $metastring;
 7651: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 7652: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 7653: 	    $metastring = 
 7654: 		&Apache::lonnet::ssi_body($which,
 7655: 					  ('grade_target' => 'meta'));
 7656: 	    $cachetime = 1; # only want this cached in the child not long term
 7657: 	} elsif ($uri !~ m -^(editupload)/-) {
 7658: 	    my $file=&filelocation('',&clutter($filename));
 7659: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 7660: 	    $metastring=&getfile($file);
 7661: 	}
 7662:         my $parser=HTML::LCParser->new(\$metastring);
 7663:         my $token;
 7664:         undef %metathesekeys;
 7665:         while ($token=$parser->get_token) {
 7666: 	    if ($token->[0] eq 'S') {
 7667: 		if (defined($token->[2]->{'package'})) {
 7668: #
 7669: # This is a package - get package info
 7670: #
 7671: 		    my $package=$token->[2]->{'package'};
 7672: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7673: 		    if (defined($token->[2]->{'id'})) { 
 7674: 			$keyroot.='_'.$token->[2]->{'id'}; 
 7675: 		    }
 7676: 		    if ($metaentry{':packages'}) {
 7677: 			$metaentry{':packages'}.=','.$package.$keyroot;
 7678: 		    } else {
 7679: 			$metaentry{':packages'}=$package.$keyroot;
 7680: 		    }
 7681: 		    foreach my $pack_entry (keys(%packagetab)) {
 7682: 			my $part=$keyroot;
 7683: 			$part=~s/^\_//;
 7684: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 7685: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 7686: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 7687: 			    # ignore package.tab specified default values
 7688:                             # here &package_tab_default() will fetch those
 7689: 			    if ($subp eq 'default') { next; }
 7690: 			    my $value=$packagetab{$pack_entry};
 7691: 			    my $unikey;
 7692: 			    if ($pack =~ /_0$/) {
 7693: 				$unikey='parameter_0_'.$name;
 7694: 				$part=0;
 7695: 			    } else {
 7696: 				$unikey='parameter'.$keyroot.'_'.$name;
 7697: 			    }
 7698: 			    if ($subp eq 'display') {
 7699: 				$value.=' [Part: '.$part.']';
 7700: 			    }
 7701: 			    $metaentry{':'.$unikey.'.part'}=$part;
 7702: 			    $metathesekeys{$unikey}=1;
 7703: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7704: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 7705: 			    }
 7706: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 7707: 				$metaentry{':'.$unikey}=
 7708: 				    $metaentry{':'.$unikey.'.default'};
 7709: 			    }
 7710: 			}
 7711: 		    }
 7712: 		} else {
 7713: #
 7714: # This is not a package - some other kind of start tag
 7715: #
 7716: 		    my $entry=$token->[1];
 7717: 		    my $unikey;
 7718: 		    if ($entry eq 'import') {
 7719: 			$unikey='';
 7720: 		    } else {
 7721: 			$unikey=$entry;
 7722: 		    }
 7723: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7724: 
 7725: 		    if (defined($token->[2]->{'id'})) { 
 7726: 			$unikey.='_'.$token->[2]->{'id'}; 
 7727: 		    }
 7728: 
 7729: 		    if ($entry eq 'import') {
 7730: #
 7731: # Importing a library here
 7732: #
 7733: 			if ($depthcount<20) {
 7734: 			    my $location=$parser->get_text('/import');
 7735: 			    my $dir=$filename;
 7736: 			    $dir=~s|[^/]*$||;
 7737: 			    $location=&filelocation($dir,$location);
 7738: 			    my $metadata = 
 7739: 				&metadata($uri,'keys', $location,$unikey,
 7740: 					  $depthcount+1);
 7741: 			    foreach my $meta (split(',',$metadata)) {
 7742: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 7743: 				$metathesekeys{$meta}=1;
 7744: 			    }
 7745: 			}
 7746: 		    } else { 
 7747: 			
 7748: 			if (defined($token->[2]->{'name'})) { 
 7749: 			    $unikey.='_'.$token->[2]->{'name'}; 
 7750: 			}
 7751: 			$metathesekeys{$unikey}=1;
 7752: 			foreach my $param (@{$token->[3]}) {
 7753: 			    $metaentry{':'.$unikey.'.'.$param} =
 7754: 				$token->[2]->{$param};
 7755: 			}
 7756: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 7757: 			my $default=$metaentry{':'.$unikey.'.default'};
 7758: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 7759: 		 # only ws inside the tag, and not in default, so use default
 7760: 		 # as value
 7761: 			    $metaentry{':'.$unikey}=$default;
 7762: 			} elsif ( $internaltext =~ /\S/ ) {
 7763: 		  # something interesting inside the tag
 7764: 			    $metaentry{':'.$unikey}=$internaltext;
 7765: 			} else {
 7766: 		  # no interesting values, don't set a default
 7767: 			}
 7768: # end of not-a-package not-a-library import
 7769: 		    }
 7770: # end of not-a-package start tag
 7771: 		}
 7772: # the next is the end of "start tag"
 7773: 	    }
 7774: 	}
 7775: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 7776: 	$extension = lc($extension);
 7777: 	if ($extension eq 'htm') { $extension='html'; }
 7778: 
 7779: 	foreach my $key (keys(%packagetab)) {
 7780: 	    #no specific packages #how's our extension
 7781: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 7782: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 7783: 					 \%metathesekeys);
 7784: 	}
 7785: 
 7786: 	if (!exists($metaentry{':packages'})
 7787: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 7788: 	    foreach my $key (keys(%packagetab)) {
 7789: 		#no specific packages well let's get default then
 7790: 		if ($key!~/^default&/) { next; }
 7791: 		&metadata_create_package_def($uri,$key,'default',
 7792: 					     \%metathesekeys);
 7793: 	    }
 7794: 	}
 7795: # are there custom rights to evaluate
 7796: 	if ($metaentry{':copyright'} eq 'custom') {
 7797: 
 7798:     #
 7799:     # Importing a rights file here
 7800:     #
 7801: 	    unless ($depthcount) {
 7802: 		my $location=$metaentry{':customdistributionfile'};
 7803: 		my $dir=$filename;
 7804: 		$dir=~s|[^/]*$||;
 7805: 		$location=&filelocation($dir,$location);
 7806: 		my $rights_metadata =
 7807: 		    &metadata($uri,'keys',$location,'_rights',
 7808: 			      $depthcount+1);
 7809: 		foreach my $rights (split(',',$rights_metadata)) {
 7810: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 7811: 		    $metathesekeys{$rights}=1;
 7812: 		}
 7813: 	    }
 7814: 	}
 7815: 	# uniqifiy package listing
 7816: 	my %seen;
 7817: 	my @uniq_packages =
 7818: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 7819: 	$metaentry{':packages'} = join(',',@uniq_packages);
 7820: 
 7821: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 7822: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 7823: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 7824: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 7825: # this is the end of "was not already recently cached
 7826:     }
 7827:     return $metaentry{':'.$what};
 7828: }
 7829: 
 7830: sub metadata_create_package_def {
 7831:     my ($uri,$key,$package,$metathesekeys)=@_;
 7832:     my ($pack,$name,$subp)=split(/\&/,$key);
 7833:     if ($subp eq 'default') { next; }
 7834:     
 7835:     if (defined($metaentry{':packages'})) {
 7836: 	$metaentry{':packages'}.=','.$package;
 7837:     } else {
 7838: 	$metaentry{':packages'}=$package;
 7839:     }
 7840:     my $value=$packagetab{$key};
 7841:     my $unikey;
 7842:     $unikey='parameter_0_'.$name;
 7843:     $metaentry{':'.$unikey.'.part'}=0;
 7844:     $$metathesekeys{$unikey}=1;
 7845:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7846: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 7847:     }
 7848:     if (defined($metaentry{':'.$unikey.'.default'})) {
 7849: 	$metaentry{':'.$unikey}=
 7850: 	    $metaentry{':'.$unikey.'.default'};
 7851:     }
 7852: }
 7853: 
 7854: sub metadata_generate_part0 {
 7855:     my ($metadata,$metacache,$uri) = @_;
 7856:     my %allnames;
 7857:     foreach my $metakey (keys(%$metadata)) {
 7858: 	if ($metakey=~/^parameter\_(.*)/) {
 7859: 	  my $part=$$metacache{':'.$metakey.'.part'};
 7860: 	  my $name=$$metacache{':'.$metakey.'.name'};
 7861: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 7862: 	    $allnames{$name}=$part;
 7863: 	  }
 7864: 	}
 7865:     }
 7866:     foreach my $name (keys(%allnames)) {
 7867:       $$metadata{"parameter_0_$name"}=1;
 7868:       my $key=":parameter_0_$name";
 7869:       $$metacache{"$key.part"}='0';
 7870:       $$metacache{"$key.name"}=$name;
 7871:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 7872: 					   $allnames{$name}.'_'.$name.
 7873: 					   '.type'};
 7874:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 7875: 			     '.display'};
 7876:       my $expr='[Part: '.$allnames{$name}.']';
 7877:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 7878:       $$metacache{"$key.display"}=$olddis;
 7879:     }
 7880: }
 7881: 
 7882: # ------------------------------------------------------ Devalidate title cache
 7883: 
 7884: sub devalidate_title_cache {
 7885:     my ($url)=@_;
 7886:     if (!$env{'request.course.id'}) { return; }
 7887:     my $symb=&symbread($url);
 7888:     if (!$symb) { return; }
 7889:     my $key=$env{'request.course.id'}."\0".$symb;
 7890:     &devalidate_cache_new('title',$key);
 7891: }
 7892: 
 7893: # ------------------------------------------------- Get the title of a resource
 7894: 
 7895: sub gettitle {
 7896:     my $urlsymb=shift;
 7897:     my $symb=&symbread($urlsymb);
 7898:     if ($symb) {
 7899: 	my $key=$env{'request.course.id'}."\0".$symb;
 7900: 	my ($result,$cached)=&is_cached_new('title',$key);
 7901: 	if (defined($cached)) { 
 7902: 	    return $result;
 7903: 	}
 7904: 	my ($map,$resid,$url)=&decode_symb($symb);
 7905: 	my $title='';
 7906: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 7907: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 7908: 	} else {
 7909: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7910: 		    &GDBM_READER(),0640)) {
 7911: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 7912: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 7913: 		untie(%bighash);
 7914: 	    }
 7915: 	}
 7916: 	$title=~s/\&colon\;/\:/gs;
 7917: 	if ($title) {
 7918: 	    return &do_cache_new('title',$key,$title,600);
 7919: 	}
 7920: 	$urlsymb=$url;
 7921:     }
 7922:     my $title=&metadata($urlsymb,'title');
 7923:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 7924:     return $title;
 7925: }
 7926: 
 7927: sub get_slot {
 7928:     my ($which,$cnum,$cdom)=@_;
 7929:     if (!$cnum || !$cdom) {
 7930: 	(undef,my $courseid)=&whichuser();
 7931: 	$cdom=$env{'course.'.$courseid.'.domain'};
 7932: 	$cnum=$env{'course.'.$courseid.'.num'};
 7933:     }
 7934:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 7935:     my %slotinfo;
 7936:     if (exists($remembered{$key})) {
 7937: 	$slotinfo{$which} = $remembered{$key};
 7938:     } else {
 7939: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 7940: 	&Apache::lonhomework::showhash(%slotinfo);
 7941: 	my ($tmp)=keys(%slotinfo);
 7942: 	if ($tmp=~/^error:/) { return (); }
 7943: 	$remembered{$key} = $slotinfo{$which};
 7944:     }
 7945:     if (ref($slotinfo{$which}) eq 'HASH') {
 7946: 	return %{$slotinfo{$which}};
 7947:     }
 7948:     return $slotinfo{$which};
 7949: }
 7950: # ------------------------------------------------- Update symbolic store links
 7951: 
 7952: sub symblist {
 7953:     my ($mapname,%newhash)=@_;
 7954:     $mapname=&deversion(&declutter($mapname));
 7955:     my %hash;
 7956:     if (($env{'request.course.fn'}) && (%newhash)) {
 7957:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7958:                       &GDBM_WRCREAT(),0640)) {
 7959: 	    foreach my $url (keys(%newhash)) {
 7960: 		next if ($url eq 'last_known'
 7961: 			 && $env{'form.no_update_last_known'});
 7962: 		$hash{declutter($url)}=&encode_symb($mapname,
 7963: 						    $newhash{$url}->[1],
 7964: 						    $newhash{$url}->[0]);
 7965:             }
 7966:             if (untie(%hash)) {
 7967: 		return 'ok';
 7968:             }
 7969:         }
 7970:     }
 7971:     return 'error';
 7972: }
 7973: 
 7974: # --------------------------------------------------------------- Verify a symb
 7975: 
 7976: sub symbverify {
 7977:     my ($symb,$thisurl)=@_;
 7978:     my $thisfn=$thisurl;
 7979:     $thisfn=&declutter($thisfn);
 7980: # direct jump to resource in page or to a sequence - will construct own symbs
 7981:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 7982: # check URL part
 7983:     my ($map,$resid,$url)=&decode_symb($symb);
 7984: 
 7985:     unless ($url eq $thisfn) { return 0; }
 7986: 
 7987:     $symb=&symbclean($symb);
 7988:     $thisurl=&deversion($thisurl);
 7989:     $thisfn=&deversion($thisfn);
 7990: 
 7991:     my %bighash;
 7992:     my $okay=0;
 7993: 
 7994:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7995:                             &GDBM_READER(),0640)) {
 7996:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 7997:         unless ($ids) { 
 7998:            $ids=$bighash{'ids_/'.$thisurl};
 7999:         }
 8000:         if ($ids) {
 8001: # ------------------------------------------------------------------- Has ID(s)
 8002: 	    foreach my $id (split(/\,/,$ids)) {
 8003: 	       my ($mapid,$resid)=split(/\./,$id);
 8004:                if (
 8005:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 8006:    eq $symb) { 
 8007: 		   if (($env{'request.role.adv'}) ||
 8008: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 8009: 		       $okay=1; 
 8010: 		   }
 8011: 	       }
 8012: 	   }
 8013:         }
 8014: 	untie(%bighash);
 8015:     }
 8016:     return $okay;
 8017: }
 8018: 
 8019: # --------------------------------------------------------------- Clean-up symb
 8020: 
 8021: sub symbclean {
 8022:     my $symb=shift;
 8023:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 8024: # remove version from map
 8025:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 8026: 
 8027: # remove version from URL
 8028:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 8029: 
 8030: # remove wrapper
 8031: 
 8032:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 8033:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 8034:     return $symb;
 8035: }
 8036: 
 8037: # ---------------------------------------------- Split symb to find map and url
 8038: 
 8039: sub encode_symb {
 8040:     my ($map,$resid,$url)=@_;
 8041:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 8042: }
 8043: 
 8044: sub decode_symb {
 8045:     my $symb=shift;
 8046:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 8047:     my ($map,$resid,$url)=split(/___/,$symb);
 8048:     return (&fixversion($map),$resid,&fixversion($url));
 8049: }
 8050: 
 8051: sub fixversion {
 8052:     my $fn=shift;
 8053:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 8054:     my %bighash;
 8055:     my $uri=&clutter($fn);
 8056:     my $key=$env{'request.course.id'}.'_'.$uri;
 8057: # is this cached?
 8058:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 8059:     if (defined($cached)) { return $result; }
 8060: # unfortunately not cached, or expired
 8061:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8062: 	    &GDBM_READER(),0640)) {
 8063:  	if ($bighash{'version_'.$uri}) {
 8064:  	    my $version=$bighash{'version_'.$uri};
 8065:  	    unless (($version eq 'mostrecent') || 
 8066: 		    ($version==&getversion($uri))) {
 8067:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 8068:  	    }
 8069:  	}
 8070:  	untie %bighash;
 8071:     }
 8072:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 8073: }
 8074: 
 8075: sub deversion {
 8076:     my $url=shift;
 8077:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 8078:     return $url;
 8079: }
 8080: 
 8081: # ------------------------------------------------------ Return symb list entry
 8082: 
 8083: sub symbread {
 8084:     my ($thisfn,$donotrecurse)=@_;
 8085:     my $cache_str='request.symbread.cached.'.$thisfn;
 8086:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 8087: # no filename provided? try from environment
 8088:     unless ($thisfn) {
 8089:         if ($env{'request.symb'}) {
 8090: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 8091: 	}
 8092: 	$thisfn=$env{'request.filename'};
 8093:     }
 8094:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8095: # is that filename actually a symb? Verify, clean, and return
 8096:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 8097: 	if (&symbverify($thisfn,$1)) {
 8098: 	    return $env{$cache_str}=&symbclean($thisfn);
 8099: 	}
 8100:     }
 8101:     $thisfn=declutter($thisfn);
 8102:     my %hash;
 8103:     my %bighash;
 8104:     my $syval='';
 8105:     if (($env{'request.course.fn'}) && ($thisfn)) {
 8106:         my $targetfn = $thisfn;
 8107:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 8108:             $targetfn = 'adm/wrapper/'.$thisfn;
 8109:         }
 8110: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 8111: 	    $targetfn=$1;
 8112: 	}
 8113:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 8114:                       &GDBM_READER(),0640)) {
 8115: 	    $syval=$hash{$targetfn};
 8116:             untie(%hash);
 8117:         }
 8118: # ---------------------------------------------------------- There was an entry
 8119:         if ($syval) {
 8120: 	    #unless ($syval=~/\_\d+$/) {
 8121: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 8122: 		    #&appenv({'request.ambiguous' => $thisfn});
 8123: 		    #return $env{$cache_str}='';
 8124: 		#}    
 8125: 		#$syval.=$1;
 8126: 	    #}
 8127:         } else {
 8128: # ------------------------------------------------------- Was not in symb table
 8129:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8130:                             &GDBM_READER(),0640)) {
 8131: # ---------------------------------------------- Get ID(s) for current resource
 8132:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 8133:               unless ($ids) { 
 8134:                  $ids=$bighash{'ids_/'.$thisfn};
 8135:               }
 8136:               unless ($ids) {
 8137: # alias?
 8138: 		  $ids=$bighash{'mapalias_'.$thisfn};
 8139:               }
 8140:               if ($ids) {
 8141: # ------------------------------------------------------------------- Has ID(s)
 8142:                  my @possibilities=split(/\,/,$ids);
 8143:                  if ($#possibilities==0) {
 8144: # ----------------------------------------------- There is only one possibility
 8145: 		     my ($mapid,$resid)=split(/\./,$ids);
 8146: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 8147: 						    $resid,$thisfn);
 8148:                  } elsif (!$donotrecurse) {
 8149: # ------------------------------------------ There is more than one possibility
 8150:                      my $realpossible=0;
 8151:                      foreach my $id (@possibilities) {
 8152: 			 my $file=$bighash{'src_'.$id};
 8153:                          if (&allowed('bre',$file)) {
 8154:          		    my ($mapid,$resid)=split(/\./,$id);
 8155:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 8156: 				$realpossible++;
 8157:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 8158: 						    $resid,$thisfn);
 8159:                             }
 8160: 			 }
 8161:                      }
 8162: 		     if ($realpossible!=1) { $syval=''; }
 8163:                  } else {
 8164:                      $syval='';
 8165:                  }
 8166: 	      }
 8167:               untie(%bighash)
 8168:            }
 8169:         }
 8170:         if ($syval) {
 8171: 	    return $env{$cache_str}=$syval;
 8172:         }
 8173:     }
 8174:     &appenv({'request.ambiguous' => $thisfn});
 8175:     return $env{$cache_str}='';
 8176: }
 8177: 
 8178: # ---------------------------------------------------------- Return random seed
 8179: 
 8180: sub numval {
 8181:     my $txt=shift;
 8182:     $txt=~tr/A-J/0-9/;
 8183:     $txt=~tr/a-j/0-9/;
 8184:     $txt=~tr/K-T/0-9/;
 8185:     $txt=~tr/k-t/0-9/;
 8186:     $txt=~tr/U-Z/0-5/;
 8187:     $txt=~tr/u-z/0-5/;
 8188:     $txt=~s/\D//g;
 8189:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 8190:     return int($txt);
 8191: }
 8192: 
 8193: sub numval2 {
 8194:     my $txt=shift;
 8195:     $txt=~tr/A-J/0-9/;
 8196:     $txt=~tr/a-j/0-9/;
 8197:     $txt=~tr/K-T/0-9/;
 8198:     $txt=~tr/k-t/0-9/;
 8199:     $txt=~tr/U-Z/0-5/;
 8200:     $txt=~tr/u-z/0-5/;
 8201:     $txt=~s/\D//g;
 8202:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8203:     my $total;
 8204:     foreach my $val (@txts) { $total+=$val; }
 8205:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 8206:     return int($total);
 8207: }
 8208: 
 8209: sub numval3 {
 8210:     use integer;
 8211:     my $txt=shift;
 8212:     $txt=~tr/A-J/0-9/;
 8213:     $txt=~tr/a-j/0-9/;
 8214:     $txt=~tr/K-T/0-9/;
 8215:     $txt=~tr/k-t/0-9/;
 8216:     $txt=~tr/U-Z/0-5/;
 8217:     $txt=~tr/u-z/0-5/;
 8218:     $txt=~s/\D//g;
 8219:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8220:     my $total;
 8221:     foreach my $val (@txts) { $total+=$val; }
 8222:     if ($_64bit) { $total=(($total<<32)>>32); }
 8223:     return $total;
 8224: }
 8225: 
 8226: sub digest {
 8227:     my ($data)=@_;
 8228:     my $digest=&Digest::MD5::md5($data);
 8229:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 8230:     my ($e,$f);
 8231:     {
 8232:         use integer;
 8233:         $e=($a+$b);
 8234:         $f=($c+$d);
 8235:         if ($_64bit) {
 8236:             $e=(($e<<32)>>32);
 8237:             $f=(($f<<32)>>32);
 8238:         }
 8239:     }
 8240:     if (wantarray) {
 8241: 	return ($e,$f);
 8242:     } else {
 8243: 	my $g;
 8244: 	{
 8245: 	    use integer;
 8246: 	    $g=($e+$f);
 8247: 	    if ($_64bit) {
 8248: 		$g=(($g<<32)>>32);
 8249: 	    }
 8250: 	}
 8251: 	return $g;
 8252:     }
 8253: }
 8254: 
 8255: sub latest_rnd_algorithm_id {
 8256:     return '64bit5';
 8257: }
 8258: 
 8259: sub get_rand_alg {
 8260:     my ($courseid)=@_;
 8261:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 8262:     if ($courseid) {
 8263: 	return $env{"course.$courseid.rndseed"};
 8264:     }
 8265:     return &latest_rnd_algorithm_id();
 8266: }
 8267: 
 8268: sub validCODE {
 8269:     my ($CODE)=@_;
 8270:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 8271:     return 0;
 8272: }
 8273: 
 8274: sub getCODE {
 8275:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 8276:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 8277: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 8278: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 8279: 	return $Apache::lonhomework::history{'resource.CODE'};
 8280:     }
 8281:     return undef;
 8282: }
 8283: 
 8284: sub rndseed {
 8285:     my ($symb,$courseid,$domain,$username)=@_;
 8286:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 8287:     if (!defined($symb)) {
 8288: 	unless ($symb=$wsymb) { return time; }
 8289:     }
 8290:     if (!$courseid) { $courseid=$wcourseid; }
 8291:     if (!$domain) { $domain=$wdomain; }
 8292:     if (!$username) { $username=$wusername }
 8293:     my $which=&get_rand_alg();
 8294: 
 8295:     if (defined(&getCODE())) {
 8296: 	if ($which eq '64bit5') {
 8297: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 8298: 	} elsif ($which eq '64bit4') {
 8299: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 8300: 	} else {
 8301: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 8302: 	}
 8303:     } elsif ($which eq '64bit5') {
 8304: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 8305:     } elsif ($which eq '64bit4') {
 8306: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 8307:     } elsif ($which eq '64bit3') {
 8308: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 8309:     } elsif ($which eq '64bit2') {
 8310: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 8311:     } elsif ($which eq '64bit') {
 8312: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 8313:     }
 8314:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 8315: }
 8316: 
 8317: sub rndseed_32bit {
 8318:     my ($symb,$courseid,$domain,$username)=@_;
 8319:     {
 8320: 	use integer;
 8321: 	my $symbchck=unpack("%32C*",$symb) << 27;
 8322: 	my $symbseed=numval($symb) << 22;
 8323: 	my $namechck=unpack("%32C*",$username) << 17;
 8324: 	my $nameseed=numval($username) << 12;
 8325: 	my $domainseed=unpack("%32C*",$domain) << 7;
 8326: 	my $courseseed=unpack("%32C*",$courseid);
 8327: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 8328: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8329: 	#&logthis("rndseed :$num:$symb");
 8330: 	if ($_64bit) { $num=(($num<<32)>>32); }
 8331: 	return $num;
 8332:     }
 8333: }
 8334: 
 8335: sub rndseed_64bit {
 8336:     my ($symb,$courseid,$domain,$username)=@_;
 8337:     {
 8338: 	use integer;
 8339: 	my $symbchck=unpack("%32S*",$symb) << 21;
 8340: 	my $symbseed=numval($symb) << 10;
 8341: 	my $namechck=unpack("%32S*",$username);
 8342: 	
 8343: 	my $nameseed=numval($username) << 21;
 8344: 	my $domainseed=unpack("%32S*",$domain) << 10;
 8345: 	my $courseseed=unpack("%32S*",$courseid);
 8346: 	
 8347: 	my $num1=$symbchck+$symbseed+$namechck;
 8348: 	my $num2=$nameseed+$domainseed+$courseseed;
 8349: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8350: 	#&logthis("rndseed :$num:$symb");
 8351: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8352: 	return "$num1,$num2";
 8353:     }
 8354: }
 8355: 
 8356: sub rndseed_64bit2 {
 8357:     my ($symb,$courseid,$domain,$username)=@_;
 8358:     {
 8359: 	use integer;
 8360: 	# strings need to be an even # of cahracters long, it it is odd the
 8361:         # last characters gets thrown away
 8362: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8363: 	my $symbseed=numval($symb) << 10;
 8364: 	my $namechck=unpack("%32S*",$username.' ');
 8365: 	
 8366: 	my $nameseed=numval($username) << 21;
 8367: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8368: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8369: 	
 8370: 	my $num1=$symbchck+$symbseed+$namechck;
 8371: 	my $num2=$nameseed+$domainseed+$courseseed;
 8372: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8373: 	#&logthis("rndseed :$num:$symb");
 8374: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8375: 	return "$num1,$num2";
 8376:     }
 8377: }
 8378: 
 8379: sub rndseed_64bit3 {
 8380:     my ($symb,$courseid,$domain,$username)=@_;
 8381:     {
 8382: 	use integer;
 8383: 	# strings need to be an even # of cahracters long, it it is odd the
 8384:         # last characters gets thrown away
 8385: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8386: 	my $symbseed=numval2($symb) << 10;
 8387: 	my $namechck=unpack("%32S*",$username.' ');
 8388: 	
 8389: 	my $nameseed=numval2($username) << 21;
 8390: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8391: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8392: 	
 8393: 	my $num1=$symbchck+$symbseed+$namechck;
 8394: 	my $num2=$nameseed+$domainseed+$courseseed;
 8395: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8396: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8397: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8398: 	
 8399: 	return "$num1:$num2";
 8400:     }
 8401: }
 8402: 
 8403: sub rndseed_64bit4 {
 8404:     my ($symb,$courseid,$domain,$username)=@_;
 8405:     {
 8406: 	use integer;
 8407: 	# strings need to be an even # of cahracters long, it it is odd the
 8408:         # last characters gets thrown away
 8409: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8410: 	my $symbseed=numval3($symb) << 10;
 8411: 	my $namechck=unpack("%32S*",$username.' ');
 8412: 	
 8413: 	my $nameseed=numval3($username) << 21;
 8414: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8415: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8416: 	
 8417: 	my $num1=$symbchck+$symbseed+$namechck;
 8418: 	my $num2=$nameseed+$domainseed+$courseseed;
 8419: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8420: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8421: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8422: 	
 8423: 	return "$num1:$num2";
 8424:     }
 8425: }
 8426: 
 8427: sub rndseed_64bit5 {
 8428:     my ($symb,$courseid,$domain,$username)=@_;
 8429:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 8430:     return "$num1:$num2";
 8431: }
 8432: 
 8433: sub rndseed_CODE_64bit {
 8434:     my ($symb,$courseid,$domain,$username)=@_;
 8435:     {
 8436: 	use integer;
 8437: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8438: 	my $symbseed=numval2($symb);
 8439: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8440: 	my $CODEseed=numval(&getCODE());
 8441: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8442: 	my $num1=$symbseed+$CODEchck;
 8443: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8444: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8445: 	#&logthis("rndseed :$num1:$num2:$symb");
 8446: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8447: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8448: 	return "$num1:$num2";
 8449:     }
 8450: }
 8451: 
 8452: sub rndseed_CODE_64bit4 {
 8453:     my ($symb,$courseid,$domain,$username)=@_;
 8454:     {
 8455: 	use integer;
 8456: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8457: 	my $symbseed=numval3($symb);
 8458: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8459: 	my $CODEseed=numval3(&getCODE());
 8460: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8461: 	my $num1=$symbseed+$CODEchck;
 8462: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8463: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8464: 	#&logthis("rndseed :$num1:$num2:$symb");
 8465: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8466: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8467: 	return "$num1:$num2";
 8468:     }
 8469: }
 8470: 
 8471: sub rndseed_CODE_64bit5 {
 8472:     my ($symb,$courseid,$domain,$username)=@_;
 8473:     my $code = &getCODE();
 8474:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 8475:     return "$num1:$num2";
 8476: }
 8477: 
 8478: sub setup_random_from_rndseed {
 8479:     my ($rndseed)=@_;
 8480:     if ($rndseed =~/([,:])/) {
 8481: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 8482: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 8483:     } else {
 8484: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 8485:     }
 8486: }
 8487: 
 8488: sub latest_receipt_algorithm_id {
 8489:     return 'receipt3';
 8490: }
 8491: 
 8492: sub recunique {
 8493:     my $fucourseid=shift;
 8494:     my $unique;
 8495:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 8496: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8497: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 8498:     } else {
 8499: 	$unique=$perlvar{'lonReceipt'};
 8500:     }
 8501:     return unpack("%32C*",$unique);
 8502: }
 8503: 
 8504: sub recprefix {
 8505:     my $fucourseid=shift;
 8506:     my $prefix;
 8507:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 8508: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8509: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 8510:     } else {
 8511: 	$prefix=$perlvar{'lonHostID'};
 8512:     }
 8513:     return unpack("%32C*",$prefix);
 8514: }
 8515: 
 8516: sub ireceipt {
 8517:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 8518: 
 8519:     my $return =&recprefix($fucourseid).'-';
 8520: 
 8521:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 8522: 	$env{'request.state'} eq 'construct') {
 8523: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 8524: 	return $return;
 8525:     }
 8526: 
 8527:     my $cuname=unpack("%32C*",$funame);
 8528:     my $cudom=unpack("%32C*",$fudom);
 8529:     my $cucourseid=unpack("%32C*",$fucourseid);
 8530:     my $cusymb=unpack("%32C*",$fusymb);
 8531:     my $cunique=&recunique($fucourseid);
 8532:     my $cpart=unpack("%32S*",$part);
 8533:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 8534: 
 8535: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 8536: 			       
 8537: 	$return.= ($cunique%$cuname+
 8538: 		   $cunique%$cudom+
 8539: 		   $cusymb%$cuname+
 8540: 		   $cusymb%$cudom+
 8541: 		   $cucourseid%$cuname+
 8542: 		   $cucourseid%$cudom+
 8543: 		   $cpart%$cuname+
 8544: 		   $cpart%$cudom);
 8545:     } else {
 8546: 	$return.= ($cunique%$cuname+
 8547: 		   $cunique%$cudom+
 8548: 		   $cusymb%$cuname+
 8549: 		   $cusymb%$cudom+
 8550: 		   $cucourseid%$cuname+
 8551: 		   $cucourseid%$cudom);
 8552:     }
 8553:     return $return;
 8554: }
 8555: 
 8556: sub receipt {
 8557:     my ($part)=@_;
 8558:     my ($symb,$courseid,$domain,$name) = &whichuser();
 8559:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 8560: }
 8561: 
 8562: sub whichuser {
 8563:     my ($passedsymb)=@_;
 8564:     my ($symb,$courseid,$domain,$name,$publicuser);
 8565:     if (defined($env{'form.grade_symb'})) {
 8566: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 8567: 	my $allowed=&allowed('vgr',$tmp_courseid);
 8568: 	if (!$allowed &&
 8569: 	    exists($env{'request.course.sec'}) &&
 8570: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 8571: 	    $allowed=&allowed('vgr',$tmp_courseid.
 8572: 			      '/'.$env{'request.course.sec'});
 8573: 	}
 8574: 	if ($allowed) {
 8575: 	    ($symb)=&get_env_multiple('form.grade_symb');
 8576: 	    $courseid=$tmp_courseid;
 8577: 	    ($domain)=&get_env_multiple('form.grade_domain');
 8578: 	    ($name)=&get_env_multiple('form.grade_username');
 8579: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 8580: 	}
 8581:     }
 8582:     if (!$passedsymb) {
 8583: 	$symb=&symbread();
 8584:     } else {
 8585: 	$symb=$passedsymb;
 8586:     }
 8587:     $courseid=$env{'request.course.id'};
 8588:     $domain=$env{'user.domain'};
 8589:     $name=$env{'user.name'};
 8590:     if ($name eq 'public' && $domain eq 'public') {
 8591: 	if (!defined($env{'form.username'})) {
 8592: 	    $env{'form.username'}.=time.rand(10000000);
 8593: 	}
 8594: 	$name.=$env{'form.username'};
 8595:     }
 8596:     return ($symb,$courseid,$domain,$name,$publicuser);
 8597: 
 8598: }
 8599: 
 8600: # ------------------------------------------------------------ Serves up a file
 8601: # returns either the contents of the file or 
 8602: # -1 if the file doesn't exist
 8603: #
 8604: # if the target is a file that was uploaded via DOCS, 
 8605: # a check will be made to see if a current copy exists on the local server,
 8606: # if it does this will be served, otherwise a copy will be retrieved from
 8607: # the home server for the course and stored in /home/httpd/html/userfiles on
 8608: # the local server.   
 8609: 
 8610: sub getfile {
 8611:     my ($file) = @_;
 8612:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8613:     &repcopy($file);
 8614:     return &readfile($file);
 8615: }
 8616: 
 8617: sub repcopy_userfile {
 8618:     my ($file)=@_;
 8619:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8620:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 8621:     my ($cdom,$cnum,$filename) = 
 8622: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 8623:     my $uri="/uploaded/$cdom/$cnum/$filename";
 8624:     if (-e "$file") {
 8625: # we already have a local copy, check it out
 8626: 	my @fileinfo = stat($file);
 8627: 	my $rtncode;
 8628: 	my $info;
 8629: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 8630: 	if ($lwpresp ne 'ok') {
 8631: # there is no such file anymore, even though we had a local copy
 8632: 	    if ($rtncode eq '404') {
 8633: 		unlink($file);
 8634: 	    }
 8635: 	    return -1;
 8636: 	}
 8637: 	if ($info < $fileinfo[9]) {
 8638: # nice, the file we have is up-to-date, just say okay
 8639: 	    return 'ok';
 8640: 	} else {
 8641: # the file is outdated, get rid of it
 8642: 	    unlink($file);
 8643: 	}
 8644:     }
 8645: # one way or the other, at this point, we don't have the file
 8646: # construct the correct path for the file
 8647:     my @parts = ($cdom,$cnum); 
 8648:     if ($filename =~ m|^(.+)/[^/]+$|) {
 8649: 	push @parts, split(/\//,$1);
 8650:     }
 8651:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 8652:     foreach my $part (@parts) {
 8653: 	$path .= '/'.$part;
 8654: 	if (!-e $path) {
 8655: 	    mkdir($path,0770);
 8656: 	}
 8657:     }
 8658: # now the path exists for sure
 8659: # get a user agent
 8660:     my $ua=new LWP::UserAgent;
 8661:     my $transferfile=$file.'.in.transfer';
 8662: # FIXME: this should flock
 8663:     if (-e $transferfile) { return 'ok'; }
 8664:     my $request;
 8665:     $uri=~s/^\///;
 8666:     my $homeserver = &homeserver($cnum,$cdom);
 8667:     my $protocol = $protocol{$homeserver};
 8668:     $protocol = 'http' if ($protocol ne 'https');
 8669:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
 8670:     my $response=$ua->request($request,$transferfile);
 8671: # did it work?
 8672:     if ($response->is_error()) {
 8673: 	unlink($transferfile);
 8674: 	&logthis("Userfile repcopy failed for $uri");
 8675: 	return -1;
 8676:     }
 8677: # worked, rename the transfer file
 8678:     rename($transferfile,$file);
 8679:     return 'ok';
 8680: }
 8681: 
 8682: sub tokenwrapper {
 8683:     my $uri=shift;
 8684:     $uri=~s|^https?\://([^/]+)||;
 8685:     $uri=~s|^/||;
 8686:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 8687:     my $token=$1;
 8688:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 8689:     if ($udom && $uname && $file) {
 8690: 	$file=~s|(\?\.*)*$||;
 8691:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 8692:         my $homeserver = &homeserver($uname,$udom);
 8693:         my $protocol = $protocol{$homeserver};
 8694:         $protocol = 'http' if ($protocol ne 'https');
 8695:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
 8696:                (($uri=~/\?/)?'&':'?').'token='.$token.
 8697:                                '&tokenissued='.$perlvar{'lonHostID'};
 8698:     } else {
 8699:         return '/adm/notfound.html';
 8700:     }
 8701: }
 8702: 
 8703: # call with reqtype HEAD: get last modification time
 8704: # call with reqtype GET: get the file contents
 8705: # Do not call this with reqtype GET for large files! It loads everything into memory
 8706: #
 8707: sub getuploaded {
 8708:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 8709:     $uri=~s/^\///;
 8710:     my $homeserver = &homeserver($cnum,$cdom);
 8711:     my $protocol = $protocol{$homeserver};
 8712:     $protocol = 'http' if ($protocol ne 'https');
 8713:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
 8714:     my $ua=new LWP::UserAgent;
 8715:     my $request=new HTTP::Request($reqtype,$uri);
 8716:     my $response=$ua->request($request);
 8717:     $$rtncode = $response->code;
 8718:     if (! $response->is_success()) {
 8719: 	return 'failed';
 8720:     }      
 8721:     if ($reqtype eq 'HEAD') {
 8722: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 8723:     } elsif ($reqtype eq 'GET') {
 8724: 	$$info = $response->content;
 8725:     }
 8726:     return 'ok';
 8727: }
 8728: 
 8729: sub readfile {
 8730:     my $file = shift;
 8731:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 8732:     my $fh;
 8733:     open($fh,"<$file");
 8734:     my $a='';
 8735:     while (my $line = <$fh>) { $a .= $line; }
 8736:     return $a;
 8737: }
 8738: 
 8739: sub filelocation {
 8740:     my ($dir,$file) = @_;
 8741:     my $location;
 8742:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 8743: 
 8744:     if ($file =~ m-^/adm/-) {
 8745: 	$file=~s-^/adm/wrapper/-/-;
 8746: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8747:     }
 8748: 
 8749:     if ($file=~m:^/~:) { # is a contruction space reference
 8750:         $location = $file;
 8751:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 8752:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 8753: 	# is a correct contruction space reference
 8754:         $location = $file;
 8755:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
 8756:         $location = $file;
 8757:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 8758:         my ($udom,$uname,$filename)=
 8759:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 8760:         my $home=&homeserver($uname,$udom);
 8761:         my $is_me=0;
 8762:         my @ids=&current_machine_ids();
 8763:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 8764:         if ($is_me) {
 8765:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
 8766:         } else {
 8767:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 8768:   	      $udom.'/'.$uname.'/'.$filename;
 8769:         }
 8770:     } elsif ($file =~ m-^/adm/-) {
 8771: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 8772:     } else {
 8773:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8774:         $file=~s:^/res/:/:;
 8775:         if ( !( $file =~ m:^/:) ) {
 8776:             $location = $dir. '/'.$file;
 8777:         } else {
 8778:             $location = '/home/httpd/html/res'.$file;
 8779:         }
 8780:     }
 8781:     $location=~s://+:/:g; # remove duplicate /
 8782:     while ($location=~m{/\.\./}) {
 8783: 	if ($location =~ m{/[^/]+/\.\./}) {
 8784: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 8785: 	} else {
 8786: 	    $location=~ s{/\.\./}{/}g;
 8787: 	}
 8788:     } #remove dir/..
 8789:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 8790:     return $location;
 8791: }
 8792: 
 8793: sub hreflocation {
 8794:     my ($dir,$file)=@_;
 8795:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
 8796: 	$file=filelocation($dir,$file);
 8797:     } elsif ($file=~m-^/adm/-) {
 8798: 	$file=~s-^/adm/wrapper/-/-;
 8799: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8800:     }
 8801:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 8802: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 8803:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 8804: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 8805:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 8806: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 8807: 	    -/uploaded/$1/$2/-x;
 8808:     }
 8809:     if ($file=~ m{^/userfiles/}) {
 8810: 	$file =~ s{^/userfiles/}{/uploaded/};
 8811:     }
 8812:     return $file;
 8813: }
 8814: 
 8815: sub current_machine_domains {
 8816:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 8817: }
 8818: 
 8819: sub machine_domains {
 8820:     my ($hostname) = @_;
 8821:     my @domains;
 8822:     my %hostname = &all_hostnames();
 8823:     while( my($id, $name) = each(%hostname)) {
 8824: #	&logthis("-$id-$name-$hostname-");
 8825: 	if ($hostname eq $name) {
 8826: 	    push(@domains,&host_domain($id));
 8827: 	}
 8828:     }
 8829:     return @domains;
 8830: }
 8831: 
 8832: sub current_machine_ids {
 8833:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 8834: }
 8835: 
 8836: sub machine_ids {
 8837:     my ($hostname) = @_;
 8838:     $hostname ||= &hostname($perlvar{'lonHostID'});
 8839:     my @ids;
 8840:     my %name_to_host = &all_names();
 8841:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 8842: 	return @{ $name_to_host{$hostname} };
 8843:     }
 8844:     return;
 8845: }
 8846: 
 8847: sub additional_machine_domains {
 8848:     my @domains;
 8849:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 8850:     while( my $line = <$fh>) {
 8851:         $line =~ s/\s//g;
 8852:         push(@domains,$line);
 8853:     }
 8854:     return @domains;
 8855: }
 8856: 
 8857: sub default_login_domain {
 8858:     my $domain = $perlvar{'lonDefDomain'};
 8859:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 8860:     foreach my $posdom (&current_machine_domains(),
 8861:                         &additional_machine_domains()) {
 8862:         if (lc($posdom) eq lc($testdomain)) {
 8863:             $domain=$posdom;
 8864:             last;
 8865:         }
 8866:     }
 8867:     return $domain;
 8868: }
 8869: 
 8870: # ------------------------------------------------------------- Declutters URLs
 8871: 
 8872: sub declutter {
 8873:     my $thisfn=shift;
 8874:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8875:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8876:     $thisfn=~s/^\///;
 8877:     $thisfn=~s|^adm/wrapper/||;
 8878:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 8879:     $thisfn=~s/^res\///;
 8880:     $thisfn=~s/\?.+$//;
 8881:     return $thisfn;
 8882: }
 8883: 
 8884: # ------------------------------------------------------------- Clutter up URLs
 8885: 
 8886: sub clutter {
 8887:     my $thisfn='/'.&declutter(shift);
 8888:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 8889: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 8890:        $thisfn='/res'.$thisfn; 
 8891:     }
 8892:     if ($thisfn !~m|/adm|) {
 8893: 	if ($thisfn =~ m|/ext/|) {
 8894: 	    $thisfn='/adm/wrapper'.$thisfn;
 8895: 	} else {
 8896: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 8897: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 8898: 	    if ($embstyle eq 'ssi'
 8899: 		|| ($embstyle eq 'hdn')
 8900: 		|| ($embstyle eq 'rat')
 8901: 		|| ($embstyle eq 'prv')
 8902: 		|| ($embstyle eq 'ign')) {
 8903: 		#do nothing with these
 8904: 	    } elsif (($embstyle eq 'img') 
 8905: 		|| ($embstyle eq 'emb')
 8906: 		|| ($embstyle eq 'wrp')) {
 8907: 		$thisfn='/adm/wrapper'.$thisfn;
 8908: 	    } elsif ($embstyle eq 'unk'
 8909: 		     && $thisfn!~/\.(sequence|page)$/) {
 8910: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 8911: 	    } else {
 8912: #		&logthis("Got a blank emb style");
 8913: 	    }
 8914: 	}
 8915:     }
 8916:     return $thisfn;
 8917: }
 8918: 
 8919: sub clutter_with_no_wrapper {
 8920:     my $uri = &clutter(shift);
 8921:     if ($uri =~ m-^/adm/-) {
 8922: 	$uri =~ s-^/adm/wrapper/-/-;
 8923: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 8924:     }
 8925:     return $uri;
 8926: }
 8927: 
 8928: sub freeze_escape {
 8929:     my ($value)=@_;
 8930:     if (ref($value)) {
 8931: 	$value=&nfreeze($value);
 8932: 	return '__FROZEN__'.&escape($value);
 8933:     }
 8934:     return &escape($value);
 8935: }
 8936: 
 8937: 
 8938: sub thaw_unescape {
 8939:     my ($value)=@_;
 8940:     if ($value =~ /^__FROZEN__/) {
 8941: 	substr($value,0,10,undef);
 8942: 	$value=&unescape($value);
 8943: 	return &thaw($value);
 8944:     }
 8945:     return &unescape($value);
 8946: }
 8947: 
 8948: sub correct_line_ends {
 8949:     my ($result)=@_;
 8950:     $$result =~s/\r\n/\n/mg;
 8951:     $$result =~s/\r/\n/mg;
 8952: }
 8953: # ================================================================ Main Program
 8954: 
 8955: sub goodbye {
 8956:    &logthis("Starting Shut down");
 8957: #not converted to using infrastruture and probably shouldn't be
 8958:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 8959: #converted
 8960: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 8961:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 8962: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 8963: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 8964: #1.1 only
 8965: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 8966: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 8967: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 8968: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 8969:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 8970:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 8971:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 8972:    &flushcourselogs();
 8973:    &logthis("Shutting down");
 8974: }
 8975: 
 8976: sub get_dns {
 8977:     my ($url,$func,$ignore_cache) = @_;
 8978:     if (!$ignore_cache) {
 8979: 	my ($content,$cached)=
 8980: 	    &Apache::lonnet::is_cached_new('dns',$url);
 8981: 	if ($cached) {
 8982: 	    &$func($content);
 8983: 	    return;
 8984: 	}
 8985:     }
 8986: 
 8987:     my %alldns;
 8988:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8989:     foreach my $dns (<$config>) {
 8990: 	next if ($dns !~ /^\^(\S*)/x);
 8991:         my $line = $1;
 8992:         my ($host,$protocol) = split(/:/,$line);
 8993:         if ($protocol ne 'https') {
 8994:             $protocol = 'http';
 8995:         }
 8996: 	$alldns{$host} = $protocol;
 8997:     }
 8998:     while (%alldns) {
 8999: 	my ($dns) = keys(%alldns);
 9000: 	my $ua=new LWP::UserAgent;
 9001: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
 9002: 	my $response=$ua->request($request);
 9003:         delete($alldns{$dns});
 9004: 	next if ($response->is_error());
 9005: 	my @content = split("\n",$response->content);
 9006: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 9007: 	&$func(\@content);
 9008: 	return;
 9009:     }
 9010:     close($config);
 9011:     my $which = (split('/',$url))[3];
 9012:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 9013:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 9014:     my @content = <$config>;
 9015:     &$func(\@content);
 9016:     return;
 9017: }
 9018: # ------------------------------------------------------------ Read domain file
 9019: {
 9020:     my $loaded;
 9021:     my %domain;
 9022: 
 9023:     sub parse_domain_tab {
 9024: 	my ($lines) = @_;
 9025: 	foreach my $line (@$lines) {
 9026: 	    next if ($line =~ /^(\#|\s*$ )/x);
 9027: 
 9028: 	    chomp($line);
 9029: 	    my ($name,@elements) = split(/:/,$line,9);
 9030: 	    my %this_domain;
 9031: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 9032: 			       'lang_def', 'city', 'longi', 'lati',
 9033: 			       'primary') {
 9034: 		$this_domain{$field} = shift(@elements);
 9035: 	    }
 9036: 	    $domain{$name} = \%this_domain;
 9037: 	}
 9038:     }
 9039: 
 9040:     sub reset_domain_info {
 9041: 	undef($loaded);
 9042: 	undef(%domain);
 9043:     }
 9044: 
 9045:     sub load_domain_tab {
 9046: 	my ($ignore_cache) = @_;
 9047: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 9048: 	my $fh;
 9049: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 9050: 	    my @lines = <$fh>;
 9051: 	    &parse_domain_tab(\@lines);
 9052: 	}
 9053: 	close($fh);
 9054: 	$loaded = 1;
 9055:     }
 9056: 
 9057:     sub domain {
 9058: 	&load_domain_tab() if (!$loaded);
 9059: 
 9060: 	my ($name,$what) = @_;
 9061: 	return if ( !exists($domain{$name}) );
 9062: 
 9063: 	if (!$what) {
 9064: 	    return $domain{$name}{'description'};
 9065: 	}
 9066: 	return $domain{$name}{$what};
 9067:     }
 9068: 
 9069:     sub domain_info {
 9070:         &load_domain_tab() if (!$loaded);
 9071:         return %domain;
 9072:     }
 9073: 
 9074: }
 9075: 
 9076: 
 9077: # ------------------------------------------------------------- Read hosts file
 9078: {
 9079:     my %hostname;
 9080:     my %hostdom;
 9081:     my %libserv;
 9082:     my $loaded;
 9083:     my %name_to_host;
 9084: 
 9085:     sub parse_hosts_tab {
 9086: 	my ($file) = @_;
 9087: 	foreach my $configline (@$file) {
 9088: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 9089: 	    next if ($configline =~ /^\^/);
 9090: 	    chomp($configline);
 9091: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
 9092: 	    $name=~s/\s//g;
 9093: 	    if ($id && $domain && $role && $name) {
 9094: 		$hostname{$id}=$name;
 9095: 		push(@{$name_to_host{$name}}, $id);
 9096: 		$hostdom{$id}=$domain;
 9097: 		if ($role eq 'library') { $libserv{$id}=$name; }
 9098:                 if (defined($protocol)) {
 9099:                     if ($protocol eq 'https') {
 9100:                         $protocol{$id} = $protocol;
 9101:                     } else {
 9102:                         $protocol{$id} = 'http'; 
 9103:                     }
 9104:                 } else {
 9105:                     $protocol{$id} = 'http';
 9106:                 }
 9107: 	    }
 9108: 	}
 9109:     }
 9110:     
 9111:     sub reset_hosts_info {
 9112: 	&purge_remembered();
 9113: 	&reset_domain_info();
 9114: 	&reset_hosts_ip_info();
 9115: 	undef(%name_to_host);
 9116: 	undef(%hostname);
 9117: 	undef(%hostdom);
 9118: 	undef(%libserv);
 9119: 	undef($loaded);
 9120:     }
 9121: 
 9122:     sub load_hosts_tab {
 9123: 	my ($ignore_cache) = @_;
 9124: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 9125: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 9126: 	my @config = <$config>;
 9127: 	&parse_hosts_tab(\@config);
 9128: 	close($config);
 9129: 	$loaded=1;
 9130:     }
 9131: 
 9132:     sub hostname {
 9133: 	&load_hosts_tab() if (!$loaded);
 9134: 
 9135: 	my ($lonid) = @_;
 9136: 	return $hostname{$lonid};
 9137:     }
 9138: 
 9139:     sub all_hostnames {
 9140: 	&load_hosts_tab() if (!$loaded);
 9141: 
 9142: 	return %hostname;
 9143:     }
 9144: 
 9145:     sub all_names {
 9146: 	&load_hosts_tab() if (!$loaded);
 9147: 
 9148: 	return %name_to_host;
 9149:     }
 9150: 
 9151:     sub all_host_domain {
 9152:         &load_hosts_tab() if (!$loaded);
 9153:         return %hostdom;
 9154:     }
 9155: 
 9156:     sub is_library {
 9157: 	&load_hosts_tab() if (!$loaded);
 9158: 
 9159: 	return exists($libserv{$_[0]});
 9160:     }
 9161: 
 9162:     sub all_library {
 9163: 	&load_hosts_tab() if (!$loaded);
 9164: 
 9165: 	return %libserv;
 9166:     }
 9167: 
 9168:     sub get_servers {
 9169: 	&load_hosts_tab() if (!$loaded);
 9170: 
 9171: 	my ($domain,$type) = @_;
 9172: 	my %possible_hosts = ($type eq 'library') ? %libserv
 9173: 	                                          : %hostname;
 9174: 	my %result;
 9175: 	if (ref($domain) eq 'ARRAY') {
 9176: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9177: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 9178: 		    $result{$host} = $hostname;
 9179: 		}
 9180: 	    }
 9181: 	} else {
 9182: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9183: 		if ($hostdom{$host} eq $domain) {
 9184: 		    $result{$host} = $hostname;
 9185: 		}
 9186: 	    }
 9187: 	}
 9188: 	return %result;
 9189:     }
 9190: 
 9191:     sub host_domain {
 9192: 	&load_hosts_tab() if (!$loaded);
 9193: 
 9194: 	my ($lonid) = @_;
 9195: 	return $hostdom{$lonid};
 9196:     }
 9197: 
 9198:     sub all_domains {
 9199: 	&load_hosts_tab() if (!$loaded);
 9200: 
 9201: 	my %seen;
 9202: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 9203: 	return @uniq;
 9204:     }
 9205: }
 9206: 
 9207: { 
 9208:     my %iphost;
 9209:     my %name_to_ip;
 9210:     my %lonid_to_ip;
 9211: 
 9212:     sub get_hosts_from_ip {
 9213: 	my ($ip) = @_;
 9214: 	my %iphosts = &get_iphost();
 9215: 	if (ref($iphosts{$ip})) {
 9216: 	    return @{$iphosts{$ip}};
 9217: 	}
 9218: 	return;
 9219:     }
 9220:     
 9221:     sub reset_hosts_ip_info {
 9222: 	undef(%iphost);
 9223: 	undef(%name_to_ip);
 9224: 	undef(%lonid_to_ip);
 9225:     }
 9226: 
 9227:     sub get_host_ip {
 9228: 	my ($lonid) = @_;
 9229: 	if (exists($lonid_to_ip{$lonid})) {
 9230: 	    return $lonid_to_ip{$lonid};
 9231: 	}
 9232: 	my $name=&hostname($lonid);
 9233:    	my $ip = gethostbyname($name);
 9234: 	return if (!$ip || length($ip) ne 4);
 9235: 	$ip=inet_ntoa($ip);
 9236: 	$name_to_ip{$name}   = $ip;
 9237: 	$lonid_to_ip{$lonid} = $ip;
 9238: 	return $ip;
 9239:     }
 9240:     
 9241:     sub get_iphost {
 9242: 	my ($ignore_cache) = @_;
 9243: 
 9244: 	if (!$ignore_cache) {
 9245: 	    if (%iphost) {
 9246: 		return %iphost;
 9247: 	    }
 9248: 	    my ($ip_info,$cached)=
 9249: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 9250: 	    if ($cached) {
 9251: 		%iphost      = %{$ip_info->[0]};
 9252: 		%name_to_ip  = %{$ip_info->[1]};
 9253: 		%lonid_to_ip = %{$ip_info->[2]};
 9254: 		return %iphost;
 9255: 	    }
 9256: 	}
 9257: 
 9258: 	# get yesterday's info for fallback
 9259: 	my %old_name_to_ip;
 9260: 	my ($ip_info,$cached)=
 9261: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 9262: 	if ($cached) {
 9263: 	    %old_name_to_ip = %{$ip_info->[1]};
 9264: 	}
 9265: 
 9266: 	my %name_to_host = &all_names();
 9267: 	foreach my $name (keys(%name_to_host)) {
 9268: 	    my $ip;
 9269: 	    if (!exists($name_to_ip{$name})) {
 9270: 		$ip = gethostbyname($name);
 9271: 		if (!$ip || length($ip) ne 4) {
 9272: 		    if (defined($old_name_to_ip{$name})) {
 9273: 			$ip = $old_name_to_ip{$name};
 9274: 			&logthis("Can't find $name defaulting to old $ip");
 9275: 		    } else {
 9276: 			&logthis("Name $name no IP found");
 9277: 			next;
 9278: 		    }
 9279: 		} else {
 9280: 		    $ip=inet_ntoa($ip);
 9281: 		}
 9282: 		$name_to_ip{$name} = $ip;
 9283: 	    } else {
 9284: 		$ip = $name_to_ip{$name};
 9285: 	    }
 9286: 	    foreach my $id (@{ $name_to_host{$name} }) {
 9287: 		$lonid_to_ip{$id} = $ip;
 9288: 	    }
 9289: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 9290: 	}
 9291: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 9292: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 9293: 				      48*60*60);
 9294: 
 9295: 	return %iphost;
 9296:     }
 9297: 
 9298:     #
 9299:     #  Given a DNS returns the loncapa host name for that DNS 
 9300:     # 
 9301:     sub host_from_dns {
 9302:         my ($dns) = @_;
 9303:         my @hosts;
 9304:         my $ip;
 9305: 
 9306:         if (exists($name_to_ip{$dns})) {
 9307:             $ip = $name_to_ip{$dns};
 9308:         }
 9309:         if (!$ip) {
 9310:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
 9311:             if (length($ip) == 4) { 
 9312: 	        $ip   = &IO::Socket::inet_ntoa($ip);
 9313:             }
 9314:         }
 9315:         if ($ip) {
 9316: 	    @hosts = get_hosts_from_ip($ip);
 9317: 	    return $hosts[0];
 9318:         }
 9319:         return undef;
 9320:     }
 9321: 
 9322: }
 9323: 
 9324: BEGIN {
 9325: 
 9326: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 9327:     unless ($readit) {
 9328: {
 9329:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 9330:     %perlvar = (%perlvar,%{$configvars});
 9331: }
 9332: 
 9333: 
 9334: # ------------------------------------------------------ Read spare server file
 9335: {
 9336:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 9337: 
 9338:     while (my $configline=<$config>) {
 9339:        chomp($configline);
 9340:        if ($configline) {
 9341: 	   my ($host,$type) = split(':',$configline,2);
 9342: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 9343: 	   push(@{ $spareid{$type} }, $host);
 9344:        }
 9345:     }
 9346:     close($config);
 9347: }
 9348: # ------------------------------------------------------------ Read permissions
 9349: {
 9350:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 9351: 
 9352:     while (my $configline=<$config>) {
 9353: 	chomp($configline);
 9354: 	if ($configline) {
 9355: 	    my ($role,$perm)=split(/ /,$configline);
 9356: 	    if ($perm ne '') { $pr{$role}=$perm; }
 9357: 	}
 9358:     }
 9359:     close($config);
 9360: }
 9361: 
 9362: # -------------------------------------------- Read plain texts for permissions
 9363: {
 9364:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 9365: 
 9366:     while (my $configline=<$config>) {
 9367: 	chomp($configline);
 9368: 	if ($configline) {
 9369: 	    my ($short,@plain)=split(/:/,$configline);
 9370:             %{$prp{$short}} = ();
 9371: 	    if (@plain > 0) {
 9372:                 $prp{$short}{'std'} = $plain[0];
 9373:                 for (my $i=1; $i<@plain; $i++) {
 9374:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 9375:                 }
 9376:             }
 9377: 	}
 9378:     }
 9379:     close($config);
 9380: }
 9381: 
 9382: # ---------------------------------------------------------- Read package table
 9383: {
 9384:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 9385: 
 9386:     while (my $configline=<$config>) {
 9387: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 9388: 	chomp($configline);
 9389: 	my ($short,$plain)=split(/:/,$configline);
 9390: 	my ($pack,$name)=split(/\&/,$short);
 9391: 	if ($plain ne '') {
 9392: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 9393: 	    $packagetab{$short}=$plain; 
 9394: 	}
 9395:     }
 9396:     close($config);
 9397: }
 9398: 
 9399: # ------------- set up temporary directory
 9400: {
 9401:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 9402: 
 9403: }
 9404: 
 9405: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 9406: 				'compress_threshold'=> 20_000,
 9407:  			        });
 9408: 
 9409: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 9410: $dumpcount=0;
 9411: $locknum=0;
 9412: 
 9413: &logtouch();
 9414: &logthis('<font color="yellow">INFO: Read configuration</font>');
 9415: $readit=1;
 9416:     {
 9417: 	use integer;
 9418: 	my $test=(2**32)+1;
 9419: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 9420: 	&logthis(" Detected 64bit platform ($_64bit)");
 9421:     }
 9422: }
 9423: }
 9424: 
 9425: 1;
 9426: __END__
 9427: 
 9428: =pod
 9429: 
 9430: =head1 NAME
 9431: 
 9432: Apache::lonnet - Subroutines to ask questions about things in the network.
 9433: 
 9434: =head1 SYNOPSIS
 9435: 
 9436: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 9437: 
 9438:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 9439: 
 9440: Common parameters:
 9441: 
 9442: =over 4
 9443: 
 9444: =item *
 9445: 
 9446: $uname : an internal username (if $cname expecting a course Id specifically)
 9447: 
 9448: =item *
 9449: 
 9450: $udom : a domain (if $cdom expecting a course's domain specifically)
 9451: 
 9452: =item *
 9453: 
 9454: $symb : a resource instance identifier
 9455: 
 9456: =item *
 9457: 
 9458: $namespace : the name of a .db file that contains the data needed or
 9459: being set.
 9460: 
 9461: =back
 9462: 
 9463: =head1 OVERVIEW
 9464: 
 9465: lonnet provides subroutines which interact with the
 9466: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 9467: about classes, users, and resources.
 9468: 
 9469: For many of these objects you can also use this to store data about
 9470: them or modify them in various ways.
 9471: 
 9472: =head2 Symbs
 9473: 
 9474: To identify a specific instance of a resource, LON-CAPA uses symbols
 9475: or "symbs"X<symb>. These identifiers are built from the URL of the
 9476: map, the resource number of the resource in the map, and the URL of
 9477: the resource itself. The latter is somewhat redundant, but might help
 9478: if maps change.
 9479: 
 9480: An example is
 9481: 
 9482:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 9483: 
 9484: The respective map entry is
 9485: 
 9486:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 9487:   title="Problem 2">
 9488:  </resource>
 9489: 
 9490: Symbs are used by the random number generator, as well as to store and
 9491: restore data specific to a certain instance of for example a problem.
 9492: 
 9493: =head2 Storing And Retrieving Data
 9494: 
 9495: X<store()>X<cstore()>X<restore()>Three of the most important functions
 9496: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 9497: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 9498: is is the non-critical message twin of cstore. These functions are for
 9499: handlers to store a perl hash to a user's permanent data space in an
 9500: easy manner, and to retrieve it again on another call. It is expected
 9501: that a handler would use this once at the beginning to retrieve data,
 9502: and then again once at the end to send only the new data back.
 9503: 
 9504: The data is stored in the user's data directory on the user's
 9505: homeserver under the ID of the course.
 9506: 
 9507: The hash that is returned by restore will have all of the previous
 9508: value for all of the elements of the hash.
 9509: 
 9510: Example:
 9511: 
 9512:  #creating a hash
 9513:  my %hash;
 9514:  $hash{'foo'}='bar';
 9515: 
 9516:  #storing it
 9517:  &Apache::lonnet::cstore(\%hash);
 9518: 
 9519:  #changing a value
 9520:  $hash{'foo'}='notbar';
 9521: 
 9522:  #adding a new value
 9523:  $hash{'bar'}='foo';
 9524:  &Apache::lonnet::cstore(\%hash);
 9525: 
 9526:  #retrieving the hash
 9527:  my %history=&Apache::lonnet::restore();
 9528: 
 9529:  #print the hash
 9530:  foreach my $key (sort(keys(%history))) {
 9531:    print("\%history{$key} = $history{$key}");
 9532:  }
 9533: 
 9534: Will print out:
 9535: 
 9536:  %history{1:foo} = bar
 9537:  %history{1:keys} = foo:timestamp
 9538:  %history{1:timestamp} = 990455579
 9539:  %history{2:bar} = foo
 9540:  %history{2:foo} = notbar
 9541:  %history{2:keys} = foo:bar:timestamp
 9542:  %history{2:timestamp} = 990455580
 9543:  %history{bar} = foo
 9544:  %history{foo} = notbar
 9545:  %history{timestamp} = 990455580
 9546:  %history{version} = 2
 9547: 
 9548: Note that the special hash entries C<keys>, C<version> and
 9549: C<timestamp> were added to the hash. C<version> will be equal to the
 9550: total number of versions of the data that have been stored. The
 9551: C<timestamp> attribute will be the UNIX time the hash was
 9552: stored. C<keys> is available in every historical section to list which
 9553: keys were added or changed at a specific historical revision of a
 9554: hash.
 9555: 
 9556: B<Warning>: do not store the hash that restore returns directly. This
 9557: will cause a mess since it will restore the historical keys as if the
 9558: were new keys. I.E. 1:foo will become 1:1:foo etc.
 9559: 
 9560: Calling convention:
 9561: 
 9562:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 9563:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 9564: 
 9565: For more detailed information, see lonnet specific documentation.
 9566: 
 9567: =head1 RETURN MESSAGES
 9568: 
 9569: =over 4
 9570: 
 9571: =item * B<con_lost>: unable to contact remote host
 9572: 
 9573: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 9574: when the connection is brought back up
 9575: 
 9576: =item * B<con_failed>: unable to contact remote host and unable to save message
 9577: for later delivery
 9578: 
 9579: =item * B<error:>: an error a occurred, a description of the error follows the :
 9580: 
 9581: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 9582: that was requested
 9583: 
 9584: =back
 9585: 
 9586: =head1 PUBLIC SUBROUTINES
 9587: 
 9588: =head2 Session Environment Functions
 9589: 
 9590: =over 4
 9591: 
 9592: =item * 
 9593: X<appenv()>
 9594: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
 9595: the user envirnoment file, and will be restored for each access this
 9596: user makes during this session, also modifies the %env for the current
 9597: process. Optional rolesarrayref - if defined contains a reference to an array
 9598: of roles which are exempt from the restriction on modifying user.role entries 
 9599: in the user's environment.db and in %env.    
 9600: 
 9601: =item *
 9602: X<delenv()>
 9603: B<delenv($delthis,$regexp)>: removes all items from the session
 9604: environment file that begin with $delthis. If the 
 9605: optional second arg - $regexp - is true, $delthis is treated as a 
 9606: regular expression, otherwise \Q$delthis\E is used. 
 9607: The values are also deleted from the current processes %env.
 9608: 
 9609: =item * get_env_multiple($name) 
 9610: 
 9611: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9612: values may be defined and end up as an array ref.
 9613: 
 9614: returns an array of values
 9615: 
 9616: =back
 9617: 
 9618: =head2 User Information
 9619: 
 9620: =over 4
 9621: 
 9622: =item *
 9623: X<queryauthenticate()>
 9624: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 9625: authentication scheme
 9626: 
 9627: =item *
 9628: X<authenticate()>
 9629: B<authenticate($uname,$upass,$udom)>: try to
 9630: authenticate user from domain's lib servers (first use the current
 9631: one). C<$upass> should be the users password.
 9632: 
 9633: =item *
 9634: X<homeserver()>
 9635: B<homeserver($uname,$udom)>: find the server which has
 9636: the user's directory and files (there must be only one), this caches
 9637: the answer, and also caches if there is a borken connection.
 9638: 
 9639: =item *
 9640: X<idget()>
 9641: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 9642: (IDs are a unique resource in a domain, there must be only 1 ID per
 9643: username, and only 1 username per ID in a specific domain) (returns
 9644: hash: id=>name,id=>name)
 9645: 
 9646: =item *
 9647: X<idrget()>
 9648: B<idrget($udom,@unames)>: find the IDs behind a list of
 9649: usernames (returns hash: name=>id,name=>id)
 9650: 
 9651: =item *
 9652: X<idput()>
 9653: B<idput($udom,%ids)>: store away a list of names and associated IDs
 9654: 
 9655: =item *
 9656: X<rolesinit()>
 9657: B<rolesinit($udom,$username,$authhost)>: get user privileges
 9658: 
 9659: =item *
 9660: X<getsection()>
 9661: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 9662: course $cname, return section name/number or '' for "not in course"
 9663: and '-1' for "no section"
 9664: 
 9665: =item *
 9666: X<userenvironment()>
 9667: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 9668: passed in @what from the requested user's environment, returns a hash
 9669: 
 9670: =item * 
 9671: X<userlog_query()>
 9672: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 9673: activity.log file. %filters defines filters applied when parsing the
 9674: log file. These can be start or end timestamps, or the type of action
 9675: - log to look for Login or Logout events, check for Checkin or
 9676: Checkout, role for role selection. The response is in the form
 9677: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 9678: escaped strings of the action recorded in the activity.log file.
 9679: 
 9680: =back
 9681: 
 9682: =head2 User Roles
 9683: 
 9684: =over 4
 9685: 
 9686: =item *
 9687: 
 9688: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 9689:  F: full access
 9690:  U,I,K: authentication modes (cxx only)
 9691:  '': forbidden
 9692:  1: user needs to choose course
 9693:  2: browse allowed
 9694:  A: passphrase authentication needed
 9695: 
 9696: =item *
 9697: 
 9698: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 9699: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 9700: and course level
 9701: 
 9702: =item *
 9703: 
 9704: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
 9705: (rolesplain.tab); plain text explanation of a user role term.
 9706: $type is Course (default) or Community.
 9707: If $forcedefault evaluates to true, text returned will be default 
 9708: text for $type. Otherwise, if this is a course, the text returned 
 9709: will be a custom name for the role (if defined in the course's 
 9710: environment).  If no custom name is defined the default is returned.
 9711:    
 9712: =item *
 9713: 
 9714: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
 9715: All arguments are optional. Returns a hash of a roles, either for
 9716: co-author/assistant author roles for a user's Construction Space
 9717: (default), or if $context is 'userroles', roles for the user himself,
 9718: In the hash, keys are set to colon-separated $uname,$udom,$role, and
 9719: (optionally) if $withsec is true, a fourth colon-separated item - $section.
 9720: For each key, value is set to colon-separated start and end times for
 9721: the role.  If no username and domain are specified, will default to
 9722: current user/domain. Types, roles, and roledoms are references to arrays
 9723: of role statuses (active, future or previous), roles 
 9724: (e.g., cc,in, st etc.) and domains of the roles which can be used
 9725: to restrict the list of roles reported. If no array ref is 
 9726: provided for types, will default to return only active roles.
 9727: 
 9728: =back
 9729: 
 9730: =head2 User Modification
 9731: 
 9732: =over 4
 9733: 
 9734: =item *
 9735: 
 9736: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
 9737: user for the level given by URL.  Optional start and end dates (leave empty
 9738: string or zero for "no date")
 9739: 
 9740: =item *
 9741: 
 9742: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 9743: change a users, password, possible return values are: ok,
 9744: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 9745: refused
 9746: 
 9747: =item *
 9748: 
 9749: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 9750: 
 9751: =item *
 9752: 
 9753: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
 9754:            $forceid,$desiredhome,$email,$inststatus) : 
 9755: modify user
 9756: 
 9757: =item *
 9758: 
 9759: modifystudent
 9760: 
 9761: modify a student's enrollment and identification information.
 9762: The course id is resolved based on the current users environment.  
 9763: This means the envoking user must be a course coordinator or otherwise
 9764: associated with a course.
 9765: 
 9766: This call is essentially a wrapper for lonnet::modifyuser and
 9767: lonnet::modify_student_enrollment
 9768: 
 9769: Inputs: 
 9770: 
 9771: =over 4
 9772: 
 9773: =item B<$udom> Student's loncapa domain
 9774: 
 9775: =item B<$uname> Student's loncapa login name
 9776: 
 9777: =item B<$uid> Student/Employee ID
 9778: 
 9779: =item B<$umode> Student's authentication mode
 9780: 
 9781: =item B<$upass> Student's password
 9782: 
 9783: =item B<$first> Student's first name
 9784: 
 9785: =item B<$middle> Student's middle name
 9786: 
 9787: =item B<$last> Student's last name
 9788: 
 9789: =item B<$gene> Student's generation
 9790: 
 9791: =item B<$usec> Student's section in course
 9792: 
 9793: =item B<$end> Unix time of the roles expiration
 9794: 
 9795: =item B<$start> Unix time of the roles start date
 9796: 
 9797: =item B<$forceid> If defined, allow $uid to be changed
 9798: 
 9799: =item B<$desiredhome> server to use as home server for student
 9800: 
 9801: =item B<$email> Student's permanent e-mail address
 9802: 
 9803: =item B<$type> Type of enrollment (auto or manual)
 9804: 
 9805: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
 9806: 
 9807: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
 9808: 
 9809: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
 9810: 
 9811: =item B<$context> role change context (shown in User Management Logs display in a course)
 9812: 
 9813: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
 9814: 
 9815: =back
 9816: 
 9817: =item *
 9818: 
 9819: modify_student_enrollment
 9820: 
 9821: Change a students enrollment status in a class.  The environment variable
 9822: 'role.request.course' must be defined for this function to proceed.
 9823: 
 9824: Inputs:
 9825: 
 9826: =over 4
 9827: 
 9828: =item $udom, students domain
 9829: 
 9830: =item $uname, students name
 9831: 
 9832: =item $uid, students user id
 9833: 
 9834: =item $first, students first name
 9835: 
 9836: =item $middle
 9837: 
 9838: =item $last
 9839: 
 9840: =item $gene
 9841: 
 9842: =item $usec
 9843: 
 9844: =item $end
 9845: 
 9846: =item $start
 9847: 
 9848: =item $type
 9849: 
 9850: =item $locktype
 9851: 
 9852: =item $cid
 9853: 
 9854: =item $selfenroll
 9855: 
 9856: =item $context
 9857: 
 9858: =back
 9859: 
 9860: 
 9861: =item *
 9862: 
 9863: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 9864: custom role; give a custom role to a user for the level given by URL.  Specify
 9865: name and domain of role author, and role name
 9866: 
 9867: =item *
 9868: 
 9869: revokerole($udom,$uname,$url,$role) : revoke a role for url
 9870: 
 9871: =item *
 9872: 
 9873: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 9874: 
 9875: =back
 9876: 
 9877: =head2 Course Infomation
 9878: 
 9879: =over 4
 9880: 
 9881: =item *
 9882: 
 9883: coursedescription($courseid) : returns a hash of information about the
 9884: specified course id, including all environment settings for the
 9885: course, the description of the course will be in the hash under the
 9886: key 'description'
 9887: 
 9888: =item *
 9889: 
 9890: resdata($name,$domain,$type,@which) : request for current parameter
 9891: setting for a specific $type, where $type is either 'course' or 'user',
 9892: @what should be a list of parameters to ask about. This routine caches
 9893: answers for 5 minutes.
 9894: 
 9895: =item *
 9896: 
 9897: get_courseresdata($courseid, $domain) : dump the entire course resource
 9898: data base, returning a hash that is keyed by the resource name and has
 9899: values that are the resource value.  I believe that the timestamps and
 9900: versions are also returned.
 9901: 
 9902: 
 9903: =back
 9904: 
 9905: =head2 Course Modification
 9906: 
 9907: =over 4
 9908: 
 9909: =item *
 9910: 
 9911: writecoursepref($courseid,%prefs) : write preferences (environment
 9912: database) for a course
 9913: 
 9914: =item *
 9915: 
 9916: createcourse($udom,$description,$url) : make/modify course
 9917: 
 9918: =back
 9919: 
 9920: =head2 Resource Subroutines
 9921: 
 9922: =over 4
 9923: 
 9924: =item *
 9925: 
 9926: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 9927: 
 9928: =item *
 9929: 
 9930: repcopy($filename) : subscribes to the requested file, and attempts to
 9931: replicate from the owning library server, Might return
 9932: 'unavailable', 'not_found', 'forbidden', 'ok', or
 9933: 'bad_request', also attempts to grab the metadata for the
 9934: resource. Expects the local filesystem pathname
 9935: (/home/httpd/html/res/....)
 9936: 
 9937: =back
 9938: 
 9939: =head2 Resource Information
 9940: 
 9941: =over 4
 9942: 
 9943: =item *
 9944: 
 9945: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 9946: a vairety of different possible values, $varname should be a request
 9947: string, and the other parameters can be used to specify who and what
 9948: one is asking about.
 9949: 
 9950: Possible values for $varname are environment.lastname (or other item
 9951: from the envirnment hash), user.name (or someother aspect about the
 9952: user), resource.0.maxtries (or some other part and parameter of a
 9953: resource)
 9954: 
 9955: =item *
 9956: 
 9957: directcondval($number) : get current value of a condition; reads from a state
 9958: string
 9959: 
 9960: =item *
 9961: 
 9962: condval($condidx) : value of condition index based on state
 9963: 
 9964: =item *
 9965: 
 9966: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 9967: resource's metadata, $what should be either a specific key, or either
 9968: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 9969: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 9970: 
 9971: this function automatically caches all requests
 9972: 
 9973: =item *
 9974: 
 9975: metadata_query($query,$custom,$customshow) : make a metadata query against the
 9976: network of library servers; returns file handle of where SQL and regex results
 9977: will be stored for query
 9978: 
 9979: =item *
 9980: 
 9981: symbread($filename) : return symbolic list entry (filename argument optional);
 9982: returns the data handle
 9983: 
 9984: =item *
 9985: 
 9986: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 9987: a possible symb for the URL in $thisfn, and if is an encryypted
 9988: resource that the user accessed using /enc/ returns a 1 on success, 0
 9989: on failure, user must be in a course, as it assumes the existance of
 9990: the course initial hash, and uses $env('request.course.id'}
 9991: 
 9992: 
 9993: =item *
 9994: 
 9995: symbclean($symb) : removes versions numbers from a symb, returns the
 9996: cleaned symb
 9997: 
 9998: =item *
 9999: 
10000: is_on_map($uri) : checks if the $uri is somewhere on the current
10001: course map, user must be in a course for it to work.
10002: 
10003: =item *
10004: 
10005: numval($salt) : return random seed value (addend for rndseed)
10006: 
10007: =item *
10008: 
10009: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10010: a random seed, all arguments are optional, if they aren't sent it uses the
10011: environment to derive them. Note: if symb isn't sent and it can't get one
10012: from &symbread it will use the current time as its return value
10013: 
10014: =item *
10015: 
10016: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10017: unfakeable, receipt
10018: 
10019: =item *
10020: 
10021: receipt() : API to ireceipt working off of env values; given out to users
10022: 
10023: =item *
10024: 
10025: countacc($url) : count the number of accesses to a given URL
10026: 
10027: =item *
10028: 
10029: 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
10030: 
10031: =item *
10032: 
10033: 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)
10034: 
10035: =item *
10036: 
10037: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
10038: 
10039: =item *
10040: 
10041: devalidate($symb) : devalidate temporary spreadsheet calculations,
10042: forcing spreadsheet to reevaluate the resource scores next time.
10043: 
10044: =back
10045: 
10046: =head2 Storing/Retreiving Data
10047: 
10048: =over 4
10049: 
10050: =item *
10051: 
10052: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
10053: for this url; hashref needs to be given and should be a \%hashname; the
10054: remaining args aren't required and if they aren't passed or are '' they will
10055: be derived from the env
10056: 
10057: =item *
10058: 
10059: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
10060: uses critical subroutine
10061: 
10062: =item *
10063: 
10064: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
10065: all args are optional
10066: 
10067: =item *
10068: 
10069: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
10070: dumps the complete (or key matching regexp) namespace into a hash
10071: ($udom, $uname, $regexp, $range are optional) for a namespace that is
10072: normally &store()ed into
10073: 
10074: $range should be either an integer '100' (give me the first 100
10075:                                            matching records)
10076:               or be  two integers sperated by a - with no spaces
10077:                  '30-50' (give me the 30th through the 50th matching
10078:                           records)
10079: 
10080: 
10081: =item *
10082: 
10083: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
10084: replaces a &store() version of data with a replacement set of data
10085: for a particular resource in a namespace passed in the $storehash hash 
10086: reference
10087: 
10088: =item *
10089: 
10090: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
10091: works very similar to store/cstore, but all data is stored in a
10092: temporary location and can be reset using tmpreset, $storehash should
10093: be a hash reference, returns nothing on success
10094: 
10095: =item *
10096: 
10097: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
10098: similar to restore, but all data is stored in a temporary location and
10099: can be reset using tmpreset. Returns a hash of values on success,
10100: error string otherwise.
10101: 
10102: =item *
10103: 
10104: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
10105: deltes all keys for $symb form the temporary storage hash.
10106: 
10107: =item *
10108: 
10109: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10110: reference filled in from namesp ($udom and $uname are optional)
10111: 
10112: =item *
10113: 
10114: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
10115: namesp ($udom and $uname are optional)
10116: 
10117: =item *
10118: 
10119: dump($namespace,$udom,$uname,$regexp,$range) : 
10120: dumps the complete (or key matching regexp) namespace into a hash
10121: ($udom, $uname, $regexp, $range are optional)
10122: 
10123: $range should be either an integer '100' (give me the first 100
10124:                                            matching records)
10125:               or be  two integers sperated by a - with no spaces
10126:                  '30-50' (give me the 30th through the 50th matching
10127:                           records)
10128: =item *
10129: 
10130: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
10131: $store can be a scalar, an array reference, or if the amount to be 
10132: incremented is > 1, a hash reference.
10133: 
10134: ($udom and $uname are optional)
10135: 
10136: =item *
10137: 
10138: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
10139: ($udom and $uname are optional)
10140: 
10141: =item *
10142: 
10143: cput($namespace,$storehash,$udom,$uname) : critical put
10144: ($udom and $uname are optional)
10145: 
10146: =item *
10147: 
10148: newput($namespace,$storehash,$udom,$uname) :
10149: 
10150: Attempts to store the items in the $storehash, but only if they don't
10151: currently exist, if this succeeds you can be certain that you have 
10152: successfully created a new key value pair in the $namespace db.
10153: 
10154: 
10155: Args:
10156:  $namespace: name of database to store values to
10157:  $storehash: hashref to store to the db
10158:  $udom: (optional) domain of user containing the db
10159:  $uname: (optional) name of user caontaining the db
10160: 
10161: Returns:
10162:  'ok' -> succeeded in storing all keys of $storehash
10163:  'key_exists: <key>' -> failed to anything out of $storehash, as at
10164:                         least <key> already existed in the db (other
10165:                         requested keys may also already exist)
10166:  'error: <msg>' -> unable to tie the DB or other error occurred
10167:  'con_lost' -> unable to contact request server
10168:  'refused' -> action was not allowed by remote machine
10169: 
10170: 
10171: =item *
10172: 
10173: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10174: reference filled in from namesp (encrypts the return communication)
10175: ($udom and $uname are optional)
10176: 
10177: =item *
10178: 
10179: log($udom,$name,$home,$message) : write to permanent log for user; use
10180: critical subroutine
10181: 
10182: =item *
10183: 
10184: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
10185: array reference filled in from namespace found in domain level on either
10186: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
10187: 
10188: =item *
10189: 
10190: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
10191: domain level either on specified domain server ($uhome) or primary domain 
10192: server ($udom and $uhome are optional)
10193: 
10194: =item * 
10195: 
10196: get_domain_defaults($target_domain) : returns hash with defaults for
10197: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
10198: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
10199: or localauth), initial password or a kerberos realm, language (e.g., en-us).
10200: Values are retrieved from cache (if current), or from domain's configuration.db
10201: (if available), or lastly from values in lonTabs/dns_domain,tab, 
10202: or lonTabs/domain.tab. 
10203: 
10204: %domdefaults = &get_auth_defaults($target_domain);
10205: 
10206: =back
10207: 
10208: =head2 Network Status Functions
10209: 
10210: =over 4
10211: 
10212: =item *
10213: 
10214: dirlist($uri) : return directory list based on URI
10215: 
10216: =item *
10217: 
10218: spareserver() : find server with least workload from spare.tab
10219: 
10220: 
10221: =item *
10222: 
10223: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
10224: if there is no corresponding loncapa host.
10225: 
10226: =back
10227: 
10228: 
10229: =head2 Apache Request
10230: 
10231: =over 4
10232: 
10233: =item *
10234: 
10235: ssi($url,%hash) : server side include, does a complete request cycle on url to
10236: localhost, posts hash
10237: 
10238: =back
10239: 
10240: =head2 Data to String to Data
10241: 
10242: =over 4
10243: 
10244: =item *
10245: 
10246: hash2str(%hash) : convert a hash into a string complete with escaping and '='
10247: and '&' separators, supports elements that are arrayrefs and hashrefs
10248: 
10249: =item *
10250: 
10251: hashref2str($hashref) : convert a hashref into a string complete with
10252: escaping and '=' and '&' separators, supports elements that are
10253: arrayrefs and hashrefs
10254: 
10255: =item *
10256: 
10257: arrayref2str($arrayref) : convert an arrayref into a string complete
10258: with escaping and '&' separators, supports elements that are arrayrefs
10259: and hashrefs
10260: 
10261: =item *
10262: 
10263: str2hash($string) : convert string to hash using unescaping and
10264: splitting on '=' and '&', supports elements that are arrayrefs and
10265: hashrefs
10266: 
10267: =item *
10268: 
10269: str2array($string) : convert string to hash using unescaping and
10270: splitting on '&', supports elements that are arrayrefs and hashrefs
10271: 
10272: =back
10273: 
10274: =head2 Logging Routines
10275: 
10276: =over 4
10277: 
10278: These routines allow one to make log messages in the lonnet.log and
10279: lonnet.perm logfiles.
10280: 
10281: =item *
10282: 
10283: logtouch() : make sure the logfile, lonnet.log, exists
10284: 
10285: =item *
10286: 
10287: logthis() : append message to the normal lonnet.log file, it gets
10288: preiodically rolled over and deleted.
10289: 
10290: =item *
10291: 
10292: logperm() : append a permanent message to lonnet.perm.log, this log
10293: file never gets deleted by any automated portion of the system, only
10294: messages of critical importance should go in here.
10295: 
10296: =back
10297: 
10298: =head2 General File Helper Routines
10299: 
10300: =over 4
10301: 
10302: =item *
10303: 
10304: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10305: (a) files in /uploaded
10306:   (i) If a local copy of the file exists - 
10307:       compares modification date of local copy with last-modified date for 
10308:       definitive version stored on home server for course. If local copy is 
10309:       stale, requests a new version from the home server and stores it. 
10310:       If the original has been removed from the home server, then local copy 
10311:       is unlinked.
10312:   (ii) If local copy does not exist -
10313:       requests the file from the home server and stores it. 
10314:   
10315:   If $caller is 'uploadrep':  
10316:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10317:     for request for files originally uploaded via DOCS. 
10318:      - returns 'ok' if fresh local copy now available, -1 otherwise.
10319:   
10320:   Otherwise:
10321:      This indicates a call from the content generation phase of the request.
10322:      -  returns the entire contents of the file or -1.
10323:      
10324: (b) files in /res
10325:    - returns the entire contents of a file or -1; 
10326:    it properly subscribes to and replicates the file if neccessary.
10327: 
10328: 
10329: =item *
10330: 
10331: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10332:                   reference
10333: 
10334: returns either a stat() list of data about the file or an empty list
10335: if the file doesn't exist or couldn't find out about it (connection
10336: problems or user unknown)
10337: 
10338: =item *
10339: 
10340: filelocation($dir,$file) : returns file system location of a file
10341: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10342: directory that relative $file lookups are to looked in ($dir of /a/dir
10343: and a file of ../bob will become /a/bob)
10344: 
10345: =item *
10346: 
10347: hreflocation($dir,$file) : returns file system location or a URL; same as
10348: filelocation except for hrefs
10349: 
10350: =item *
10351: 
10352: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10353: 
10354: =back
10355: 
10356: =head2 Usererfile file routines (/uploaded*)
10357: 
10358: =over 4
10359: 
10360: =item *
10361: 
10362: userfileupload(): main rotine for putting a file in a user or course's
10363:                   filespace, arguments are,
10364: 
10365:  formname - required - this is the name of the element in $env where the
10366:            filename, and the contents of the file to create/modifed exist
10367:            the filename is in $env{'form.'.$formname.'.filename'} and the
10368:            contents of the file is located in $env{'form.'.$formname}
10369:  coursedoc - if true, store the file in the course of the active role
10370:              of the current user
10371:  subdir - required - subdirectory to put the file in under ../userfiles/
10372:          if undefined, it will be placed in "unknown"
10373: 
10374:  (This routine calls clean_filename() to remove any dangerous
10375:  characters from the filename, and then calls finuserfileupload() to
10376:  complete the transaction)
10377: 
10378:  returns either the url of the uploaded file (/uploaded/....) if successful
10379:  and /adm/notfound.html if unsuccessful
10380: 
10381: =item *
10382: 
10383: clean_filename(): routine for cleaing a filename up for storage in
10384:                  userfile space, argument is:
10385: 
10386:  filename - proposed filename
10387: 
10388: returns: the new clean filename
10389: 
10390: =item *
10391: 
10392: finishuserfileupload(): routine that creaes and sends the file to
10393: userspace, probably shouldn't be called directly
10394: 
10395:   docuname: username or courseid of destination for the file
10396:   docudom: domain of user/course of destination for the file
10397:   formname: same as for userfileupload()
10398:   fname: filename (inculding subdirectories) for the file
10399: 
10400:  returns either the url of the uploaded file (/uploaded/....) if successful
10401:  and /adm/notfound.html if unsuccessful
10402: 
10403: =item *
10404: 
10405: renameuserfile(): renames an existing userfile to a new name
10406: 
10407:   Args:
10408:    docuname: username or courseid of destination for the file
10409:    docudom: domain of user/course of destination for the file
10410:    old: current file name (including any subdirs under userfiles)
10411:    new: desired file name (including any subdirs under userfiles)
10412: 
10413: =item *
10414: 
10415: mkdiruserfile(): creates a directory is a userfiles dir
10416: 
10417:   Args:
10418:    docuname: username or courseid of destination for the file
10419:    docudom: domain of user/course of destination for the file
10420:    dir: dir to create (including any subdirs under userfiles)
10421: 
10422: =item *
10423: 
10424: removeuserfile(): removes a file that exists in userfiles
10425: 
10426:   Args:
10427:    docuname: username or courseid of destination for the file
10428:    docudom: domain of user/course of destination for the file
10429:    fname: filname to delete (including any subdirs under userfiles)
10430: 
10431: =item *
10432: 
10433: removeuploadedurl(): convience function for removeuserfile()
10434: 
10435:   Args:
10436:    url:  a full /uploaded/... url to delete
10437: 
10438: =item * 
10439: 
10440: get_portfile_permissions():
10441:   Args:
10442:     domain: domain of user or course contain the portfolio files
10443:     user: name of user or num of course contain the portfolio files
10444:   Returns:
10445:     hashref of a dump of the proper file_permissions.db
10446:    
10447: 
10448: =item * 
10449: 
10450: get_access_controls():
10451: 
10452: Args:
10453:   current_permissions: the hash ref returned from get_portfile_permissions()
10454:   group: (optional) the group you want the files associated with
10455:   file: (optional) the file you want access info on
10456: 
10457: Returns:
10458:     a hash (keys are file names) of hashes containing
10459:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10460:         values are XML containing access control settings (see below) 
10461: 
10462: Internal notes:
10463: 
10464:  access controls are stored in file_permissions.db as key=value pairs.
10465:     key -> path to file/file_name\0uniqueID:scope_end_start
10466:         where scope -> public,guest,course,group,domains or users.
10467:               end -> UNIX time for end of access (0 -> no end date)
10468:               start -> UNIX time for start of access
10469: 
10470:     value -> XML description of access control
10471:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10472:             <start></start>
10473:             <end></end>
10474: 
10475:             <password></password>  for scope type = guest
10476: 
10477:             <domain></domain>     for scope type = course or group
10478:             <number></number>
10479:             <roles id="">
10480:              <role></role>
10481:              <access></access>
10482:              <section></section>
10483:              <group></group>
10484:             </roles>
10485: 
10486:             <dom></dom>         for scope type = domains
10487: 
10488:             <users>             for scope type = users
10489:              <user>
10490:               <uname></uname>
10491:               <udom></udom>
10492:              </user>
10493:             </users>
10494:            </scope> 
10495:               
10496:  Access data is also aggregated for each file in an additional key=value pair:
10497:  key -> path to file/file_name\0accesscontrol 
10498:  value -> reference to hash
10499:           hash contains key = value pairs
10500:           where key = uniqueID:scope_end_start
10501:                 value = UNIX time record was last updated
10502: 
10503:           Used to improve speed of look-ups of access controls for each file.  
10504:  
10505:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10506: 
10507: modify_access_controls():
10508: 
10509: Modifies access controls for a portfolio file
10510: Args
10511: 1. file name
10512: 2. reference to hash of required changes,
10513: 3. domain
10514: 4. username
10515:   where domain,username are the domain of the portfolio owner 
10516:   (either a user or a course) 
10517: 
10518: Returns:
10519: 1. result of additions or updates ('ok' or 'error', with error message). 
10520: 2. result of deletions ('ok' or 'error', with error message).
10521: 3. reference to hash of any new or updated access controls.
10522: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10523:    key = integer (inbound ID)
10524:    value = uniqueID  
10525: 
10526: =back
10527: 
10528: =head2 HTTP Helper Routines
10529: 
10530: =over 4
10531: 
10532: =item *
10533: 
10534: escape() : unpack non-word characters into CGI-compatible hex codes
10535: 
10536: =item *
10537: 
10538: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10539: 
10540: =back
10541: 
10542: =head1 PRIVATE SUBROUTINES
10543: 
10544: =head2 Underlying communication routines (Shouldn't call)
10545: 
10546: =over 4
10547: 
10548: =item *
10549: 
10550: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10551: 
10552: =item *
10553: 
10554: reply() : uses subreply to send a message to remote machine, logs all failures
10555: 
10556: =item *
10557: 
10558: critical() : passes a critical message to another server; if cannot
10559: get through then place message in connection buffer directory and
10560: returns con_delayed, if incapable of saving message, returns
10561: con_failed
10562: 
10563: =item *
10564: 
10565: reconlonc() : tries to reconnect lonc client processes.
10566: 
10567: =back
10568: 
10569: =head2 Resource Access Logging
10570: 
10571: =over 4
10572: 
10573: =item *
10574: 
10575: flushcourselogs() : flush (save) buffer logs and access logs
10576: 
10577: =item *
10578: 
10579: courselog($what) : save message for course in hash
10580: 
10581: =item *
10582: 
10583: courseacclog($what) : save message for course using &courselog().  Perform
10584: special processing for specific resource types (problems, exams, quizzes, etc).
10585: 
10586: =item *
10587: 
10588: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10589: as a PerlChildExitHandler
10590: 
10591: =back
10592: 
10593: =head2 Other
10594: 
10595: =over 4
10596: 
10597: =item *
10598: 
10599: symblist($mapname,%newhash) : update symbolic storage links
10600: 
10601: =back
10602: 
10603: =cut
10604: 

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