File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1056: download - view: text, annotated - select for diffs
Wed Mar 17 20:22:06 2010 UTC (14 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_9_X, version_2_10_X, HEAD
- If auto assignment of co-owners is enabled for official courses
  - when CC role is assigned, check if:
    (a) new role will be active immediately
    (b) user with new role is official course personnel
- Store creation date, creator and creation context in nohist_courseids.db entry for new course, when creating a course.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1056 2010/03/17 20:22:06 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 File::MMagic;
   96: use LONCAPA qw(:DEFAULT :match);
   97: use LONCAPA::Configuration;
   98: 
   99: my $readit;
  100: my $max_connection_retries = 10;     # Or some such value.
  101: 
  102: require Exporter;
  103: 
  104: our @ISA = qw (Exporter);
  105: our @EXPORT = qw(%env);
  106: 
  107: 
  108: # --------------------------------------------------------------------- Logging
  109: {
  110:     my $logid;
  111:     sub instructor_log {
  112: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  113:         if (($cnum eq '') || ($cdom eq '')) {
  114:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  115:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  116:         }
  117: 	$logid++;
  118:         my $now = time();
  119: 	my $id=$now.'00000'.$$.'00000'.$logid;
  120: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  121: 				    { $id => {
  122: 					'exe_uname' => $env{'user.name'},
  123: 					'exe_udom'  => $env{'user.domain'},
  124: 					'exe_time'  => $now,
  125: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  126: 					'delflag'   => $delflag,
  127: 					'logentry'  => $storehash,
  128: 					'uname'     => $uname,
  129: 					'udom'      => $udom,
  130: 				    }
  131: 				  },$cdom,$cnum);
  132:     }
  133: }
  134: 
  135: sub logtouch {
  136:     my $execdir=$perlvar{'lonDaemons'};
  137:     unless (-e "$execdir/logs/lonnet.log") {	
  138: 	open(my $fh,">>$execdir/logs/lonnet.log");
  139: 	close $fh;
  140:     }
  141:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  142:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  143: }
  144: 
  145: sub logthis {
  146:     my $message=shift;
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     my $now=time;
  149:     my $local=localtime($now);
  150:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  151: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  152: 	print $fh $logstring;
  153: 	close($fh);
  154:     }
  155:     return 1;
  156: }
  157: 
  158: sub logperm {
  159:     my $message=shift;
  160:     my $execdir=$perlvar{'lonDaemons'};
  161:     my $now=time;
  162:     my $local=localtime($now);
  163:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  164: 	print $fh "$now:$message:$local\n";
  165: 	close($fh);
  166:     }
  167:     return 1;
  168: }
  169: 
  170: sub create_connection {
  171:     my ($hostname,$lonid) = @_;
  172:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  173: 				     Type    => SOCK_STREAM,
  174: 				     Timeout => 10);
  175:     return 0 if (!$client);
  176:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  177:     my $result = <$client>;
  178:     chomp($result);
  179:     return 1 if ($result eq 'done');
  180:     return 0;
  181: }
  182: 
  183: sub get_server_timezone {
  184:     my ($cnum,$cdom) = @_;
  185:     my $home=&homeserver($cnum,$cdom);
  186:     if ($home ne 'no_host') {
  187:         my $cachetime = 24*3600;
  188:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  189:         if (defined($cached)) {
  190:             return $timezone;
  191:         } else {
  192:             my $timezone = &reply('servertimezone',$home);
  193:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  194:         }
  195:     }
  196: }
  197: 
  198: sub get_server_loncaparev {
  199:     my ($dom,$lonhost) = @_;
  200:     if (defined($lonhost)) {
  201:         if (!defined(&hostname($lonhost))) {
  202:             undef($lonhost);
  203:         }
  204:     }
  205:     if (!defined($lonhost)) {
  206:         if (defined(&domain($dom,'primary'))) {
  207:             $lonhost=&domain($dom,'primary');
  208:             if ($lonhost eq 'no_host') {
  209:                 undef($lonhost);
  210:             }
  211:         }
  212:     }
  213:     if (defined($lonhost)) {
  214:         my $cachetime = 24*3600;
  215:         my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  216:         if (defined($cached)) {
  217:             return $loncaparev;
  218:         } else {
  219:             my $loncaparev = &reply('serverloncaparev',$lonhost);
  220:             return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  221:         }
  222:     }
  223: }
  224: 
  225: # -------------------------------------------------- Non-critical communication
  226: sub subreply {
  227:     my ($cmd,$server)=@_;
  228:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  229:     #
  230:     #  With loncnew process trimming, there's a timing hole between lonc server
  231:     #  process exit and the master server picking up the listen on the AF_UNIX
  232:     #  socket.  In that time interval, a lock file will exist:
  233: 
  234:     my $lockfile=$peerfile.".lock";
  235:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  236: 	sleep(1);
  237:     }
  238:     # At this point, either a loncnew parent is listening or an old lonc
  239:     # or loncnew child is listening so we can connect or everything's dead.
  240:     #
  241:     #   We'll give the connection a few tries before abandoning it.  If
  242:     #   connection is not possible, we'll con_lost back to the client.
  243:     #   
  244:     my $client;
  245:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  246: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  247: 				      Type    => SOCK_STREAM,
  248: 				      Timeout => 10);
  249: 	if ($client) {
  250: 	    last;		# Connected!
  251: 	} else {
  252: 	    &create_connection(&hostname($server),$server);
  253: 	}
  254:         sleep(1);		# Try again later if failed connection.
  255:     }
  256:     my $answer;
  257:     if ($client) {
  258: 	print $client "sethost:$server:$cmd\n";
  259: 	$answer=<$client>;
  260: 	if (!$answer) { $answer="con_lost"; }
  261: 	chomp($answer);
  262:     } else {
  263: 	$answer = 'con_lost';	# Failed connection.
  264:     }
  265:     return $answer;
  266: }
  267: 
  268: sub reply {
  269:     my ($cmd,$server)=@_;
  270:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  271:     my $answer=subreply($cmd,$server);
  272:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  273:        &logthis("<font color=\"blue\">WARNING:".
  274:                 " $cmd to $server returned $answer</font>");
  275:     }
  276:     return $answer;
  277: }
  278: 
  279: # ----------------------------------------------------------- Send USR1 to lonc
  280: 
  281: sub reconlonc {
  282:     my ($lonid) = @_;
  283:     my $hostname = &hostname($lonid);
  284:     if ($lonid) {
  285: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  286: 	if ($hostname && -e $peerfile) {
  287: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  288: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  289: 					     Type    => SOCK_STREAM,
  290: 					     Timeout => 10);
  291: 	    if ($client) {
  292: 		print $client ("reset_retries\n");
  293: 		my $answer=<$client>;
  294: 		#reset just this one.
  295: 	    }
  296: 	}
  297: 	return;
  298:     }
  299: 
  300:     &logthis("Trying to reconnect lonc");
  301:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  302:     if (open(my $fh,"<$loncfile")) {
  303: 	my $loncpid=<$fh>;
  304:         chomp($loncpid);
  305:         if (kill 0 => $loncpid) {
  306: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  307:             kill USR1 => $loncpid;
  308:             sleep 1;
  309:          } else {
  310: 	    &logthis(
  311:                "<font color=\"blue\">WARNING:".
  312:                " lonc at pid $loncpid not responding, giving up</font>");
  313:         }
  314:     } else {
  315: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  316:     }
  317: }
  318: 
  319: # ------------------------------------------------------ Critical communication
  320: 
  321: sub critical {
  322:     my ($cmd,$server)=@_;
  323:     unless (&hostname($server)) {
  324:         &logthis("<font color=\"blue\">WARNING:".
  325:                " Critical message to unknown server ($server)</font>");
  326:         return 'no_such_host';
  327:     }
  328:     my $answer=reply($cmd,$server);
  329:     if ($answer eq 'con_lost') {
  330: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  331: 	my $answer=reply($cmd,$server);
  332:         if ($answer eq 'con_lost') {
  333:             my $now=time;
  334:             my $middlename=$cmd;
  335:             $middlename=substr($middlename,0,16);
  336:             $middlename=~s/\W//g;
  337:             my $dfilename=
  338:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  339:             $dumpcount++;
  340:             {
  341: 		my $dfh;
  342: 		if (open($dfh,">$dfilename")) {
  343: 		    print $dfh "$cmd\n"; 
  344: 		    close($dfh);
  345: 		}
  346:             }
  347:             sleep 2;
  348:             my $wcmd='';
  349:             {
  350: 		my $dfh;
  351: 		if (open($dfh,"<$dfilename")) {
  352: 		    $wcmd=<$dfh>; 
  353: 		    close($dfh);
  354: 		}
  355:             }
  356:             chomp($wcmd);
  357:             if ($wcmd eq $cmd) {
  358: 		&logthis("<font color=\"blue\">WARNING: ".
  359:                          "Connection buffer $dfilename: $cmd</font>");
  360:                 &logperm("D:$server:$cmd");
  361: 	        return 'con_delayed';
  362:             } else {
  363:                 &logthis("<font color=\"red\">CRITICAL:"
  364:                         ." Critical connection failed: $server $cmd</font>");
  365:                 &logperm("F:$server:$cmd");
  366:                 return 'con_failed';
  367:             }
  368:         }
  369:     }
  370:     return $answer;
  371: }
  372: 
  373: # ------------------------------------------- check if return value is an error
  374: 
  375: sub error {
  376:     my ($result) = @_;
  377:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  378: 	if ($2 == 2) { return undef; }
  379: 	return $1;
  380:     }
  381:     return undef;
  382: }
  383: 
  384: sub convert_and_load_session_env {
  385:     my ($lonidsdir,$handle)=@_;
  386:     my @profile;
  387:     {
  388: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  389: 	if (!$opened) {
  390: 	    return 0;
  391: 	}
  392: 	flock($idf,LOCK_SH);
  393: 	@profile=<$idf>;
  394: 	close($idf);
  395:     }
  396:     my %temp_env;
  397:     foreach my $line (@profile) {
  398: 	if ($line !~ m/=/) {
  399: 	    return 0;
  400: 	}
  401: 	chomp($line);
  402: 	my ($envname,$envvalue)=split(/=/,$line,2);
  403: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  404:     }
  405:     unlink("$lonidsdir/$handle.id");
  406:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  407: 	    0640)) {
  408: 	%disk_env = %temp_env;
  409: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  410: 	untie(%disk_env);
  411:     }
  412:     return 1;
  413: }
  414: 
  415: # ------------------------------------------- Transfer profile into environment
  416: my $env_loaded;
  417: sub transfer_profile_to_env {
  418:     my ($lonidsdir,$handle,$force_transfer) = @_;
  419:     if (!$force_transfer && $env_loaded) { return; } 
  420: 
  421:     if (!defined($lonidsdir)) {
  422: 	$lonidsdir = $perlvar{'lonIDsDir'};
  423:     }
  424:     if (!defined($handle)) {
  425:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  426:     }
  427: 
  428:     my $convert;
  429:     {
  430:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  431: 	if (!$opened) {
  432: 	    return;
  433: 	}
  434: 	flock($idf,LOCK_SH);
  435: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  436: 		&GDBM_READER(),0640)) {
  437: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  438: 	    untie(%disk_env);
  439: 	} else {
  440: 	    $convert = 1;
  441: 	}
  442:     }
  443:     if ($convert) {
  444: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  445: 	    &logthis("Failed to load session, or convert session.");
  446: 	}
  447:     }
  448: 
  449:     my %remove;
  450:     while ( my $envname = each(%env) ) {
  451:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  452:             if ($time < time-300) {
  453:                 $remove{$key}++;
  454:             }
  455:         }
  456:     }
  457: 
  458:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  459:     $env_loaded=1;
  460:     foreach my $expired_key (keys(%remove)) {
  461:         &delenv($expired_key);
  462:     }
  463: }
  464: 
  465: # ---------------------------------------------------- Check for valid session 
  466: sub check_for_valid_session {
  467:     my ($r) = @_;
  468:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  469:     my $lonid=$cookies{'lonID'};
  470:     return undef if (!$lonid);
  471: 
  472:     my $handle=&LONCAPA::clean_handle($lonid->value);
  473:     my $lonidsdir=$r->dir_config('lonIDsDir');
  474:     return undef if (!-e "$lonidsdir/$handle.id");
  475: 
  476:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  477:     return undef if (!$opened);
  478: 
  479:     flock($idf,LOCK_SH);
  480:     my %disk_env;
  481:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  482: 	    &GDBM_READER(),0640)) {
  483: 	return undef;	
  484:     }
  485: 
  486:     if (!defined($disk_env{'user.name'})
  487: 	|| !defined($disk_env{'user.domain'})) {
  488: 	return undef;
  489:     }
  490:     return $handle;
  491: }
  492: 
  493: sub timed_flock {
  494:     my ($file,$lock_type) = @_;
  495:     my $failed=0;
  496:     eval {
  497: 	local $SIG{__DIE__}='DEFAULT';
  498: 	local $SIG{ALRM}=sub {
  499: 	    $failed=1;
  500: 	    die("failed lock");
  501: 	};
  502: 	alarm(13);
  503: 	flock($file,$lock_type);
  504: 	alarm(0);
  505:     };
  506:     if ($failed) {
  507: 	return undef;
  508:     } else {
  509: 	return 1;
  510:     }
  511: }
  512: 
  513: # ---------------------------------------------------------- Append Environment
  514: 
  515: sub appenv {
  516:     my ($newenv,$roles) = @_;
  517:     if (ref($newenv) eq 'HASH') {
  518:         foreach my $key (keys(%{$newenv})) {
  519:             my $refused = 0;
  520: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  521:                 $refused = 1;
  522:                 if (ref($roles) eq 'ARRAY') {
  523:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  524:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  525:                         $refused = 0;
  526:                     }
  527:                 }
  528:             }
  529:             if ($refused) {
  530:                 &logthis("<font color=\"blue\">WARNING: ".
  531:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  532:                          .'</font>');
  533: 	        delete($newenv->{$key});
  534:             } else {
  535:                 $env{$key}=$newenv->{$key};
  536:             }
  537:         }
  538:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  539:         if ($opened
  540: 	    && &timed_flock($env_file,LOCK_EX)
  541: 	    &&
  542: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  543: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  544: 	    while (my ($key,$value) = each(%{$newenv})) {
  545: 	        $disk_env{$key} = $value;
  546: 	    }
  547: 	    untie(%disk_env);
  548:         }
  549:     }
  550:     return 'ok';
  551: }
  552: # ----------------------------------------------------- Delete from Environment
  553: 
  554: sub delenv {
  555:     my ($delthis,$regexp) = @_;
  556:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  557:         &logthis("<font color=\"blue\">WARNING: ".
  558:                 "Attempt to delete from environment ".$delthis);
  559:         return 'error';
  560:     }
  561:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  562:     if ($opened
  563: 	&& &timed_flock($env_file,LOCK_EX)
  564: 	&&
  565: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  566: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  567: 	foreach my $key (keys(%disk_env)) {
  568: 	    if ($regexp) {
  569:                 if ($key=~/^$delthis/) {
  570:                     delete($env{$key});
  571:                     delete($disk_env{$key});
  572:                 } 
  573:             } else {
  574:                 if ($key=~/^\Q$delthis\E/) {
  575: 		    delete($env{$key});
  576: 		    delete($disk_env{$key});
  577: 	        }
  578:             }
  579: 	}
  580: 	untie(%disk_env);
  581:     }
  582:     return 'ok';
  583: }
  584: 
  585: sub get_env_multiple {
  586:     my ($name) = @_;
  587:     my @values;
  588:     if (defined($env{$name})) {
  589:         # exists is it an array
  590:         if (ref($env{$name})) {
  591:             @values=@{ $env{$name} };
  592:         } else {
  593:             $values[0]=$env{$name};
  594:         }
  595:     }
  596:     return(@values);
  597: }
  598: 
  599: # ------------------------------------------------------------------- Locking
  600: 
  601: sub set_lock {
  602:     my ($text)=@_;
  603:     $locknum++;
  604:     my $id=$$.'-'.$locknum;
  605:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  606:              'session.lock.'.$id => $text});
  607:     return $id;
  608: }
  609: 
  610: sub get_locks {
  611:     my $num=0;
  612:     my %texts=();
  613:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  614:        if ($lock=~/\w/) {
  615:           $num++;
  616:           $texts{$lock}=$env{'session.lock.'.$lock};
  617:        }
  618:    }
  619:    return ($num,%texts);
  620: }
  621: 
  622: sub remove_lock {
  623:     my ($id)=@_;
  624:     my $newlocks='';
  625:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  626:        if (($lock=~/\w/) && ($lock ne $id)) {
  627:           $newlocks.=','.$lock;
  628:        }
  629:     }
  630:     &appenv({'session.locks' => $newlocks});
  631:     &delenv('session.lock.'.$id);
  632: }
  633: 
  634: sub remove_all_locks {
  635:     my $activelocks=$env{'session.locks'};
  636:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  637:        if ($lock=~/\w/) {
  638:           &remove_lock($lock);
  639:        }
  640:     }
  641: }
  642: 
  643: 
  644: # ------------------------------------------ Find out current server userload
  645: sub userload {
  646:     my $numusers=0;
  647:     {
  648: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  649: 	my $filename;
  650: 	my $curtime=time;
  651: 	while ($filename=readdir(LONIDS)) {
  652: 	    next if ($filename eq '.' || $filename eq '..');
  653: 	    next if ($filename =~ /publicuser_\d+\.id/);
  654: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  655: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  656: 	}
  657: 	closedir(LONIDS);
  658:     }
  659:     my $userloadpercent=0;
  660:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  661:     if ($maxuserload) {
  662: 	$userloadpercent=100*$numusers/$maxuserload;
  663:     }
  664:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  665:     return $userloadpercent;
  666: }
  667: 
  668: # ------------------------------------------ Fight off request when overloaded
  669: 
  670: sub overloaderror {
  671:     my ($r,$checkserver)=@_;
  672:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  673:     my $loadavg;
  674:     if ($checkserver eq $perlvar{'lonHostID'}) {
  675:        open(my $loadfile,'/proc/loadavg');
  676:        $loadavg=<$loadfile>;
  677:        $loadavg =~ s/\s.*//g;
  678:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  679:        close($loadfile);
  680:     } else {
  681:        $loadavg=&reply('load',$checkserver);
  682:     }
  683:     my $overload=$loadavg-100;
  684:     if ($overload>0) {
  685: 	$r->err_headers_out->{'Retry-After'}=$overload;
  686:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  687:         return 413;
  688:     }    
  689:     return '';
  690: }
  691: 
  692: # ------------------------------ Find server with least workload from spare.tab
  693: 
  694: sub spareserver {
  695:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  696:     my $spare_server;
  697:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  698:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  699:                                                      :  $userloadpercent;
  700:     
  701:     foreach my $try_server (@{ $spareid{'primary'} }) {
  702: 	($spare_server, $lowest_load) =
  703: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  704:     }
  705: 
  706:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  707: 
  708:     if (!$found_server) {
  709: 	foreach my $try_server (@{ $spareid{'default'} }) {
  710: 	    ($spare_server, $lowest_load) =
  711: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  712: 	}
  713:     }
  714: 
  715:     if (!$want_server_name) {
  716:         my $protocol = 'http';
  717:         if ($protocol{$spare_server} eq 'https') {
  718:             $protocol = $protocol{$spare_server};
  719:         }
  720:         if (defined($spare_server)) {
  721:             my $hostname = &hostname($spare_server);
  722:             if (defined($hostname)) {  
  723: 	        $spare_server = $protocol.'://'.$hostname;
  724:             }
  725:         }
  726:     }
  727:     return $spare_server;
  728: }
  729: 
  730: sub compare_server_load {
  731:     my ($try_server, $spare_server, $lowest_load) = @_;
  732: 
  733:     my $loadans     = &reply('load',    $try_server);
  734:     my $userloadans = &reply('userload',$try_server);
  735: 
  736:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  737: 	next; #didn't get a number from the server
  738:     }
  739: 
  740:     my $load;
  741:     if ($loadans =~ /\d/) {
  742: 	if ($userloadans =~ /\d/) {
  743: 	    #both are numbers, pick the bigger one
  744: 	    $load = ($loadans > $userloadans) ? $loadans 
  745: 		                              : $userloadans;
  746: 	} else {
  747: 	    $load = $loadans;
  748: 	}
  749:     } else {
  750: 	$load = $userloadans;
  751:     }
  752: 
  753:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  754: 	$spare_server = $try_server;
  755: 	$lowest_load  = $load;
  756:     }
  757:     return ($spare_server,$lowest_load);
  758: }
  759: 
  760: # --------------------------- ask offload servers if user already has a session
  761: sub find_existing_session {
  762:     my ($udom,$uname) = @_;
  763:     foreach my $try_server (@{ $spareid{'primary'} },
  764: 			    @{ $spareid{'default'} }) {
  765: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
  766:     }
  767:     return;
  768: }
  769: 
  770: # -------------------------------- ask if server already has a session for user
  771: sub has_user_session {
  772:     my ($lonid,$udom,$uname) = @_;
  773:     my $result = &reply(join(':','userhassession',
  774: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  775:     return 1 if ($result eq 'ok');
  776: 
  777:     return 0;
  778: }
  779: 
  780: # --------------------------------------------- Try to change a user's password
  781: 
  782: sub changepass {
  783:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  784:     $currentpass = &escape($currentpass);
  785:     $newpass     = &escape($newpass);
  786:     my $lonhost = $perlvar{'lonHostID'};
  787:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  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:     } elsif ($answer =~ "invalid_client") {
  813:         &logthis("$server refused to change $uname in $udom password because ".
  814:                  "it was a reset by e-mail originating from an invalid server.");
  815:     }
  816:     return $answer;
  817: }
  818: 
  819: # ----------------------- Try to determine user's current authentication scheme
  820: 
  821: sub queryauthenticate {
  822:     my ($uname,$udom)=@_;
  823:     my $uhome=&homeserver($uname,$udom);
  824:     if (!$uhome) {
  825: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  826: 	return 'no_host';
  827:     }
  828:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  829:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  830: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  831:     }
  832:     return $answer;
  833: }
  834: 
  835: # --------- Try to authenticate user from domain's lib servers (first this one)
  836: 
  837: sub authenticate {
  838:     my ($uname,$upass,$udom,$checkdefauth)=@_;
  839:     $upass=&escape($upass);
  840:     $uname= &LONCAPA::clean_username($uname);
  841:     my $uhome=&homeserver($uname,$udom,1);
  842:     my $newhome;
  843:     if ((!$uhome) || ($uhome eq 'no_host')) {
  844: # Maybe the machine was offline and only re-appeared again recently?
  845:         &reconlonc();
  846: # One more
  847: 	$uhome=&homeserver($uname,$udom,1);
  848:         if (($uhome eq 'no_host') && $checkdefauth) {
  849:             if (defined(&domain($udom,'primary'))) {
  850:                 $newhome=&domain($udom,'primary');
  851:             }
  852:             if ($newhome ne '') {
  853:                 $uhome = $newhome;
  854:             }
  855:         }
  856: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  857: 	    &logthis("User $uname at $udom is unknown in authenticate");
  858: 	    return 'no_host';
  859:         }
  860:     }
  861:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
  862:     if ($answer eq 'authorized') {
  863:         if ($newhome) {
  864:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
  865:             return 'no_account_on_host'; 
  866:         } else {
  867:             &logthis("User $uname at $udom authorized by $uhome");
  868:             return $uhome;
  869:         }
  870:     }
  871:     if ($answer eq 'non_authorized') {
  872: 	&logthis("User $uname at $udom rejected by $uhome");
  873: 	return 'no_host'; 
  874:     }
  875:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  876:     return 'no_host';
  877: }
  878: 
  879: # ---------------------- Find the homebase for a user from domain's lib servers
  880: 
  881: my %homecache;
  882: sub homeserver {
  883:     my ($uname,$udom,$ignoreBadCache)=@_;
  884:     my $index="$uname:$udom";
  885: 
  886:     if (exists($homecache{$index})) { return $homecache{$index}; }
  887: 
  888:     my %servers = &get_servers($udom,'library');
  889:     foreach my $tryserver (keys(%servers)) {
  890:         next if ($ignoreBadCache ne 'true' && 
  891: 		 exists($badServerCache{$tryserver}));
  892: 
  893: 	my $answer=reply("home:$udom:$uname",$tryserver);
  894: 	if ($answer eq 'found') {
  895: 	    delete($badServerCache{$tryserver}); 
  896: 	    return $homecache{$index}=$tryserver;
  897: 	} elsif ($answer eq 'no_host') {
  898: 	    $badServerCache{$tryserver}=1;
  899: 	}
  900:     }    
  901:     return 'no_host';
  902: }
  903: 
  904: # ------------------------------------- Find the usernames behind a list of IDs
  905: 
  906: sub idget {
  907:     my ($udom,@ids)=@_;
  908:     my %returnhash=();
  909:     
  910:     my %servers = &get_servers($udom,'library');
  911:     foreach my $tryserver (keys(%servers)) {
  912: 	my $idlist=join('&',@ids);
  913: 	$idlist=~tr/A-Z/a-z/; 
  914: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  915: 	my @answer=();
  916: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  917: 	    @answer=split(/\&/,$reply);
  918: 	}                    ;
  919: 	my $i;
  920: 	for ($i=0;$i<=$#ids;$i++) {
  921: 	    if ($answer[$i]) {
  922: 		$returnhash{$ids[$i]}=$answer[$i];
  923: 	    } 
  924: 	}
  925:     } 
  926:     return %returnhash;
  927: }
  928: 
  929: # ------------------------------------- Find the IDs behind a list of usernames
  930: 
  931: sub idrget {
  932:     my ($udom,@unames)=@_;
  933:     my %returnhash=();
  934:     foreach my $uname (@unames) {
  935:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  936:     }
  937:     return %returnhash;
  938: }
  939: 
  940: # ------------------------------- Store away a list of names and associated IDs
  941: 
  942: sub idput {
  943:     my ($udom,%ids)=@_;
  944:     my %servers=();
  945:     foreach my $uname (keys(%ids)) {
  946: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  947:         my $uhom=&homeserver($uname,$udom);
  948:         if ($uhom ne 'no_host') {
  949:             my $id=&escape($ids{$uname});
  950:             $id=~tr/A-Z/a-z/;
  951:             my $esc_unam=&escape($uname);
  952: 	    if ($servers{$uhom}) {
  953: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  954:             } else {
  955:                 $servers{$uhom}=$id.'='.$esc_unam;
  956:             }
  957:         }
  958:     }
  959:     foreach my $server (keys(%servers)) {
  960:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  961:     }
  962: }
  963: 
  964: # ------------------------------dump from db file owned by domainconfig user
  965: sub dump_dom {
  966:     my ($namespace,$udom,$regexp,$range)=@_;
  967:     if (!$udom) {
  968:         $udom=$env{'user.domain'};
  969:     }
  970:     my %returnhash;
  971:     if ($udom) {
  972:         my $uname = &get_domainconfiguser($udom);
  973:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
  974:     }
  975:     return %returnhash;
  976: }
  977: 
  978: # ------------------------------------------ get items from domain db files   
  979: 
  980: sub get_dom {
  981:     my ($namespace,$storearr,$udom,$uhome)=@_;
  982:     my $items='';
  983:     foreach my $item (@$storearr) {
  984:         $items.=&escape($item).'&';
  985:     }
  986:     $items=~s/\&$//;
  987:     if (!$udom) {
  988:         $udom=$env{'user.domain'};
  989:         if (defined(&domain($udom,'primary'))) {
  990:             $uhome=&domain($udom,'primary');
  991:         } else {
  992:             undef($uhome);
  993:         }
  994:     } else {
  995:         if (!$uhome) {
  996:             if (defined(&domain($udom,'primary'))) {
  997:                 $uhome=&domain($udom,'primary');
  998:             }
  999:         }
 1000:     }
 1001:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1002:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1003:         my %returnhash;
 1004:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1005:             return %returnhash;
 1006:         }
 1007:         my @pairs=split(/\&/,$rep);
 1008:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1009:             return @pairs;
 1010:         }
 1011:         my $i=0;
 1012:         foreach my $item (@$storearr) {
 1013:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1014:             $i++;
 1015:         }
 1016:         return %returnhash;
 1017:     } else {
 1018:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1019:     }
 1020: }
 1021: 
 1022: # -------------------------------------------- put items in domain db files 
 1023: 
 1024: sub put_dom {
 1025:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1026:     if (!$udom) {
 1027:         $udom=$env{'user.domain'};
 1028:         if (defined(&domain($udom,'primary'))) {
 1029:             $uhome=&domain($udom,'primary');
 1030:         } else {
 1031:             undef($uhome);
 1032:         }
 1033:     } else {
 1034:         if (!$uhome) {
 1035:             if (defined(&domain($udom,'primary'))) {
 1036:                 $uhome=&domain($udom,'primary');
 1037:             }
 1038:         }
 1039:     } 
 1040:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1041:         my $items='';
 1042:         foreach my $item (keys(%$storehash)) {
 1043:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1044:         }
 1045:         $items=~s/\&$//;
 1046:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1047:     } else {
 1048:         &logthis("put_dom failed - no homeserver and/or domain");
 1049:     }
 1050: }
 1051: 
 1052: # --------------------- newput for items in db file owned by domainconfig user
 1053: sub newput_dom {
 1054:     my ($namespace,$storehash,$udom) = @_;
 1055:     my $result;
 1056:     if (!$udom) {
 1057:         $udom=$env{'user.domain'};
 1058:     }
 1059:     if ($udom) {
 1060:         my $uname = &get_domainconfiguser($udom);
 1061:         $result = &newput($namespace,$storehash,$udom,$uname);
 1062:     }
 1063:     return $result;
 1064: }
 1065: 
 1066: # --------------------- delete for items in db file owned by domainconfig user
 1067: sub del_dom {
 1068:     my ($namespace,$storearr,$udom)=@_;
 1069:     if (ref($storearr) eq 'ARRAY') {
 1070:         if (!$udom) {
 1071:             $udom=$env{'user.domain'};
 1072:         }
 1073:         if ($udom) {
 1074:             my $uname = &get_domainconfiguser($udom); 
 1075:             return &del($namespace,$storearr,$udom,$uname);
 1076:         }
 1077:     }
 1078: }
 1079: 
 1080: # ----------------------------------construct domainconfig user for a domain 
 1081: sub get_domainconfiguser {
 1082:     my ($udom) = @_;
 1083:     return $udom.'-domainconfig';
 1084: }
 1085: 
 1086: sub retrieve_inst_usertypes {
 1087:     my ($udom) = @_;
 1088:     my (%returnhash,@order);
 1089:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1090:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1091:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1092:         %returnhash = %{$domdefs{'inststatustypes'}};
 1093:         @order = @{$domdefs{'inststatusorder'}};
 1094:     } else {
 1095:         if (defined(&domain($udom,'primary'))) {
 1096:             my $uhome=&domain($udom,'primary');
 1097:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1098:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1099:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1100:                 return (\%returnhash,\@order);
 1101:             }
 1102:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1103:             my @pairs=split(/\&/,$hashitems);
 1104:             foreach my $item (@pairs) {
 1105:                 my ($key,$value)=split(/=/,$item,2);
 1106:                 $key = &unescape($key);
 1107:                 next if ($key =~ /^error: 2 /);
 1108:                 $returnhash{$key}=&thaw_unescape($value);
 1109:             }
 1110:             my @esc_order = split(/\&/,$orderitems);
 1111:             foreach my $item (@esc_order) {
 1112:                 push(@order,&unescape($item));
 1113:             }
 1114:         } else {
 1115:             &logthis("get_dom failed - no primary domain server for $udom");
 1116:         }
 1117:     }
 1118:     return (\%returnhash,\@order);
 1119: }
 1120: 
 1121: sub is_domainimage {
 1122:     my ($url) = @_;
 1123:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1124:         if (&domain($1) ne '') {
 1125:             return '1';
 1126:         }
 1127:     }
 1128:     return;
 1129: }
 1130: 
 1131: sub inst_directory_query {
 1132:     my ($srch) = @_;
 1133:     my $udom = $srch->{'srchdomain'};
 1134:     my %results;
 1135:     my $homeserver = &domain($udom,'primary');
 1136:     my $outcome;
 1137:     if ($homeserver ne '') {
 1138: 	my $queryid=&reply("querysend:instdirsearch:".
 1139: 			   &escape($srch->{'srchby'}).':'.
 1140: 			   &escape($srch->{'srchterm'}).':'.
 1141: 			   &escape($srch->{'srchtype'}),$homeserver);
 1142: 	my $host=&hostname($homeserver);
 1143: 	if ($queryid !~/^\Q$host\E\_/) {
 1144: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1145: 	    return;
 1146: 	}
 1147: 	my $response = &get_query_reply($queryid);
 1148: 	my $maxtries = 5;
 1149: 	my $tries = 1;
 1150: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1151: 	    $response = &get_query_reply($queryid);
 1152: 	    $tries ++;
 1153: 	}
 1154: 
 1155:         if (!&error($response) && $response ne 'refused') {
 1156:             if ($response eq 'unavailable') {
 1157:                 $outcome = $response;
 1158:             } else {
 1159:                 $outcome = 'ok';
 1160:                 my @matches = split(/\n/,$response);
 1161:                 foreach my $match (@matches) {
 1162:                     my ($key,$value) = split(/=/,$match);
 1163:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1164:                 }
 1165:             }
 1166:         }
 1167:     }
 1168:     return ($outcome,%results);
 1169: }
 1170: 
 1171: sub usersearch {
 1172:     my ($srch) = @_;
 1173:     my $dom = $srch->{'srchdomain'};
 1174:     my %results;
 1175:     my %libserv = &all_library();
 1176:     my $query = 'usersearch';
 1177:     foreach my $tryserver (keys(%libserv)) {
 1178:         if (&host_domain($tryserver) eq $dom) {
 1179:             my $host=&hostname($tryserver);
 1180:             my $queryid=
 1181:                 &reply("querysend:".&escape($query).':'.
 1182:                        &escape($srch->{'srchby'}).':'.
 1183:                        &escape($srch->{'srchtype'}).':'.
 1184:                        &escape($srch->{'srchterm'}),$tryserver);
 1185:             if ($queryid !~/^\Q$host\E\_/) {
 1186:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1187:                 next;
 1188:             }
 1189:             my $reply = &get_query_reply($queryid);
 1190:             my $maxtries = 1;
 1191:             my $tries = 1;
 1192:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1193:                 $reply = &get_query_reply($queryid);
 1194:                 $tries ++;
 1195:             }
 1196:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1197:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1198:             } else {
 1199:                 my @matches;
 1200:                 if ($reply =~ /\n/) {
 1201:                     @matches = split(/\n/,$reply);
 1202:                 } else {
 1203:                     @matches = split(/\&/,$reply);
 1204:                 }
 1205:                 foreach my $match (@matches) {
 1206:                     my ($uname,$udom,%userhash);
 1207:                     foreach my $entry (split(/:/,$match)) {
 1208:                         my ($key,$value) =
 1209:                             map {&unescape($_);} split(/=/,$entry);
 1210:                         $userhash{$key} = $value;
 1211:                         if ($key eq 'username') {
 1212:                             $uname = $value;
 1213:                         } elsif ($key eq 'domain') {
 1214:                             $udom = $value;
 1215:                         }
 1216:                     }
 1217:                     $results{$uname.':'.$udom} = \%userhash;
 1218:                 }
 1219:             }
 1220:         }
 1221:     }
 1222:     return %results;
 1223: }
 1224: 
 1225: sub get_instuser {
 1226:     my ($udom,$uname,$id) = @_;
 1227:     my $homeserver = &domain($udom,'primary');
 1228:     my ($outcome,%results);
 1229:     if ($homeserver ne '') {
 1230:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1231:                            &escape($id).':'.&escape($udom),$homeserver);
 1232:         my $host=&hostname($homeserver);
 1233:         if ($queryid !~/^\Q$host\E\_/) {
 1234:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1235:             return;
 1236:         }
 1237:         my $response = &get_query_reply($queryid);
 1238:         my $maxtries = 5;
 1239:         my $tries = 1;
 1240:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1241:             $response = &get_query_reply($queryid);
 1242:             $tries ++;
 1243:         }
 1244:         if (!&error($response) && $response ne 'refused') {
 1245:             if ($response eq 'unavailable') {
 1246:                 $outcome = $response;
 1247:             } else {
 1248:                 $outcome = 'ok';
 1249:                 my @matches = split(/\n/,$response);
 1250:                 foreach my $match (@matches) {
 1251:                     my ($key,$value) = split(/=/,$match);
 1252:                     $results{&unescape($key)} = &thaw_unescape($value);
 1253:                 }
 1254:             }
 1255:         }
 1256:     }
 1257:     my %userinfo;
 1258:     if (ref($results{$uname}) eq 'HASH') {
 1259:         %userinfo = %{$results{$uname}};
 1260:     } 
 1261:     return ($outcome,%userinfo);
 1262: }
 1263: 
 1264: sub inst_rulecheck {
 1265:     my ($udom,$uname,$id,$item,$rules) = @_;
 1266:     my %returnhash;
 1267:     if ($udom ne '') {
 1268:         if (ref($rules) eq 'ARRAY') {
 1269:             @{$rules} = map {&escape($_);} (@{$rules});
 1270:             my $rulestr = join(':',@{$rules});
 1271:             my $homeserver=&domain($udom,'primary');
 1272:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1273:                 my $response;
 1274:                 if ($item eq 'username') {                
 1275:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1276:                                               ':'.&escape($uname).':'.$rulestr,
 1277:                                               $homeserver));
 1278:                 } elsif ($item eq 'id') {
 1279:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1280:                                               ':'.&escape($id).':'.$rulestr,
 1281:                                               $homeserver));
 1282:                 } elsif ($item eq 'selfcreate') {
 1283:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1284:                                                &escape($udom).':'.&escape($uname).
 1285:                                               ':'.$rulestr,$homeserver));
 1286:                 }
 1287:                 if ($response ne 'refused') {
 1288:                     my @pairs=split(/\&/,$response);
 1289:                     foreach my $item (@pairs) {
 1290:                         my ($key,$value)=split(/=/,$item,2);
 1291:                         $key = &unescape($key);
 1292:                         next if ($key =~ /^error: 2 /);
 1293:                         $returnhash{$key}=&thaw_unescape($value);
 1294:                     }
 1295:                 }
 1296:             }
 1297:         }
 1298:     }
 1299:     return %returnhash;
 1300: }
 1301: 
 1302: sub inst_userrules {
 1303:     my ($udom,$check) = @_;
 1304:     my (%ruleshash,@ruleorder);
 1305:     if ($udom ne '') {
 1306:         my $homeserver=&domain($udom,'primary');
 1307:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1308:             my $response;
 1309:             if ($check eq 'id') {
 1310:                 $response=&reply('instidrules:'.&escape($udom),
 1311:                                  $homeserver);
 1312:             } elsif ($check eq 'email') {
 1313:                 $response=&reply('instemailrules:'.&escape($udom),
 1314:                                  $homeserver);
 1315:             } else {
 1316:                 $response=&reply('instuserrules:'.&escape($udom),
 1317:                                  $homeserver);
 1318:             }
 1319:             if (($response ne 'refused') && ($response ne 'error') && 
 1320:                 ($response ne 'unknown_cmd') && 
 1321:                 ($response ne 'no_such_host')) {
 1322:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1323:                 my @pairs=split(/\&/,$hashitems);
 1324:                 foreach my $item (@pairs) {
 1325:                     my ($key,$value)=split(/=/,$item,2);
 1326:                     $key = &unescape($key);
 1327:                     next if ($key =~ /^error: 2 /);
 1328:                     $ruleshash{$key}=&thaw_unescape($value);
 1329:                 }
 1330:                 my @esc_order = split(/\&/,$orderitems);
 1331:                 foreach my $item (@esc_order) {
 1332:                     push(@ruleorder,&unescape($item));
 1333:                 }
 1334:             }
 1335:         }
 1336:     }
 1337:     return (\%ruleshash,\@ruleorder);
 1338: }
 1339: 
 1340: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1341: 
 1342: sub get_domain_defaults {
 1343:     my ($domain) = @_;
 1344:     my $cachetime = 60*60*24;
 1345:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1346:     if (defined($cached)) {
 1347:         if (ref($result) eq 'HASH') {
 1348:             return %{$result};
 1349:         }
 1350:     }
 1351:     my %domdefaults;
 1352:     my %domconfig =
 1353:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1354:                                   'requestcourses','inststatus',
 1355:                                   'coursedefaults'],$domain);
 1356:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1357:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1358:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1359:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1360:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1361:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1362:     } else {
 1363:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1364:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1365:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1366:     }
 1367:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1368:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1369:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1370:         } else {
 1371:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1372:         } 
 1373:         my @usertools = ('aboutme','blog','portfolio');
 1374:         foreach my $item (@usertools) {
 1375:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1376:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1377:             }
 1378:         }
 1379:     }
 1380:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1381:         foreach my $item ('official','unofficial','community') {
 1382:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1383:         }
 1384:     }
 1385:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 1386:         foreach my $item ('inststatustypes','inststatusorder') {
 1387:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 1388:         }
 1389:     }
 1390:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 1391:         foreach my $item ('canuse_pdfforms') {
 1392:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
 1393:         }
 1394:     }
 1395:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1396:                                   $cachetime);
 1397:     return %domdefaults;
 1398: }
 1399: 
 1400: # --------------------------------------------------- Assign a key to a student
 1401: 
 1402: sub assign_access_key {
 1403: #
 1404: # a valid key looks like uname:udom#comments
 1405: # comments are being appended
 1406: #
 1407:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1408:     $kdom=
 1409:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1410:     $knum=
 1411:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1412:     $cdom=
 1413:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1414:     $cnum=
 1415:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1416:     $udom=$env{'user.name'} unless (defined($udom));
 1417:     $uname=$env{'user.domain'} unless (defined($uname));
 1418:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1419:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1420:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1421:                                                   # assigned to this person
 1422:                                                   # - this should not happen,
 1423:                                                   # unless something went wrong
 1424:                                                   # the first time around
 1425: # ready to assign
 1426:         $logentry=$1.'; '.$logentry;
 1427:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1428:                                                  $kdom,$knum) eq 'ok') {
 1429: # key now belongs to user
 1430: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1431:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1432:                 &appenv({'environment.'.$envkey => $ckey});
 1433:                 return 'ok';
 1434:             } else {
 1435:                 return 
 1436:   'error: Count not permanently assign key, will need to be re-entered later.';
 1437: 	    }
 1438:         } else {
 1439:             return 'error: Could not assign key, try again later.';
 1440:         }
 1441:     } elsif (!$existing{$ckey}) {
 1442: # the key does not exist
 1443: 	return 'error: The key does not exist';
 1444:     } else {
 1445: # the key is somebody else's
 1446: 	return 'error: The key is already in use';
 1447:     }
 1448: }
 1449: 
 1450: # ------------------------------------------ put an additional comment on a key
 1451: 
 1452: sub comment_access_key {
 1453: #
 1454: # a valid key looks like uname:udom#comments
 1455: # comments are being appended
 1456: #
 1457:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1458:     $cdom=
 1459:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1460:     $cnum=
 1461:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1462:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1463:     if ($existing{$ckey}) {
 1464:         $existing{$ckey}.='; '.$logentry;
 1465: # ready to assign
 1466:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1467:                                                  $cdom,$cnum) eq 'ok') {
 1468: 	    return 'ok';
 1469:         } else {
 1470: 	    return 'error: Count not store comment.';
 1471:         }
 1472:     } else {
 1473: # the key does not exist
 1474: 	return 'error: The key does not exist';
 1475:     }
 1476: }
 1477: 
 1478: # ------------------------------------------------------ Generate a set of keys
 1479: 
 1480: sub generate_access_keys {
 1481:     my ($number,$cdom,$cnum,$logentry)=@_;
 1482:     $cdom=
 1483:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1484:     $cnum=
 1485:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1486:     unless (&allowed('mky',$cdom)) { return 0; }
 1487:     unless (($cdom) && ($cnum)) { return 0; }
 1488:     if ($number>10000) { return 0; }
 1489:     sleep(2); # make sure don't get same seed twice
 1490:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1491:     my $total=0;
 1492:     for (my $i=1;$i<=$number;$i++) {
 1493:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1494:                   sprintf("%lx",int(100000*rand)).'-'.
 1495:                   sprintf("%lx",int(100000*rand));
 1496:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1497:        $newkey=~s/0/h/g; # and also 0 and O
 1498:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1499:        if ($existing{$newkey}) {
 1500:            $i--;
 1501:        } else {
 1502: 	  if (&put('accesskeys',
 1503:               { $newkey => '# generated '.localtime().
 1504:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1505:                            '; '.$logentry },
 1506: 		   $cdom,$cnum) eq 'ok') {
 1507:               $total++;
 1508: 	  }
 1509:        }
 1510:     }
 1511:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1512:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1513:     return $total;
 1514: }
 1515: 
 1516: # ------------------------------------------------------- Validate an accesskey
 1517: 
 1518: sub validate_access_key {
 1519:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1520:     $cdom=
 1521:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1522:     $cnum=
 1523:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1524:     $udom=$env{'user.domain'} unless (defined($udom));
 1525:     $uname=$env{'user.name'} unless (defined($uname));
 1526:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1527:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1528: }
 1529: 
 1530: # ------------------------------------- Find the section of student in a course
 1531: sub devalidate_getsection_cache {
 1532:     my ($udom,$unam,$courseid)=@_;
 1533:     my $hashid="$udom:$unam:$courseid";
 1534:     &devalidate_cache_new('getsection',$hashid);
 1535: }
 1536: 
 1537: sub courseid_to_courseurl {
 1538:     my ($courseid) = @_;
 1539:     #already url style courseid
 1540:     return $courseid if ($courseid =~ m{^/});
 1541: 
 1542:     if (exists($env{'course.'.$courseid.'.num'})) {
 1543: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1544: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1545: 	return "/$cdom/$cnum";
 1546:     }
 1547: 
 1548:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1549:     if (exists($courseinfo{'num'})) {
 1550: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1551:     }
 1552: 
 1553:     return undef;
 1554: }
 1555: 
 1556: sub getsection {
 1557:     my ($udom,$unam,$courseid)=@_;
 1558:     my $cachetime=1800;
 1559: 
 1560:     my $hashid="$udom:$unam:$courseid";
 1561:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1562:     if (defined($cached)) { return $result; }
 1563: 
 1564:     my %Pending; 
 1565:     my %Expired;
 1566:     #
 1567:     # Each role can either have not started yet (pending), be active, 
 1568:     #    or have expired.
 1569:     #
 1570:     # If there is an active role, we are done.
 1571:     #
 1572:     # If there is more than one role which has not started yet, 
 1573:     #     choose the one which will start sooner
 1574:     # If there is one role which has not started yet, return it.
 1575:     #
 1576:     # If there is more than one expired role, choose the one which ended last.
 1577:     # If there is a role which has expired, return it.
 1578:     #
 1579:     $courseid = &courseid_to_courseurl($courseid);
 1580:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1581:     foreach my $key (keys(%roleshash)) {
 1582:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1583:         my $section=$1;
 1584:         if ($key eq $courseid.'_st') { $section=''; }
 1585:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1586:         my $now=time;
 1587:         if (defined($end) && $end && ($now > $end)) {
 1588:             $Expired{$end}=$section;
 1589:             next;
 1590:         }
 1591:         if (defined($start) && $start && ($now < $start)) {
 1592:             $Pending{$start}=$section;
 1593:             next;
 1594:         }
 1595:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1596:     }
 1597:     #
 1598:     # Presumedly there will be few matching roles from the above
 1599:     # loop and the sorting time will be negligible.
 1600:     if (scalar(keys(%Pending))) {
 1601:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1602:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1603:     } 
 1604:     if (scalar(keys(%Expired))) {
 1605:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1606:         my $time = pop(@sorted);
 1607:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1608:     }
 1609:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1610: }
 1611: 
 1612: sub save_cache {
 1613:     &purge_remembered();
 1614:     #&Apache::loncommon::validate_page();
 1615:     undef(%env);
 1616:     undef($env_loaded);
 1617: }
 1618: 
 1619: my $to_remember=-1;
 1620: my %remembered;
 1621: my %accessed;
 1622: my $kicks=0;
 1623: my $hits=0;
 1624: sub make_key {
 1625:     my ($name,$id) = @_;
 1626:     if (length($id) > 65 
 1627: 	&& length(&escape($id)) > 200) {
 1628: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1629:     }
 1630:     return &escape($name.':'.$id);
 1631: }
 1632: 
 1633: sub devalidate_cache_new {
 1634:     my ($name,$id,$debug) = @_;
 1635:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1636:     $id=&make_key($name,$id);
 1637:     $memcache->delete($id);
 1638:     delete($remembered{$id});
 1639:     delete($accessed{$id});
 1640: }
 1641: 
 1642: sub is_cached_new {
 1643:     my ($name,$id,$debug) = @_;
 1644:     $id=&make_key($name,$id);
 1645:     if (exists($remembered{$id})) {
 1646: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1647: 	$accessed{$id}=[&gettimeofday()];
 1648: 	$hits++;
 1649: 	return ($remembered{$id},1);
 1650:     }
 1651:     my $value = $memcache->get($id);
 1652:     if (!(defined($value))) {
 1653: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1654: 	return (undef,undef);
 1655:     }
 1656:     if ($value eq '__undef__') {
 1657: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1658: 	$value=undef;
 1659:     }
 1660:     &make_room($id,$value,$debug);
 1661:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1662:     return ($value,1);
 1663: }
 1664: 
 1665: sub do_cache_new {
 1666:     my ($name,$id,$value,$time,$debug) = @_;
 1667:     $id=&make_key($name,$id);
 1668:     my $setvalue=$value;
 1669:     if (!defined($setvalue)) {
 1670: 	$setvalue='__undef__';
 1671:     }
 1672:     if (!defined($time) ) {
 1673: 	$time=600;
 1674:     }
 1675:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1676:     my $result = $memcache->set($id,$setvalue,$time);
 1677:     if (! $result) {
 1678: 	&logthis("caching of id -> $id  failed");
 1679: 	$memcache->disconnect_all();
 1680:     }
 1681:     # need to make a copy of $value
 1682:     &make_room($id,$value,$debug);
 1683:     return $value;
 1684: }
 1685: 
 1686: sub make_room {
 1687:     my ($id,$value,$debug)=@_;
 1688: 
 1689:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1690:                                     : $value;
 1691:     if ($to_remember<0) { return; }
 1692:     $accessed{$id}=[&gettimeofday()];
 1693:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1694:     my $to_kick;
 1695:     my $max_time=0;
 1696:     foreach my $other (keys(%accessed)) {
 1697: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1698: 	    $to_kick=$other;
 1699: 	    $max_time=&tv_interval($accessed{$other});
 1700: 	}
 1701:     }
 1702:     delete($remembered{$to_kick});
 1703:     delete($accessed{$to_kick});
 1704:     $kicks++;
 1705:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1706:     return;
 1707: }
 1708: 
 1709: sub purge_remembered {
 1710:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1711:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1712:     undef(%remembered);
 1713:     undef(%accessed);
 1714: }
 1715: # ------------------------------------- Read an entry from a user's environment
 1716: 
 1717: sub userenvironment {
 1718:     my ($udom,$unam,@what)=@_;
 1719:     my $items;
 1720:     foreach my $item (@what) {
 1721:         $items.=&escape($item).'&';
 1722:     }
 1723:     $items=~s/\&$//;
 1724:     my %returnhash=();
 1725:     my $uhome = &homeserver($unam,$udom);
 1726:     unless ($uhome eq 'no_host') {
 1727:         my @answer=split(/\&/, 
 1728:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 1729:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 1730:             return %returnhash;
 1731:         }
 1732:         my $i;
 1733:         for ($i=0;$i<=$#what;$i++) {
 1734: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 1735:         }
 1736:     }
 1737:     return %returnhash;
 1738: }
 1739: 
 1740: # ---------------------------------------------------------- Get a studentphoto
 1741: sub studentphoto {
 1742:     my ($udom,$unam,$ext) = @_;
 1743:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1744:     if (defined($env{'request.course.id'})) {
 1745:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1746:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1747:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1748:             } else {
 1749:                 my ($result,$perm_reqd)=
 1750: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1751:                 if ($result eq 'ok') {
 1752:                     if (!($perm_reqd eq 'yes')) {
 1753:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1754:                     }
 1755:                 }
 1756:             }
 1757:         }
 1758:     } else {
 1759:         my ($result,$perm_reqd) = 
 1760: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1761:         if ($result eq 'ok') {
 1762:             if (!($perm_reqd eq 'yes')) {
 1763:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1764:             }
 1765:         }
 1766:     }
 1767:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1768: }
 1769: 
 1770: sub retrievestudentphoto {
 1771:     my ($udom,$unam,$ext,$type) = @_;
 1772:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1773:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1774:     if ($ret eq 'ok') {
 1775:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1776:         if ($type eq 'thumbnail') {
 1777:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1778:         }
 1779:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1780:         return $tokenurl;
 1781:     } else {
 1782:         if ($type eq 'thumbnail') {
 1783:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1784:         } else { 
 1785:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1786:         }
 1787:     }
 1788: }
 1789: 
 1790: # -------------------------------------------------------------------- New chat
 1791: 
 1792: sub chatsend {
 1793:     my ($newentry,$anon,$group)=@_;
 1794:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1795:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1796:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1797:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1798: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1799: 		   &escape($newentry)).':'.$group,$chome);
 1800: }
 1801: 
 1802: # ------------------------------------------ Find current version of a resource
 1803: 
 1804: sub getversion {
 1805:     my $fname=&clutter(shift);
 1806:     unless ($fname=~/^\/res\//) { return -1; }
 1807:     return &currentversion(&filelocation('',$fname));
 1808: }
 1809: 
 1810: sub currentversion {
 1811:     my $fname=shift;
 1812:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1813:     if (defined($cached)) { return $result; }
 1814:     my $author=$fname;
 1815:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1816:     my ($udom,$uname)=split(/\//,$author);
 1817:     my $home=homeserver($uname,$udom);
 1818:     if ($home eq 'no_host') { 
 1819:         return -1; 
 1820:     }
 1821:     my $answer=reply("currentversion:$fname",$home);
 1822:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1823: 	return -1;
 1824:     }
 1825:     return &do_cache_new('resversion',$fname,$answer,600);
 1826: }
 1827: 
 1828: # ----------------------------- Subscribe to a resource, return URL if possible
 1829: 
 1830: sub subscribe {
 1831:     my $fname=shift;
 1832:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1833:     $fname=~s/[\n\r]//g;
 1834:     my $author=$fname;
 1835:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1836:     my ($udom,$uname)=split(/\//,$author);
 1837:     my $home=homeserver($uname,$udom);
 1838:     if ($home eq 'no_host') {
 1839:         return 'not_found';
 1840:     }
 1841:     my $answer=reply("sub:$fname",$home);
 1842:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1843: 	$answer.=' by '.$home;
 1844:     }
 1845:     return $answer;
 1846: }
 1847:     
 1848: # -------------------------------------------------------------- Replicate file
 1849: 
 1850: sub repcopy {
 1851:     my $filename=shift;
 1852:     $filename=~s/\/+/\//g;
 1853:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1854:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1855:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1856: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1857: 	return &repcopy_userfile($filename);
 1858:     }
 1859:     $filename=~s/[\n\r]//g;
 1860:     my $transname="$filename.in.transfer";
 1861: # FIXME: this should flock
 1862:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1863:     my $remoteurl=subscribe($filename);
 1864:     if ($remoteurl =~ /^con_lost by/) {
 1865: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1866:            return 'unavailable';
 1867:     } elsif ($remoteurl eq 'not_found') {
 1868: 	   #&logthis("Subscribe returned not_found: $filename");
 1869: 	   return 'not_found';
 1870:     } elsif ($remoteurl =~ /^rejected by/) {
 1871: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1872:            return 'forbidden';
 1873:     } elsif ($remoteurl eq 'directory') {
 1874:            return 'ok';
 1875:     } else {
 1876:         my $author=$filename;
 1877:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1878:         my ($udom,$uname)=split(/\//,$author);
 1879:         my $home=homeserver($uname,$udom);
 1880:         unless ($home eq $perlvar{'lonHostID'}) {
 1881:            my @parts=split(/\//,$filename);
 1882:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1883:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1884:                &logthis("Malconfiguration for replication: $filename");
 1885: 	       return 'bad_request';
 1886:            }
 1887:            my $count;
 1888:            for ($count=5;$count<$#parts;$count++) {
 1889:                $path.="/$parts[$count]";
 1890:                if ((-e $path)!=1) {
 1891: 		   mkdir($path,0777);
 1892:                }
 1893:            }
 1894:            my $ua=new LWP::UserAgent;
 1895:            my $request=new HTTP::Request('GET',"$remoteurl");
 1896:            my $response=$ua->request($request,$transname);
 1897:            if ($response->is_error()) {
 1898: 	       unlink($transname);
 1899:                my $message=$response->status_line;
 1900:                &logthis("<font color=\"blue\">WARNING:"
 1901:                        ." LWP get: $message: $filename</font>");
 1902:                return 'unavailable';
 1903:            } else {
 1904: 	       if ($remoteurl!~/\.meta$/) {
 1905:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1906:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1907:                   if ($mresponse->is_error()) {
 1908: 		      unlink($filename.'.meta');
 1909:                       &logthis(
 1910:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1911:                   }
 1912: 	       }
 1913:                rename($transname,$filename);
 1914:                return 'ok';
 1915:            }
 1916:        }
 1917:     }
 1918: }
 1919: 
 1920: # ------------------------------------------------ Get server side include body
 1921: sub ssi_body {
 1922:     my ($filelink,%form)=@_;
 1923:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1924:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1925:     }
 1926:     my $output='';
 1927:     my $response;
 1928:     if ($filelink=~/^https?\:/) {
 1929:        ($output,$response)=&externalssi($filelink);
 1930:     } else {
 1931:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 1932:        $filelink .= 'inhibitmenu=yes';
 1933:        ($output,$response)=&ssi($filelink,%form);
 1934:     }
 1935:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1936:     $output=~s/^.*?\<body[^\>]*\>//si;
 1937:     $output=~s/\<\/body\s*\>.*?$//si;
 1938:     if (wantarray) {
 1939:         return ($output, $response);
 1940:     } else {
 1941:         return $output;
 1942:     }
 1943: }
 1944: 
 1945: # --------------------------------------------------------- Server Side Include
 1946: 
 1947: sub absolute_url {
 1948:     my ($host_name) = @_;
 1949:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1950:     if ($host_name eq '') {
 1951: 	$host_name = $ENV{'SERVER_NAME'};
 1952:     }
 1953:     return $protocol.$host_name;
 1954: }
 1955: 
 1956: #
 1957: #   Server side include.
 1958: # Parameters:
 1959: #  fn     Possibly encrypted resource name/id.
 1960: #  form   Hash that describes how the rendering should be done
 1961: #         and other things.
 1962: # Returns:
 1963: #   Scalar context: The content of the response.
 1964: #   Array context:  2 element list of the content and the full response object.
 1965: #     
 1966: sub ssi {
 1967: 
 1968:     my ($fn,%form)=@_;
 1969:     my $ua=new LWP::UserAgent;
 1970:     my $request;
 1971: 
 1972:     $form{'no_update_last_known'}=1;
 1973:     &Apache::lonenc::check_encrypt(\$fn);
 1974:     if (%form) {
 1975:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1976:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 1977:     } else {
 1978:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1979:     }
 1980: 
 1981:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1982:     my $response=$ua->request($request);
 1983: 
 1984:     if (wantarray) {
 1985: 	return ($response->content, $response);
 1986:     } else {
 1987: 	return $response->content;
 1988:     }
 1989: }
 1990: 
 1991: sub externalssi {
 1992:     my ($url)=@_;
 1993:     my $ua=new LWP::UserAgent;
 1994:     my $request=new HTTP::Request('GET',$url);
 1995:     my $response=$ua->request($request);
 1996:     if (wantarray) {
 1997:         return ($response->content, $response);
 1998:     } else {
 1999:         return $response->content;
 2000:     }
 2001: }
 2002: 
 2003: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2004: 
 2005: sub allowuploaded {
 2006:     my ($srcurl,$url)=@_;
 2007:     $url=&clutter(&declutter($url));
 2008:     my $dir=$url;
 2009:     $dir=~s/\/[^\/]+$//;
 2010:     my %httpref=();
 2011:     my $httpurl=&hreflocation('',$url);
 2012:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2013:     &Apache::lonnet::appenv(\%httpref);
 2014: }
 2015: 
 2016: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2017: # input: action, courseID, current domain, intended
 2018: #        path to file, source of file, instruction to parse file for objects,
 2019: #        ref to hash for embedded objects,
 2020: #        ref to hash for codebase of java objects.
 2021: #
 2022: # output: url to file (if action was uploaddoc), 
 2023: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2024: #
 2025: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2026: # course.
 2027: #
 2028: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2029: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2030: #          course's home server.
 2031: #
 2032: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2033: #          be copied from $source (current location) to 
 2034: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2035: #         and will then be copied to
 2036: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2037: #         course's home server.
 2038: #
 2039: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2040: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2041: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2042: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2043: #         in course's home server.
 2044: #
 2045: 
 2046: sub process_coursefile {
 2047:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 2048:     my $fetchresult;
 2049:     my $home=&homeserver($docuname,$docudom);
 2050:     if ($action eq 'propagate') {
 2051:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2052: 			     $home);
 2053:     } else {
 2054:         my $fpath = '';
 2055:         my $fname = $file;
 2056:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2057:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2058:         my $filepath = &build_filepath($fpath);
 2059:         if ($action eq 'copy') {
 2060:             if ($source eq '') {
 2061:                 $fetchresult = 'no source file';
 2062:                 return $fetchresult;
 2063:             } else {
 2064:                 my $destination = $filepath.'/'.$fname;
 2065:                 rename($source,$destination);
 2066:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2067:                                  $home);
 2068:             }
 2069:         } elsif ($action eq 'uploaddoc') {
 2070:             open(my $fh,'>'.$filepath.'/'.$fname);
 2071:             print $fh $env{'form.'.$source};
 2072:             close($fh);
 2073:             if ($parser eq 'parse') {
 2074:                 my $mm = new File::MMagic;
 2075:                 my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
 2076:                 if ($mime_type eq 'text/html') {
 2077:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2078:                     unless ($parse_result eq 'ok') {
 2079:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2080:                     }
 2081:                 }
 2082:             }
 2083:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2084:                                  $home);
 2085:             if ($fetchresult eq 'ok') {
 2086:                 return '/uploaded/'.$fpath.'/'.$fname;
 2087:             } else {
 2088:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2089:                         ' to host '.$home.': '.$fetchresult);
 2090:                 return '/adm/notfound.html';
 2091:             }
 2092:         }
 2093:     }
 2094:     unless ( $fetchresult eq 'ok') {
 2095:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2096:              ' to host '.$home.': '.$fetchresult);
 2097:     }
 2098:     return $fetchresult;
 2099: }
 2100: 
 2101: sub build_filepath {
 2102:     my ($fpath) = @_;
 2103:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2104:     unless ($fpath eq '') {
 2105:         my @parts=split('/',$fpath);
 2106:         foreach my $part (@parts) {
 2107:             $filepath.= '/'.$part;
 2108:             if ((-e $filepath)!=1) {
 2109:                 mkdir($filepath,0777);
 2110:             }
 2111:         }
 2112:     }
 2113:     return $filepath;
 2114: }
 2115: 
 2116: sub store_edited_file {
 2117:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2118:     my $file = $primary_url;
 2119:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2120:     my $fpath = '';
 2121:     my $fname = $file;
 2122:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2123:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2124:     my $filepath = &build_filepath($fpath);
 2125:     open(my $fh,'>'.$filepath.'/'.$fname);
 2126:     print $fh $content;
 2127:     close($fh);
 2128:     my $home=&homeserver($docuname,$docudom);
 2129:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2130: 			  $home);
 2131:     if ($$fetchresult eq 'ok') {
 2132:         return '/uploaded/'.$fpath.'/'.$fname;
 2133:     } else {
 2134:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2135: 		 ' to host '.$home.': '.$$fetchresult);
 2136:         return '/adm/notfound.html';
 2137:     }
 2138: }
 2139: 
 2140: sub clean_filename {
 2141:     my ($fname,$args)=@_;
 2142: # Replace Windows backslashes by forward slashes
 2143:     $fname=~s/\\/\//g;
 2144:     if (!$args->{'keep_path'}) {
 2145:         # Get rid of everything but the actual filename
 2146: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2147:     }
 2148: # Replace spaces by underscores
 2149:     $fname=~s/\s+/\_/g;
 2150: # Replace all other weird characters by nothing
 2151:     $fname=~s{[^/\w\.\-]}{}g;
 2152: # Replace all .\d. sequences with _\d. so they no longer look like version
 2153: # numbers
 2154:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2155:     return $fname;
 2156: }
 2157: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 2158: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 2159: # image with the same aspect ratio as the original, but with dimensions which do 
 2160: # not exceed $resizewidth and $resizeheight.
 2161:  
 2162: sub resizeImage {
 2163:     my ($img_path,$resizewidth,$resizeheight) = @_;
 2164:     my $ima = Image::Magick->new;
 2165:     my $resized;
 2166:     if (-e $img_path) {
 2167:         $ima->Read($img_path);
 2168:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 2169:             my $width = $ima->Get('width');
 2170:             my $height = $ima->Get('height');
 2171:             if ($width > $resizewidth) {
 2172: 	        my $factor = $width/$resizewidth;
 2173:                 my $newheight = $height/$factor;
 2174:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 2175:                 $resized = 1;
 2176:             }
 2177:         }
 2178:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 2179:             my $width = $ima->Get('width');
 2180:             my $height = $ima->Get('height');
 2181:             if ($height > $resizeheight) {
 2182:                 my $factor = $height/$resizeheight;
 2183:                 my $newwidth = $width/$factor;
 2184:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 2185:                 $resized = 1;
 2186:             }
 2187:         }
 2188:         if ($resized) {
 2189:             $ima->Write($img_path);
 2190:         }
 2191:     }
 2192:     return;
 2193: }
 2194: 
 2195: # --------------- Take an uploaded file and put it into the userfiles directory
 2196: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2197: #                    the desired filenam is in $env{"form.$formname.filename"}
 2198: #        $coursedoc - if true up to the current course
 2199: #                     if false
 2200: #        $subdir - directory in userfile to store the file into
 2201: #        $parser - instruction to parse file for objects ($parser = parse)    
 2202: #        $allfiles - reference to hash for embedded objects
 2203: #        $codebase - reference to hash for codebase of java objects
 2204: #        $desuname - username for permanent storage of uploaded file
 2205: #        $dsetudom - domain for permanaent storage of uploaded file
 2206: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2207: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2208: #        $resizewidth - width (pixels) to which to resize uploaded image
 2209: #        $resizeheight - height (pixels) to which to resize uploaded image
 2210: # 
 2211: # output: url of file in userspace, or error: <message> 
 2212: #             or /adm/notfound.html if failure to upload occurse
 2213: 
 2214: sub userfileupload {
 2215:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 2216:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight)=@_;
 2217:     if (!defined($subdir)) { $subdir='unknown'; }
 2218:     my $fname=$env{'form.'.$formname.'.filename'};
 2219:     $fname=&clean_filename($fname);
 2220: # See if there is anything left
 2221:     unless ($fname) { return 'error: no uploaded file'; }
 2222:     chop($env{'form.'.$formname});
 2223:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 2224:         my $now = time;
 2225:         my $filepath = 'tmp/helprequests/'.$now;
 2226:         my @parts=split(/\//,$filepath);
 2227:         my $fullpath = $perlvar{'lonDaemons'};
 2228:         for (my $i=0;$i<@parts;$i++) {
 2229:             $fullpath .= '/'.$parts[$i];
 2230:             if ((-e $fullpath)!=1) {
 2231:                 mkdir($fullpath,0777);
 2232:             }
 2233:         }
 2234:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2235:         print $fh $env{'form.'.$formname};
 2236:         close($fh);
 2237:         return $fullpath.'/'.$fname;
 2238:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 2239:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2240:                        '_'.$env{'user.domain'}.'/pending';
 2241:         my @parts=split(/\//,$filepath);
 2242:         my $fullpath = $perlvar{'lonDaemons'};
 2243:         for (my $i=0;$i<@parts;$i++) {
 2244:             $fullpath .= '/'.$parts[$i];
 2245:             if ((-e $fullpath)!=1) {
 2246:                 mkdir($fullpath,0777);
 2247:             }
 2248:         }
 2249:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2250:         print $fh $env{'form.'.$formname};
 2251:         close($fh);
 2252:         return $fullpath.'/'.$fname;
 2253:     }
 2254:     if ($subdir eq 'scantron') {
 2255:         $fname = 'scantron_orig_'.$fname;
 2256:     } else {   
 2257: # Create the directory if not present
 2258:         $fname="$subdir/$fname";
 2259:     }
 2260:     if ($coursedoc) {
 2261: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2262: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2263:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2264:             return &finishuserfileupload($docuname,$docudom,
 2265: 					 $formname,$fname,$parser,$allfiles,
 2266: 					 $codebase,$thumbwidth,$thumbheight,
 2267:                                          $resizewidth,$resizeheight);
 2268:         } else {
 2269:             $fname=$env{'form.folder'}.'/'.$fname;
 2270:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2271: 				       $fname,$formname,$parser,
 2272: 				       $allfiles,$codebase);
 2273:         }
 2274:     } elsif (defined($destuname)) {
 2275:         my $docuname=$destuname;
 2276:         my $docudom=$destudom;
 2277: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2278: 				     $parser,$allfiles,$codebase,
 2279:                                      $thumbwidth,$thumbheight,
 2280:                                      $resizewidth,$resizeheight);
 2281:         
 2282:     } else {
 2283:         my $docuname=$env{'user.name'};
 2284:         my $docudom=$env{'user.domain'};
 2285:         if (exists($env{'form.group'})) {
 2286:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2287:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2288:         }
 2289: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2290: 				     $parser,$allfiles,$codebase,
 2291:                                      $thumbwidth,$thumbheight,
 2292:                                      $resizewidth,$resizeheight);
 2293:     }
 2294: }
 2295: 
 2296: sub finishuserfileupload {
 2297:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2298:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight) = @_;
 2299:     my $path=$docudom.'/'.$docuname.'/';
 2300:     my $filepath=$perlvar{'lonDocRoot'};
 2301:   
 2302:     my ($fnamepath,$file,$fetchthumb);
 2303:     $file=$fname;
 2304:     if ($fname=~m|/|) {
 2305:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2306: 	$path.=$fnamepath.'/';
 2307:     }
 2308:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2309:     my $count;
 2310:     for ($count=4;$count<=$#parts;$count++) {
 2311:         $filepath.="/$parts[$count]";
 2312:         if ((-e $filepath)!=1) {
 2313: 	    mkdir($filepath,0777);
 2314:         }
 2315:     }
 2316: 
 2317: # Save the file
 2318:     {
 2319: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2320: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2321: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2322: 	    return '/adm/notfound.html';
 2323: 	}
 2324: 	if (!print FH ($env{'form.'.$formname})) {
 2325: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2326: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2327: 	    return '/adm/notfound.html';
 2328: 	}
 2329: 	close(FH);
 2330:         if ($resizewidth && $resizeheight) {
 2331:             my $mm = new File::MMagic;
 2332:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 2333:             if ($mime_type =~ m{^image/}) {
 2334: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 2335:             }  
 2336: 	}
 2337:     }
 2338:     if ($parser eq 'parse') {
 2339:         my $mm = new File::MMagic;
 2340:         my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 2341:         if ($mime_type eq 'text/html') {
 2342:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 2343:                                                        $allfiles,$codebase);
 2344:             unless ($parse_result eq 'ok') {
 2345:                 &logthis('Failed to parse '.$filepath.$file.
 2346: 	   	         ' for embedded media: '.$parse_result); 
 2347:             }
 2348:         }
 2349:     }
 2350:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2351:         my $input = $filepath.'/'.$file;
 2352:         my $output = $filepath.'/'.'tn-'.$file;
 2353:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2354:         system("convert -sample $thumbsize $input $output");
 2355:         if (-e $filepath.'/'.'tn-'.$file) {
 2356:             $fetchthumb  = 1; 
 2357:         }
 2358:     }
 2359:  
 2360: # Notify homeserver to grep it
 2361: #
 2362:     my $docuhome=&homeserver($docuname,$docudom);	
 2363:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2364:     if ($fetchresult eq 'ok') {
 2365:         if ($fetchthumb) {
 2366:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2367:             if ($thumbresult ne 'ok') {
 2368:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2369:                          $docuhome.': '.$thumbresult);
 2370:             }
 2371:         }
 2372: #
 2373: # Return the URL to it
 2374:         return '/uploaded/'.$path.$file;
 2375:     } else {
 2376:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2377: 		 ': '.$fetchresult);
 2378:         return '/adm/notfound.html';
 2379:     }
 2380: }
 2381: 
 2382: sub extract_embedded_items {
 2383:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 2384:     my @state = ();
 2385:     my %javafiles = (
 2386:                       codebase => '',
 2387:                       code => '',
 2388:                       archive => ''
 2389:                     );
 2390:     my %mediafiles = (
 2391:                       src => '',
 2392:                       movie => '',
 2393:                      );
 2394:     my $p;
 2395:     if ($content) {
 2396:         $p = HTML::LCParser->new($content);
 2397:     } else {
 2398:         $p = HTML::LCParser->new($fullpath);
 2399:     }
 2400:     while (my $t=$p->get_token()) {
 2401: 	if ($t->[0] eq 'S') {
 2402: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2403: 	    push(@state, $tagname);
 2404:             if (lc($tagname) eq 'allow') {
 2405:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2406:             }
 2407: 	    if (lc($tagname) eq 'img') {
 2408: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2409: 	    }
 2410: 	    if (lc($tagname) eq 'a') {
 2411: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2412: 	    }
 2413:             if (lc($tagname) eq 'script') {
 2414:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2415:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2416:                 } else {
 2417:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2418:                 }
 2419:             }
 2420:             if (lc($tagname) eq 'link') {
 2421:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2422:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2423:                 }
 2424:             }
 2425: 	    if (lc($tagname) eq 'object' ||
 2426: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2427: 		foreach my $item (keys(%javafiles)) {
 2428: 		    $javafiles{$item} = '';
 2429: 		}
 2430: 	    }
 2431: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2432: 		my $name = lc($attr->{'name'});
 2433: 		foreach my $item (keys(%javafiles)) {
 2434: 		    if ($name eq $item) {
 2435: 			$javafiles{$item} = $attr->{'value'};
 2436: 			last;
 2437: 		    }
 2438: 		}
 2439: 		foreach my $item (keys(%mediafiles)) {
 2440: 		    if ($name eq $item) {
 2441: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2442: 			last;
 2443: 		    }
 2444: 		}
 2445: 	    }
 2446: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2447: 		foreach my $item (keys(%javafiles)) {
 2448: 		    if ($attr->{$item}) {
 2449: 			$javafiles{$item} = $attr->{$item};
 2450: 			last;
 2451: 		    }
 2452: 		}
 2453: 		foreach my $item (keys(%mediafiles)) {
 2454: 		    if ($attr->{$item}) {
 2455: 			&add_filetype($allfiles,$attr->{$item},$item);
 2456: 			last;
 2457: 		    }
 2458: 		}
 2459: 	    }
 2460: 	} elsif ($t->[0] eq 'E') {
 2461: 	    my ($tagname) = ($t->[1]);
 2462: 	    if ($javafiles{'codebase'} ne '') {
 2463: 		$javafiles{'codebase'} .= '/';
 2464: 	    }  
 2465: 	    if (lc($tagname) eq 'applet' ||
 2466: 		lc($tagname) eq 'object' ||
 2467: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2468: 		) {
 2469: 		foreach my $item (keys(%javafiles)) {
 2470: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2471: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2472: 			&add_filetype($allfiles,$file,$item);
 2473: 		    }
 2474: 		}
 2475: 	    } 
 2476: 	    pop @state;
 2477: 	}
 2478:     }
 2479:     return 'ok';
 2480: }
 2481: 
 2482: sub add_filetype {
 2483:     my ($allfiles,$file,$type)=@_;
 2484:     if (exists($allfiles->{$file})) {
 2485: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2486: 	    push(@{$allfiles->{$file}}, &escape($type));
 2487: 	}
 2488:     } else {
 2489: 	@{$allfiles->{$file}} = (&escape($type));
 2490:     }
 2491: }
 2492: 
 2493: sub removeuploadedurl {
 2494:     my ($url)=@_;	
 2495:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 2496:     return &removeuserfile($uname,$udom,$fname);
 2497: }
 2498: 
 2499: sub removeuserfile {
 2500:     my ($docuname,$docudom,$fname)=@_;
 2501:     my $home=&homeserver($docuname,$docudom);    
 2502:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2503:     if ($result eq 'ok') {	
 2504:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2505:             my $metafile = $fname.'.meta';
 2506:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2507: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2508:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 2509:             my $sqlresult = 
 2510:                 &update_portfolio_table($docuname,$docudom,$file,
 2511:                                         'portfolio_metadata',$group,
 2512:                                         'delete');
 2513:         }
 2514:     }
 2515:     return $result;
 2516: }
 2517: 
 2518: sub mkdiruserfile {
 2519:     my ($docuname,$docudom,$dir)=@_;
 2520:     my $home=&homeserver($docuname,$docudom);
 2521:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2522: }
 2523: 
 2524: sub renameuserfile {
 2525:     my ($docuname,$docudom,$old,$new)=@_;
 2526:     my $home=&homeserver($docuname,$docudom);
 2527:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2528:                         &escape("$old").':'.&escape("$new"),$home);
 2529:     if ($result eq 'ok') {
 2530:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2531:             my $oldmeta = $old.'.meta';
 2532:             my $newmeta = $new.'.meta';
 2533:             my $metaresult = 
 2534:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2535: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2536:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2537:             my $sqlresult = 
 2538:                 &update_portfolio_table($docuname,$docudom,$file,
 2539:                                         'portfolio_metadata',$group,
 2540:                                         'delete');
 2541:         }
 2542:     }
 2543:     return $result;
 2544: }
 2545: 
 2546: # ------------------------------------------------------------------------- Log
 2547: 
 2548: sub log {
 2549:     my ($dom,$nam,$hom,$what)=@_;
 2550:     return critical("log:$dom:$nam:$what",$hom);
 2551: }
 2552: 
 2553: # ------------------------------------------------------------------ Course Log
 2554: #
 2555: # This routine flushes several buffers of non-mission-critical nature
 2556: #
 2557: 
 2558: sub flushcourselogs {
 2559:     &logthis('Flushing log buffers');
 2560: #
 2561: # course logs
 2562: # This is a log of all transactions in a course, which can be used
 2563: # for data mining purposes
 2564: #
 2565: # It also collects the courseid database, which lists last transaction
 2566: # times and course titles for all courseids
 2567: #
 2568:     my %courseidbuffer=();
 2569:     foreach my $crsid (keys(%courselogs)) {
 2570:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2571: 		          &escape($courselogs{$crsid}),
 2572: 		          $coursehombuf{$crsid}) eq 'ok') {
 2573: 	    delete $courselogs{$crsid};
 2574:         } else {
 2575:             &logthis('Failed to flush log buffer for '.$crsid);
 2576:             if (length($courselogs{$crsid})>40000) {
 2577:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2578:                         " exceeded maximum size, deleting.</font>");
 2579:                delete $courselogs{$crsid};
 2580:             }
 2581:         }
 2582:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2583:             'description' => $coursedescrbuf{$crsid},
 2584:             'inst_code'    => $courseinstcodebuf{$crsid},
 2585:             'type'        => $coursetypebuf{$crsid},
 2586:             'owner'       => $courseownerbuf{$crsid},
 2587:         };
 2588:     }
 2589: #
 2590: # Write course id database (reverse lookup) to homeserver of courses 
 2591: # Is used in pickcourse
 2592: #
 2593:     foreach my $crs_home (keys(%courseidbuffer)) {
 2594:         my $response = &courseidput(&host_domain($crs_home),
 2595:                                     $courseidbuffer{$crs_home},
 2596:                                     $crs_home,'timeonly');
 2597:     }
 2598: #
 2599: # File accesses
 2600: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2601: #
 2602:     foreach my $entry (keys(%accesshash)) {
 2603:         if ($entry =~ /___count$/) {
 2604:             my ($dom,$name);
 2605:             ($dom,$name,undef)=
 2606: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2607:             if (! defined($dom) || $dom eq '' || 
 2608:                 ! defined($name) || $name eq '') {
 2609:                 my $cid = $env{'request.course.id'};
 2610:                 $dom  = $env{'request.'.$cid.'.domain'};
 2611:                 $name = $env{'request.'.$cid.'.num'};
 2612:             }
 2613:             my $value = $accesshash{$entry};
 2614:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2615:             my %temphash=($url => $value);
 2616:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2617:             if ($result eq 'ok') {
 2618:                 delete $accesshash{$entry};
 2619:             } elsif ($result eq 'unknown_cmd') {
 2620:                 # Target server has old code running on it.
 2621:                 my %temphash=($entry => $value);
 2622:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2623:                     delete $accesshash{$entry};
 2624:                 }
 2625:             }
 2626:         } else {
 2627:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2628:             my %temphash=($entry => $accesshash{$entry});
 2629:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2630:                 delete $accesshash{$entry};
 2631:             }
 2632:         }
 2633:     }
 2634: #
 2635: # Roles
 2636: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2637: #
 2638:     foreach my $entry (keys(%userrolehash)) {
 2639:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2640: 	    split(/\:/,$entry);
 2641:         if (&Apache::lonnet::put('nohist_userroles',
 2642:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2643:                 $rudom,$runame) eq 'ok') {
 2644: 	    delete $userrolehash{$entry};
 2645:         }
 2646:     }
 2647: #
 2648: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2649: #
 2650:     my %domrolebuffer = ();
 2651:     foreach my $entry (keys(%domainrolehash)) {
 2652:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2653:         if ($domrolebuffer{$rudom}) {
 2654:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2655:                       '='.&escape($domainrolehash{$entry});
 2656:         } else {
 2657:             $domrolebuffer{$rudom}.=&escape($entry).
 2658:                       '='.&escape($domainrolehash{$entry});
 2659:         }
 2660:         delete $domainrolehash{$entry};
 2661:     }
 2662:     foreach my $dom (keys(%domrolebuffer)) {
 2663: 	my %servers = &get_servers($dom,'library');
 2664: 	foreach my $tryserver (keys(%servers)) {
 2665: 	    unless (&reply('domroleput:'.$dom.':'.
 2666: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2667: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2668: 	    }
 2669:         }
 2670:     }
 2671:     $dumpcount++;
 2672: }
 2673: 
 2674: sub courselog {
 2675:     my $what=shift;
 2676:     $what=time.':'.$what;
 2677:     unless ($env{'request.course.id'}) { return ''; }
 2678:     $coursedombuf{$env{'request.course.id'}}=
 2679:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2680:     $coursenumbuf{$env{'request.course.id'}}=
 2681:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2682:     $coursehombuf{$env{'request.course.id'}}=
 2683:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2684:     $coursedescrbuf{$env{'request.course.id'}}=
 2685:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2686:     $courseinstcodebuf{$env{'request.course.id'}}=
 2687:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2688:     $courseownerbuf{$env{'request.course.id'}}=
 2689:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2690:     $coursetypebuf{$env{'request.course.id'}}=
 2691:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2692:     if (defined $courselogs{$env{'request.course.id'}}) {
 2693: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2694:     } else {
 2695: 	$courselogs{$env{'request.course.id'}}.=$what;
 2696:     }
 2697:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2698: 	&flushcourselogs();
 2699:     }
 2700: }
 2701: 
 2702: sub courseacclog {
 2703:     my $fnsymb=shift;
 2704:     unless ($env{'request.course.id'}) { return ''; }
 2705:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2706:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2707:         $what.=':POST';
 2708:         # FIXME: Probably ought to escape things....
 2709: 	foreach my $key (keys(%env)) {
 2710:             if ($key=~/^form\.(.*)/) {
 2711:                 my $formitem = $1;
 2712:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 2713:                     $what.=':'.$formitem.'='.$env{$key};
 2714:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 2715:                     $what.=':'.$formitem.'='.$env{$key};
 2716:                 }
 2717:             }
 2718:         }
 2719:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2720:         # FIXME: We should not be depending on a form parameter that someone
 2721:         # editing lonsearchcat.pm might change in the future.
 2722:         if ($env{'form.phase'} eq 'course_search') {
 2723:             $what.= ':POST';
 2724:             # FIXME: Probably ought to escape things....
 2725:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2726:                                  'crsdiscuss') {
 2727:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2728:             }
 2729:         }
 2730:     }
 2731:     &courselog($what);
 2732: }
 2733: 
 2734: sub countacc {
 2735:     my $url=&declutter(shift);
 2736:     return if (! defined($url) || $url eq '');
 2737:     unless ($env{'request.course.id'}) { return ''; }
 2738:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2739:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2740:     $accesshash{$key}++;
 2741: }
 2742: 
 2743: sub linklog {
 2744:     my ($from,$to)=@_;
 2745:     $from=&declutter($from);
 2746:     $to=&declutter($to);
 2747:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2748:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2749: }
 2750:   
 2751: sub userrolelog {
 2752:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2753:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2754:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2755:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2756:         ($trole=~/^ta/) || ($trole=~/^co/)) {
 2757:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2758:        $userrolehash
 2759:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2760:                     =$tend.':'.$tstart;
 2761:     }
 2762:     if (($env{'request.role'} =~ /dc\./) &&
 2763: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2764: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2765: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
 2766:          ($trole=~/^co/))) {
 2767:        $userrolehash
 2768:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2769:                     =$tend.':'.$tstart;
 2770:     }
 2771:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2772:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2773:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2774:         ($trole=~/^sc/)) {
 2775:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2776:        $domainrolehash
 2777:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2778:                     = $tend.':'.$tstart;
 2779:     }
 2780: }
 2781: 
 2782: sub courserolelog {
 2783:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 2784:     if (($trole eq 'cc') || ($trole eq 'in') ||
 2785:         ($trole eq 'ep') || ($trole eq 'ad') ||
 2786:         ($trole eq 'ta') || ($trole eq 'st') ||
 2787:         ($trole=~/^cr/) || ($trole eq 'gr') ||
 2788:         ($trole eq 'co')) {
 2789:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 2790:             my $cdom = $1;
 2791:             my $cnum = $2;
 2792:             my $sec = $3;
 2793:             my $namespace = 'rolelog';
 2794:             my %storehash = (
 2795:                                role    => $trole,
 2796:                                start   => $tstart,
 2797:                                end     => $tend,
 2798:                                selfenroll => $selfenroll,
 2799:                                context    => $context,
 2800:                             );
 2801:             if ($trole eq 'gr') {
 2802:                 $namespace = 'groupslog';
 2803:                 $storehash{'group'} = $sec;
 2804:             } else {
 2805:                 $storehash{'section'} = $sec;
 2806:             }
 2807:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 2808:             if (($trole ne 'st') || ($sec ne '')) {
 2809:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 2810:             }
 2811:         }
 2812:     }
 2813:     return;
 2814: }
 2815: 
 2816: sub get_course_adv_roles {
 2817:     my ($cid,$codes) = @_;
 2818:     $cid=$env{'request.course.id'} unless (defined($cid));
 2819:     my %coursehash=&coursedescription($cid);
 2820:     my $crstype = &Apache::loncommon::course_type($cid);
 2821:     my %nothide=();
 2822:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2823:         if ($user !~ /:/) {
 2824: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2825:         } else {
 2826:             $nothide{$user}=1;
 2827:         }
 2828:     }
 2829:     my %returnhash=();
 2830:     my %dumphash=
 2831:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2832:     my $now=time;
 2833:     my %privileged;
 2834:     foreach my $entry (keys(%dumphash)) {
 2835: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2836:         if (($tstart) && ($tstart<0)) { next; }
 2837:         if (($tend) && ($tend<$now)) { next; }
 2838:         if (($tstart) && ($now<$tstart)) { next; }
 2839:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2840: 	if ($username eq '' || $domain eq '') { next; }
 2841:         unless (ref($privileged{$domain}) eq 'HASH') {
 2842:             my %dompersonnel =
 2843:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 2844:             $privileged{$domain} = {};
 2845:             foreach my $server (keys(%dompersonnel)) {
 2846:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 2847:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 2848:                         my ($trole,$uname,$udom) = split(/:/,$user);
 2849:                         $privileged{$udom}{$uname} = 1;
 2850:                     }
 2851:                 }
 2852:             }
 2853:         }
 2854:         if ((exists($privileged{$domain}{$username})) && 
 2855:             (!$nothide{$username.':'.$domain})) { next; }
 2856: 	if ($role eq 'cr') { next; }
 2857:         if ($codes) {
 2858:             if ($section) { $role .= ':'.$section; }
 2859:             if ($returnhash{$role}) {
 2860:                 $returnhash{$role}.=','.$username.':'.$domain;
 2861:             } else {
 2862:                 $returnhash{$role}=$username.':'.$domain;
 2863:             }
 2864:         } else {
 2865:             my $key=&plaintext($role,$crstype);
 2866:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 2867:             if ($returnhash{$key}) {
 2868: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2869:             } else {
 2870:                 $returnhash{$key}=$username.':'.$domain;
 2871:             }
 2872:         }
 2873:     }
 2874:     return %returnhash;
 2875: }
 2876: 
 2877: sub get_my_roles {
 2878:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2879:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2880:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2881:     my (%dumphash,%nothide);
 2882:     if ($context eq 'userroles') { 
 2883:         %dumphash = &dump('roles',$udom,$uname);
 2884:     } else {
 2885:         %dumphash=
 2886:             &dump('nohist_userroles',$udom,$uname);
 2887:         if ($hidepriv) {
 2888:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2889:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2890:                 if ($user !~ /:/) {
 2891:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2892:                 } else {
 2893:                     $nothide{$user} = 1;
 2894:                 }
 2895:             }
 2896:         }
 2897:     }
 2898:     my %returnhash=();
 2899:     my $now=time;
 2900:     my %privileged;
 2901:     foreach my $entry (keys(%dumphash)) {
 2902:         my ($role,$tend,$tstart);
 2903:         if ($context eq 'userroles') {
 2904: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2905:         } else {
 2906:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2907:         }
 2908:         if (($tstart) && ($tstart<0)) { next; }
 2909:         my $status = 'active';
 2910:         if (($tend) && ($tend<=$now)) {
 2911:             $status = 'previous';
 2912:         } 
 2913:         if (($tstart) && ($now<$tstart)) {
 2914:             $status = 'future';
 2915:         }
 2916:         if (ref($types) eq 'ARRAY') {
 2917:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2918:                 next;
 2919:             } 
 2920:         } else {
 2921:             if ($status ne 'active') {
 2922:                 next;
 2923:             }
 2924:         }
 2925:         my ($rolecode,$username,$domain,$section,$area);
 2926:         if ($context eq 'userroles') {
 2927:             ($area,$rolecode) = split(/_/,$entry);
 2928:             (undef,$domain,$username,$section) = split(/\//,$area);
 2929:         } else {
 2930:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2931:         }
 2932:         if (ref($roledoms) eq 'ARRAY') {
 2933:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2934:                 next;
 2935:             }
 2936:         }
 2937:         if (ref($roles) eq 'ARRAY') {
 2938:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2939:                 if ($role =~ /^cr\//) {
 2940:                     if (!grep(/^cr$/,@{$roles})) {
 2941:                         next;
 2942:                     }
 2943:                 } else {
 2944:                     next;
 2945:                 }
 2946:             }
 2947:         }
 2948:         if ($hidepriv) {
 2949:             if ($context eq 'userroles') {
 2950:                 if ((&privileged($username,$domain)) &&
 2951:                     (!$nothide{$username.':'.$domain})) {
 2952:                     next;
 2953:                 }
 2954:             } else {
 2955:                 unless (ref($privileged{$domain}) eq 'HASH') {
 2956:                     my %dompersonnel =
 2957:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 2958:                     $privileged{$domain} = {};
 2959:                     if (keys(%dompersonnel)) {
 2960:                         foreach my $server (keys(%dompersonnel)) {
 2961:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 2962:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 2963:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 2964:                                     $privileged{$udom}{$uname} = $trole;
 2965:                                 }
 2966:                             }
 2967:                         }
 2968:                     }
 2969:                 }
 2970:                 if (exists($privileged{$domain}{$username})) {
 2971:                     if (!$nothide{$username.':'.$domain}) {
 2972:                         next;
 2973:                     }
 2974:                 }
 2975:             }
 2976:         }
 2977:         if ($withsec) {
 2978:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2979:                 $tstart.':'.$tend;
 2980:         } else {
 2981:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2982:         }
 2983:     }
 2984:     return %returnhash;
 2985: }
 2986: 
 2987: # ----------------------------------------------------- Frontpage Announcements
 2988: #
 2989: #
 2990: 
 2991: sub postannounce {
 2992:     my ($server,$text)=@_;
 2993:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2994:     unless ($text=~/\w/) { $text=''; }
 2995:     return &reply('setannounce:'.&escape($text),$server);
 2996: }
 2997: 
 2998: sub getannounce {
 2999: 
 3000:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 3001: 	my $announcement='';
 3002: 	while (my $line = <$fh>) { $announcement .= $line; }
 3003: 	close($fh);
 3004: 	if ($announcement=~/\w/) { 
 3005: 	    return 
 3006:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 3007:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 3008: 	} else {
 3009: 	    return '';
 3010: 	}
 3011:     } else {
 3012: 	return '';
 3013:     }
 3014: }
 3015: 
 3016: # ---------------------------------------------------------- Course ID routines
 3017: # Deal with domain's nohist_courseid.db files
 3018: #
 3019: 
 3020: sub courseidput {
 3021:     my ($domain,$storehash,$coursehome,$caller) = @_;
 3022:     return unless (ref($storehash) eq 'HASH');
 3023:     my $outcome;
 3024:     if ($caller eq 'timeonly') {
 3025:         my $cids = '';
 3026:         foreach my $item (keys(%$storehash)) {
 3027:             $cids.=&escape($item).'&';
 3028:         }
 3029:         $cids=~s/\&$//;
 3030:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 3031:                           $coursehome);       
 3032:     } else {
 3033:         my $items = '';
 3034:         foreach my $item (keys(%$storehash)) {
 3035:             $items.= &escape($item).'='.
 3036:                      &freeze_escape($$storehash{$item}).'&';
 3037:         }
 3038:         $items=~s/\&$//;
 3039:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 3040:                           $coursehome);
 3041:     }
 3042:     if ($outcome eq 'unknown_cmd') {
 3043:         my $what;
 3044:         foreach my $cid (keys(%$storehash)) {
 3045:             $what .= &escape($cid).'=';
 3046:             foreach my $item ('description','inst_code','owner','type') {
 3047:                 $what .= &escape($storehash->{$cid}{$item}).':';
 3048:             }
 3049:             $what =~ s/\:$/&/;
 3050:         }
 3051:         $what =~ s/\&$//;  
 3052:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 3053:     } else {
 3054:         return $outcome;
 3055:     }
 3056: }
 3057: 
 3058: sub courseiddump {
 3059:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 3060:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 3061:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 3062:         $cloneonly,$createdbefore,$createdafter,$creationcontext)=@_;
 3063:     my $as_hash = 1;
 3064:     my %returnhash;
 3065:     if (!$domfilter) { $domfilter=''; }
 3066:     my %libserv = &all_library();
 3067:     foreach my $tryserver (keys(%libserv)) {
 3068:         if ( (  $hostidflag == 1 
 3069: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 3070: 	     || (!defined($hostidflag)) ) {
 3071: 
 3072: 	    if (($domfilter eq '') ||
 3073: 		(&host_domain($tryserver) eq $domfilter)) {
 3074:                 my $rep = 
 3075:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 3076:                          $sincefilter.':'.&escape($descfilter).':'.
 3077:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 3078:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 3079:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 3080:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 3081:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
 3082:                          &escape($cc_clone).':'.$cloneonly.':'.
 3083:                          &escape($createdbefore).':'.&escape($createdafter).':'.
 3084:                          &escape($creationcontext),$tryserver);
 3085:                 my @pairs=split(/\&/,$rep);
 3086:                 foreach my $item (@pairs) {
 3087:                     my ($key,$value)=split(/\=/,$item,2);
 3088:                     $key = &unescape($key);
 3089:                     next if ($key =~ /^error: 2 /);
 3090:                     my $result = &thaw_unescape($value);
 3091:                     if (ref($result) eq 'HASH') {
 3092:                         $returnhash{$key}=$result;
 3093:                     } else {
 3094:                         my @responses = split(/:/,$value);
 3095:                         my @items = ('description','inst_code','owner','type');
 3096:                         for (my $i=0; $i<@responses; $i++) {
 3097:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 3098:                         }
 3099:                     }
 3100:                 }
 3101:             }
 3102:         }
 3103:     }
 3104:     return %returnhash;
 3105: }
 3106: 
 3107: sub courselastaccess {
 3108:     my ($cdom,$cnum,$hostidref) = @_;
 3109:     my %returnhash;
 3110:     if ($cdom && $cnum) {
 3111:         my $chome = &homeserver($cnum,$cdom);
 3112:         if ($chome ne 'no_host') {
 3113:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 3114:             &extract_lastaccess(\%returnhash,$rep);
 3115:         }
 3116:     } else {
 3117:         if (!$cdom) { $cdom=''; }
 3118:         my %libserv = &all_library();
 3119:         foreach my $tryserver (keys(%libserv)) {
 3120:             if (ref($hostidref) eq 'ARRAY') {
 3121:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 3122:             } 
 3123:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 3124:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 3125:                 &extract_lastaccess(\%returnhash,$rep);
 3126:             }
 3127:         }
 3128:     }
 3129:     return %returnhash;
 3130: }
 3131: 
 3132: sub extract_lastaccess {
 3133:     my ($returnhash,$rep) = @_;
 3134:     if (ref($returnhash) eq 'HASH') {
 3135:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 3136:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 3137:                  $rep eq '') {
 3138:             my @pairs=split(/\&/,$rep);
 3139:             foreach my $item (@pairs) {
 3140:                 my ($key,$value)=split(/\=/,$item,2);
 3141:                 $key = &unescape($key);
 3142:                 next if ($key =~ /^error: 2 /);
 3143:                 $returnhash->{$key} = &thaw_unescape($value);
 3144:             }
 3145:         }
 3146:     }
 3147:     return;
 3148: }
 3149: 
 3150: # ---------------------------------------------------------- DC e-mail
 3151: 
 3152: sub dcmailput {
 3153:     my ($domain,$msgid,$message,$server)=@_;
 3154:     my $status = &Apache::lonnet::critical(
 3155:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 3156:        &escape($message),$server);
 3157:     return $status;
 3158: }
 3159: 
 3160: sub dcmaildump {
 3161:     my ($dom,$startdate,$enddate,$senders) = @_;
 3162:     my %returnhash=();
 3163: 
 3164:     if (defined(&domain($dom,'primary'))) {
 3165:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 3166:                                                          &escape($enddate).':';
 3167: 	my @esc_senders=map { &escape($_)} @$senders;
 3168: 	$cmd.=&escape(join('&',@esc_senders));
 3169: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 3170:             my ($key,$value) = split(/\=/,$line,2);
 3171:             if (($key) && ($value)) {
 3172:                 $returnhash{&unescape($key)} = &unescape($value);
 3173:             }
 3174:         }
 3175:     }
 3176:     return %returnhash;
 3177: }
 3178: # ---------------------------------------------------------- Domain roles
 3179: 
 3180: sub get_domain_roles {
 3181:     my ($dom,$roles,$startdate,$enddate)=@_;
 3182:     if ((!defined($startdate)) || ($startdate eq '')) {
 3183:         $startdate = '.';
 3184:     }
 3185:     if ((!defined($enddate)) || ($enddate eq '')) {
 3186:         $enddate = '.';
 3187:     }
 3188:     my $rolelist;
 3189:     if (ref($roles) eq 'ARRAY') {
 3190:         $rolelist = join(':',@{$roles});
 3191:     }
 3192:     my %personnel = ();
 3193: 
 3194:     my %servers = &get_servers($dom,'library');
 3195:     foreach my $tryserver (keys(%servers)) {
 3196: 	%{$personnel{$tryserver}}=();
 3197: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 3198: 					    &escape($startdate).':'.
 3199: 					    &escape($enddate).':'.
 3200: 					    &escape($rolelist), $tryserver))) {
 3201: 	    my ($key,$value) = split(/\=/,$line,2);
 3202: 	    if (($key) && ($value)) {
 3203: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 3204: 	    }
 3205: 	}
 3206:     }
 3207:     return %personnel;
 3208: }
 3209: 
 3210: # ----------------------------------------------------------- Check out an item
 3211: 
 3212: sub get_first_access {
 3213:     my ($type,$argsymb)=@_;
 3214:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3215:     if ($argsymb) { $symb=$argsymb; }
 3216:     my ($map,$id,$res)=&decode_symb($symb);
 3217:     if ($type eq 'course') {
 3218: 	$res='course';
 3219:     } elsif ($type eq 'map') {
 3220: 	$res=&symbread($map);
 3221:     } else {
 3222: 	$res=$symb;
 3223:     }
 3224:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 3225:     return $times{"$courseid\0$res"};
 3226: }
 3227: 
 3228: sub set_first_access {
 3229:     my ($type)=@_;
 3230:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3231:     my ($map,$id,$res)=&decode_symb($symb);
 3232:     if ($type eq 'course') {
 3233: 	$res='course';
 3234:     } elsif ($type eq 'map') {
 3235: 	$res=&symbread($map);
 3236:     } else {
 3237: 	$res=$symb;
 3238:     }
 3239:     my $firstaccess=&get_first_access($type,$symb);
 3240:     if (!$firstaccess) {
 3241: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 3242:     }
 3243:     return 'already_set';
 3244: }
 3245: 
 3246: sub checkout {
 3247:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 3248:     my $now=time;
 3249:     my $lonhost=$perlvar{'lonHostID'};
 3250:     my $infostr=&escape(
 3251:                  'CHECKOUTTOKEN&'.
 3252:                  $tuname.'&'.
 3253:                  $tudom.'&'.
 3254:                  $tcrsid.'&'.
 3255:                  $symb.'&'.
 3256: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 3257:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 3258:     if ($token=~/^error\:/) { 
 3259:         &logthis("<font color=\"blue\">WARNING: ".
 3260:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 3261:                  "</font>");
 3262:         return ''; 
 3263:     }
 3264: 
 3265:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 3266:     $token=~tr/a-z/A-Z/;
 3267: 
 3268:     my %infohash=('resource.0.outtoken' => $token,
 3269:                   'resource.0.checkouttime' => $now,
 3270:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 3271: 
 3272:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3273:        return '';
 3274:     } else {
 3275:         &logthis("<font color=\"blue\">WARNING: ".
 3276:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 3277:                  "</font>");
 3278:     }    
 3279: 
 3280:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3281:                          &escape('Checkout '.$infostr.' - '.
 3282:                                                  $token)) ne 'ok') {
 3283: 	return '';
 3284:     } else {
 3285:         &logthis("<font color=\"blue\">WARNING: ".
 3286:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 3287:                  "</font>");
 3288:     }
 3289:     return $token;
 3290: }
 3291: 
 3292: # ------------------------------------------------------------ Check in an item
 3293: 
 3294: sub checkin {
 3295:     my $token=shift;
 3296:     my $now=time;
 3297:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 3298:     $lonhost=~tr/A-Z/a-z/;
 3299:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 3300:     $dtoken=~s/\W/\_/g;
 3301:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 3302:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 3303: 
 3304:     unless (($tuname) && ($tudom)) {
 3305:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 3306:         return '';
 3307:     }
 3308:     
 3309:     unless (&allowed('mgr',$tcrsid)) {
 3310:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 3311:                  $env{'user.name'}.' - '.$env{'user.domain'});
 3312:         return '';
 3313:     }
 3314: 
 3315:     my %infohash=('resource.0.intoken' => $token,
 3316:                   'resource.0.checkintime' => $now,
 3317:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 3318: 
 3319:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3320:        return '';
 3321:     }    
 3322: 
 3323:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3324:                          &escape('Checkin - '.$token)) ne 'ok') {
 3325: 	return '';
 3326:     }
 3327: 
 3328:     return ($symb,$tuname,$tudom,$tcrsid);    
 3329: }
 3330: 
 3331: # --------------------------------------------- Set Expire Date for Spreadsheet
 3332: 
 3333: sub expirespread {
 3334:     my ($uname,$udom,$stype,$usymb)=@_;
 3335:     my $cid=$env{'request.course.id'}; 
 3336:     if ($cid) {
 3337:        my $now=time;
 3338:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3339:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3340:                             $env{'course.'.$cid.'.num'}.
 3341: 	        	    ':nohist_expirationdates:'.
 3342:                             &escape($key).'='.$now,
 3343:                             $env{'course.'.$cid.'.home'})
 3344:     }
 3345:     return 'ok';
 3346: }
 3347: 
 3348: # ----------------------------------------------------- Devalidate Spreadsheets
 3349: 
 3350: sub devalidate {
 3351:     my ($symb,$uname,$udom)=@_;
 3352:     my $cid=$env{'request.course.id'}; 
 3353:     if ($cid) {
 3354:         # delete the stored spreadsheets for
 3355:         # - the student level sheet of this user in course's homespace
 3356:         # - the assessment level sheet for this resource 
 3357:         #   for this user in user's homespace
 3358: 	# - current conditional state info
 3359: 	my $key=$uname.':'.$udom.':';
 3360:         my $status=
 3361: 	    &del('nohist_calculatedsheets',
 3362: 		 [$key.'studentcalc:'],
 3363: 		 $env{'course.'.$cid.'.domain'},
 3364: 		 $env{'course.'.$cid.'.num'})
 3365: 		.' '.
 3366: 	    &del('nohist_calculatedsheets_'.$cid,
 3367: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3368:         unless ($status eq 'ok ok') {
 3369:            &logthis('Could not devalidate spreadsheet '.
 3370:                     $uname.' at '.$udom.' for '.
 3371: 		    $symb.': '.$status);
 3372:         }
 3373: 	&delenv('user.state.'.$cid);
 3374:     }
 3375: }
 3376: 
 3377: sub get_scalar {
 3378:     my ($string,$end) = @_;
 3379:     my $value;
 3380:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3381: 	$value = $1;
 3382:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3383: 	$value = $1;
 3384:     }
 3385:     return &unescape($value);
 3386: }
 3387: 
 3388: sub array2str {
 3389:   my (@array) = @_;
 3390:   my $result=&arrayref2str(\@array);
 3391:   $result=~s/^__ARRAY_REF__//;
 3392:   $result=~s/__END_ARRAY_REF__$//;
 3393:   return $result;
 3394: }
 3395: 
 3396: sub arrayref2str {
 3397:   my ($arrayref) = @_;
 3398:   my $result='__ARRAY_REF__';
 3399:   foreach my $elem (@$arrayref) {
 3400:     if(ref($elem) eq 'ARRAY') {
 3401:       $result.=&arrayref2str($elem).'&';
 3402:     } elsif(ref($elem) eq 'HASH') {
 3403:       $result.=&hashref2str($elem).'&';
 3404:     } elsif(ref($elem)) {
 3405:       #print("Got a ref of ".(ref($elem))." skipping.");
 3406:     } else {
 3407:       $result.=&escape($elem).'&';
 3408:     }
 3409:   }
 3410:   $result=~s/\&$//;
 3411:   $result .= '__END_ARRAY_REF__';
 3412:   return $result;
 3413: }
 3414: 
 3415: sub hash2str {
 3416:   my (%hash) = @_;
 3417:   my $result=&hashref2str(\%hash);
 3418:   $result=~s/^__HASH_REF__//;
 3419:   $result=~s/__END_HASH_REF__$//;
 3420:   return $result;
 3421: }
 3422: 
 3423: sub hashref2str {
 3424:   my ($hashref)=@_;
 3425:   my $result='__HASH_REF__';
 3426:   foreach my $key (sort(keys(%$hashref))) {
 3427:     if (ref($key) eq 'ARRAY') {
 3428:       $result.=&arrayref2str($key).'=';
 3429:     } elsif (ref($key) eq 'HASH') {
 3430:       $result.=&hashref2str($key).'=';
 3431:     } elsif (ref($key)) {
 3432:       $result.='=';
 3433:       #print("Got a ref of ".(ref($key))." skipping.");
 3434:     } else {
 3435: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3436:     }
 3437: 
 3438:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3439:       $result.=&arrayref2str($hashref->{$key}).'&';
 3440:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3441:       $result.=&hashref2str($hashref->{$key}).'&';
 3442:     } elsif(ref($hashref->{$key})) {
 3443:        $result.='&';
 3444:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3445:     } else {
 3446:       $result.=&escape($hashref->{$key}).'&';
 3447:     }
 3448:   }
 3449:   $result=~s/\&$//;
 3450:   $result .= '__END_HASH_REF__';
 3451:   return $result;
 3452: }
 3453: 
 3454: sub str2hash {
 3455:     my ($string)=@_;
 3456:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3457:     return %$hash;
 3458: }
 3459: 
 3460: sub str2hashref {
 3461:   my ($string) = @_;
 3462: 
 3463:   my %hash;
 3464: 
 3465:   if($string !~ /^__HASH_REF__/) {
 3466:       if (! ($string eq '' || !defined($string))) {
 3467: 	  $hash{'error'}='Not hash reference';
 3468:       }
 3469:       return (\%hash, $string);
 3470:   }
 3471: 
 3472:   $string =~ s/^__HASH_REF__//;
 3473: 
 3474:   while($string !~ /^__END_HASH_REF__/) {
 3475:       #key
 3476:       my $key='';
 3477:       if($string =~ /^__HASH_REF__/) {
 3478:           ($key, $string)=&str2hashref($string);
 3479:           if(defined($key->{'error'})) {
 3480:               $hash{'error'}='Bad data';
 3481:               return (\%hash, $string);
 3482:           }
 3483:       } elsif($string =~ /^__ARRAY_REF__/) {
 3484:           ($key, $string)=&str2arrayref($string);
 3485:           if($key->[0] eq 'Array reference error') {
 3486:               $hash{'error'}='Bad data';
 3487:               return (\%hash, $string);
 3488:           }
 3489:       } else {
 3490:           $string =~ s/^(.*?)=//;
 3491: 	  $key=&unescape($1);
 3492:       }
 3493:       $string =~ s/^=//;
 3494: 
 3495:       #value
 3496:       my $value='';
 3497:       if($string =~ /^__HASH_REF__/) {
 3498:           ($value, $string)=&str2hashref($string);
 3499:           if(defined($value->{'error'})) {
 3500:               $hash{'error'}='Bad data';
 3501:               return (\%hash, $string);
 3502:           }
 3503:       } elsif($string =~ /^__ARRAY_REF__/) {
 3504:           ($value, $string)=&str2arrayref($string);
 3505:           if($value->[0] eq 'Array reference error') {
 3506:               $hash{'error'}='Bad data';
 3507:               return (\%hash, $string);
 3508:           }
 3509:       } else {
 3510: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3511:       }
 3512:       $string =~ s/^&//;
 3513: 
 3514:       $hash{$key}=$value;
 3515:   }
 3516: 
 3517:   $string =~ s/^__END_HASH_REF__//;
 3518: 
 3519:   return (\%hash, $string);
 3520: }
 3521: 
 3522: sub str2array {
 3523:     my ($string)=@_;
 3524:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3525:     return @$array;
 3526: }
 3527: 
 3528: sub str2arrayref {
 3529:   my ($string) = @_;
 3530:   my @array;
 3531: 
 3532:   if($string !~ /^__ARRAY_REF__/) {
 3533:       if (! ($string eq '' || !defined($string))) {
 3534: 	  $array[0]='Array reference error';
 3535:       }
 3536:       return (\@array, $string);
 3537:   }
 3538: 
 3539:   $string =~ s/^__ARRAY_REF__//;
 3540: 
 3541:   while($string !~ /^__END_ARRAY_REF__/) {
 3542:       my $value='';
 3543:       if($string =~ /^__HASH_REF__/) {
 3544:           ($value, $string)=&str2hashref($string);
 3545:           if(defined($value->{'error'})) {
 3546:               $array[0] ='Array reference error';
 3547:               return (\@array, $string);
 3548:           }
 3549:       } elsif($string =~ /^__ARRAY_REF__/) {
 3550:           ($value, $string)=&str2arrayref($string);
 3551:           if($value->[0] eq 'Array reference error') {
 3552:               $array[0] ='Array reference error';
 3553:               return (\@array, $string);
 3554:           }
 3555:       } else {
 3556: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3557:       }
 3558:       $string =~ s/^&//;
 3559: 
 3560:       push(@array, $value);
 3561:   }
 3562: 
 3563:   $string =~ s/^__END_ARRAY_REF__//;
 3564: 
 3565:   return (\@array, $string);
 3566: }
 3567: 
 3568: # -------------------------------------------------------------------Temp Store
 3569: 
 3570: sub tmpreset {
 3571:   my ($symb,$namespace,$domain,$stuname) = @_;
 3572:   if (!$symb) {
 3573:     $symb=&symbread();
 3574:     if (!$symb) { $symb= $env{'request.url'}; }
 3575:   }
 3576:   $symb=escape($symb);
 3577: 
 3578:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3579:   $namespace=~s/\//\_/g;
 3580:   $namespace=~s/\W//g;
 3581: 
 3582:   if (!$domain) { $domain=$env{'user.domain'}; }
 3583:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3584:   if ($domain eq 'public' && $stuname eq 'public') {
 3585:       $stuname=$ENV{'REMOTE_ADDR'};
 3586:   }
 3587:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3588:   my %hash;
 3589:   if (tie(%hash,'GDBM_File',
 3590: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3591: 	  &GDBM_WRCREAT(),0640)) {
 3592:     foreach my $key (keys(%hash)) {
 3593:       if ($key=~ /:$symb/) {
 3594: 	delete($hash{$key});
 3595:       }
 3596:     }
 3597:   }
 3598: }
 3599: 
 3600: sub tmpstore {
 3601:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3602: 
 3603:   if (!$symb) {
 3604:     $symb=&symbread();
 3605:     if (!$symb) { $symb= $env{'request.url'}; }
 3606:   }
 3607:   $symb=escape($symb);
 3608: 
 3609:   if (!$namespace) {
 3610:     # I don't think we would ever want to store this for a course.
 3611:     # it seems this will only be used if we don't have a course.
 3612:     #$namespace=$env{'request.course.id'};
 3613:     #if (!$namespace) {
 3614:       $namespace=$env{'request.state'};
 3615:     #}
 3616:   }
 3617:   $namespace=~s/\//\_/g;
 3618:   $namespace=~s/\W//g;
 3619:   if (!$domain) { $domain=$env{'user.domain'}; }
 3620:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3621:   if ($domain eq 'public' && $stuname eq 'public') {
 3622:       $stuname=$ENV{'REMOTE_ADDR'};
 3623:   }
 3624:   my $now=time;
 3625:   my %hash;
 3626:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3627:   if (tie(%hash,'GDBM_File',
 3628: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3629: 	  &GDBM_WRCREAT(),0640)) {
 3630:     $hash{"version:$symb"}++;
 3631:     my $version=$hash{"version:$symb"};
 3632:     my $allkeys=''; 
 3633:     foreach my $key (keys(%$storehash)) {
 3634:       $allkeys.=$key.':';
 3635:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3636:     }
 3637:     $hash{"$version:$symb:timestamp"}=$now;
 3638:     $allkeys.='timestamp';
 3639:     $hash{"$version:keys:$symb"}=$allkeys;
 3640:     if (untie(%hash)) {
 3641:       return 'ok';
 3642:     } else {
 3643:       return "error:$!";
 3644:     }
 3645:   } else {
 3646:     return "error:$!";
 3647:   }
 3648: }
 3649: 
 3650: # -----------------------------------------------------------------Temp Restore
 3651: 
 3652: sub tmprestore {
 3653:   my ($symb,$namespace,$domain,$stuname) = @_;
 3654: 
 3655:   if (!$symb) {
 3656:     $symb=&symbread();
 3657:     if (!$symb) { $symb= $env{'request.url'}; }
 3658:   }
 3659:   $symb=escape($symb);
 3660: 
 3661:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3662: 
 3663:   if (!$domain) { $domain=$env{'user.domain'}; }
 3664:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3665:   if ($domain eq 'public' && $stuname eq 'public') {
 3666:       $stuname=$ENV{'REMOTE_ADDR'};
 3667:   }
 3668:   my %returnhash;
 3669:   $namespace=~s/\//\_/g;
 3670:   $namespace=~s/\W//g;
 3671:   my %hash;
 3672:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3673:   if (tie(%hash,'GDBM_File',
 3674: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3675: 	  &GDBM_READER(),0640)) {
 3676:     my $version=$hash{"version:$symb"};
 3677:     $returnhash{'version'}=$version;
 3678:     my $scope;
 3679:     for ($scope=1;$scope<=$version;$scope++) {
 3680:       my $vkeys=$hash{"$scope:keys:$symb"};
 3681:       my @keys=split(/:/,$vkeys);
 3682:       my $key;
 3683:       $returnhash{"$scope:keys"}=$vkeys;
 3684:       foreach $key (@keys) {
 3685: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3686: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3687:       }
 3688:     }
 3689:     if (!(untie(%hash))) {
 3690:       return "error:$!";
 3691:     }
 3692:   } else {
 3693:     return "error:$!";
 3694:   }
 3695:   return %returnhash;
 3696: }
 3697: 
 3698: # ----------------------------------------------------------------------- Store
 3699: 
 3700: sub store {
 3701:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3702:     my $home='';
 3703: 
 3704:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3705: 
 3706:     $symb=&symbclean($symb);
 3707:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3708: 
 3709:     if (!$domain) { $domain=$env{'user.domain'}; }
 3710:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3711: 
 3712:     &devalidate($symb,$stuname,$domain);
 3713: 
 3714:     $symb=escape($symb);
 3715:     if (!$namespace) { 
 3716:        unless ($namespace=$env{'request.course.id'}) { 
 3717:           return ''; 
 3718:        } 
 3719:     }
 3720:     if (!$home) { $home=$env{'user.home'}; }
 3721: 
 3722:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3723:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3724: 
 3725:     my $namevalue='';
 3726:     foreach my $key (keys(%$storehash)) {
 3727:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3728:     }
 3729:     $namevalue=~s/\&$//;
 3730:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3731:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3732: }
 3733: 
 3734: # -------------------------------------------------------------- Critical Store
 3735: 
 3736: sub cstore {
 3737:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3738:     my $home='';
 3739: 
 3740:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3741: 
 3742:     $symb=&symbclean($symb);
 3743:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3744: 
 3745:     if (!$domain) { $domain=$env{'user.domain'}; }
 3746:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3747: 
 3748:     &devalidate($symb,$stuname,$domain);
 3749: 
 3750:     $symb=escape($symb);
 3751:     if (!$namespace) { 
 3752:        unless ($namespace=$env{'request.course.id'}) { 
 3753:           return ''; 
 3754:        } 
 3755:     }
 3756:     if (!$home) { $home=$env{'user.home'}; }
 3757: 
 3758:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3759:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3760: 
 3761:     my $namevalue='';
 3762:     foreach my $key (keys(%$storehash)) {
 3763:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3764:     }
 3765:     $namevalue=~s/\&$//;
 3766:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3767:     return critical
 3768:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3769: }
 3770: 
 3771: # --------------------------------------------------------------------- Restore
 3772: 
 3773: sub restore {
 3774:     my ($symb,$namespace,$domain,$stuname) = @_;
 3775:     my $home='';
 3776: 
 3777:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3778: 
 3779:     if (!$symb) {
 3780:       unless ($symb=escape(&symbread())) { return ''; }
 3781:     } else {
 3782:       $symb=&escape(&symbclean($symb));
 3783:     }
 3784:     if (!$namespace) { 
 3785:        unless ($namespace=$env{'request.course.id'}) { 
 3786:           return ''; 
 3787:        } 
 3788:     }
 3789:     if (!$domain) { $domain=$env{'user.domain'}; }
 3790:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3791:     if (!$home) { $home=$env{'user.home'}; }
 3792:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3793: 
 3794:     my %returnhash=();
 3795:     foreach my $line (split(/\&/,$answer)) {
 3796: 	my ($name,$value)=split(/\=/,$line);
 3797:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3798:     }
 3799:     my $version;
 3800:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3801:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3802:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3803:        }
 3804:     }
 3805:     return %returnhash;
 3806: }
 3807: 
 3808: # ---------------------------------------------------------- Course Description
 3809: 
 3810: sub coursedescription {
 3811:     my ($courseid,$args)=@_;
 3812:     $courseid=~s/^\///;
 3813:     $courseid=~s/\_/\//g;
 3814:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3815:     my $chome=&homeserver($cnum,$cdomain);
 3816:     my $normalid=$cdomain.'_'.$cnum;
 3817:     # need to always cache even if we get errors otherwise we keep 
 3818:     # trying and trying and trying to get the course description.
 3819:     my %envhash=();
 3820:     my %returnhash=();
 3821:     
 3822:     my $expiretime=600;
 3823:     if ($env{'request.course.id'} eq $normalid) {
 3824: 	$expiretime=120;
 3825:     }
 3826: 
 3827:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3828:     if (!$args->{'freshen_cache'}
 3829: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3830: 	foreach my $key (keys(%env)) {
 3831: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3832: 	    my ($setting) = $1;
 3833: 	    $returnhash{$setting} = $env{$key};
 3834: 	}
 3835: 	return %returnhash;
 3836:     }
 3837: 
 3838:     # get the data agin
 3839:     if (!$args->{'one_time'}) {
 3840: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3841:     }
 3842: 
 3843:     if ($chome ne 'no_host') {
 3844:        %returnhash=&dump('environment',$cdomain,$cnum);
 3845:        if (!exists($returnhash{'con_lost'})) {
 3846:            $returnhash{'home'}= $chome;
 3847: 	   $returnhash{'domain'} = $cdomain;
 3848: 	   $returnhash{'num'} = $cnum;
 3849:            if (!defined($returnhash{'type'})) {
 3850:                $returnhash{'type'} = 'Course';
 3851:            }
 3852:            while (my ($name,$value) = each %returnhash) {
 3853:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3854:            }
 3855:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3856:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3857: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3858:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3859:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3860:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3861:        }
 3862:     }
 3863:     if (!$args->{'one_time'}) {
 3864: 	&appenv(\%envhash);
 3865:     }
 3866:     return %returnhash;
 3867: }
 3868: 
 3869: # -------------------------------------------------See if a user is privileged
 3870: 
 3871: sub privileged {
 3872:     my ($username,$domain)=@_;
 3873:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3874: 			&homeserver($username,$domain));
 3875:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 3876:         ($rolesdump =~ /^error:/)) {
 3877:         return 0;
 3878:     }
 3879:     my $now=time;
 3880:     if ($rolesdump ne '') {
 3881:         foreach my $entry (split(/&/,$rolesdump)) {
 3882: 	    if ($entry!~/^rolesdef_/) {
 3883: 		my ($area,$role)=split(/=/,$entry);
 3884: 		$area=~s/\_\w\w$//;
 3885: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3886: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3887: 		    my $active=1;
 3888: 		    if ($tend) {
 3889: 			if ($tend<$now) { $active=0; }
 3890: 		    }
 3891: 		    if ($tstart) {
 3892: 			if ($tstart>$now) { $active=0; }
 3893: 		    }
 3894: 		    if ($active) { return 1; }
 3895: 		}
 3896: 	    }
 3897: 	}
 3898:     }
 3899:     return 0;
 3900: }
 3901: 
 3902: # -------------------------------------------------------- Get user privileges
 3903: 
 3904: sub rolesinit {
 3905:     my ($domain,$username,$authhost)=@_;
 3906:     my $now=time;
 3907:     my %userroles = ('user.login.time' => $now);
 3908:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3909:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 3910:         ($rolesdump =~ /^error:/)) { 
 3911:         return \%userroles;
 3912:     }
 3913:     my %allroles=();
 3914:     my %allgroups=();   
 3915:     my $group_privs;
 3916: 
 3917:     if ($rolesdump ne '') {
 3918:         foreach my $entry (split(/&/,$rolesdump)) {
 3919: 	  if ($entry!~/^rolesdef_/) {
 3920:             my ($area,$role)=split(/=/,$entry);
 3921: 	    $area=~s/\_\w\w$//;
 3922:             my ($trole,$tend,$tstart,$group_privs);
 3923: 	    if ($role=~/^cr/) { 
 3924: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3925: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3926: 		    ($tend,$tstart)=split('_',$trest);
 3927: 		} else {
 3928: 		    $trole=$role;
 3929: 		}
 3930:             } elsif ($role =~ m|^gr/|) {
 3931:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3932:                 ($trole,$group_privs) = split(/\//,$trole);
 3933:                 $group_privs = &unescape($group_privs);
 3934: 	    } else {
 3935: 		($trole,$tend,$tstart)=split(/_/,$role);
 3936: 	    }
 3937: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3938: 					 $username);
 3939: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3940:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3941:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3942:             if (($area ne '') && ($trole ne '')) {
 3943: 		my $spec=$trole.'.'.$area;
 3944: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3945: 		if ($trole =~ /^cr\//) {
 3946:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3947:                 } elsif ($trole eq 'gr') {
 3948:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3949: 		} else {
 3950:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3951: 		}
 3952:             }
 3953:           }
 3954:         }
 3955:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3956:         $userroles{'user.adv'}    = $adv;
 3957: 	$userroles{'user.author'} = $author;
 3958:         $env{'user.adv'}=$adv;
 3959:     }
 3960:     return \%userroles;  
 3961: }
 3962: 
 3963: sub set_arearole {
 3964:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3965: # log the associated role with the area
 3966:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3967:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3968: }
 3969: 
 3970: sub custom_roleprivs {
 3971:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3972:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3973:     my $homsvr=homeserver($rauthor,$rdomain);
 3974:     if (&hostname($homsvr) ne '') {
 3975:         my ($rdummy,$roledef)=
 3976:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3977:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3978:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3979:             if (defined($syspriv)) {
 3980:                 if ($trest =~ /^$match_community$/) {
 3981:                     $syspriv =~ s/bre\&S//; 
 3982:                 }
 3983:                 $$allroles{'cm./'}.=':'.$syspriv;
 3984:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3985:             }
 3986:             if ($tdomain ne '') {
 3987:                 if (defined($dompriv)) {
 3988:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3989:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3990:                 }
 3991:                 if (($trest ne '') && (defined($coursepriv))) {
 3992:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3993:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3994:                 }
 3995:             }
 3996:         }
 3997:     }
 3998: }
 3999: 
 4000: sub group_roleprivs {
 4001:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 4002:     my $access = 1;
 4003:     my $now = time;
 4004:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 4005:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 4006:     if ($access) {
 4007:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 4008:         $$allgroups{$course}{$group} .=':'.$group_privs;
 4009:     }
 4010: }
 4011: 
 4012: sub standard_roleprivs {
 4013:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 4014:     if (defined($pr{$trole.':s'})) {
 4015:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 4016:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 4017:     }
 4018:     if ($tdomain ne '') {
 4019:         if (defined($pr{$trole.':d'})) {
 4020:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4021:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4022:         }
 4023:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 4024:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 4025:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 4026:         }
 4027:     }
 4028: }
 4029: 
 4030: sub set_userprivs {
 4031:     my ($userroles,$allroles,$allgroups) = @_; 
 4032:     my $author=0;
 4033:     my $adv=0;
 4034:     my %grouproles = ();
 4035:     if (keys(%{$allgroups}) > 0) {
 4036:         foreach my $role (keys(%{$allroles})) {
 4037:             my ($trole,$area,$sec,$extendedarea);
 4038:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 4039:                 $trole = $1;
 4040:                 $area = $2;
 4041:                 $sec = $3;
 4042:                 $extendedarea = $area.$sec;
 4043:                 if (exists($$allgroups{$area})) {
 4044:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 4045:                         my $spec = $trole.'.'.$extendedarea;
 4046:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 4047:                                                 $$allgroups{$area}{$group};
 4048:                     }
 4049:                 }
 4050:             }
 4051:         }
 4052:     }
 4053:     foreach my $group (keys(%grouproles)) {
 4054:         $$allroles{$group} = $grouproles{$group};
 4055:     }
 4056:     foreach my $role (keys(%{$allroles})) {
 4057:         my %thesepriv;
 4058:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 4059:         foreach my $item (split(/:/,$$allroles{$role})) {
 4060:             if ($item ne '') {
 4061:                 my ($privilege,$restrictions)=split(/&/,$item);
 4062:                 if ($restrictions eq '') {
 4063:                     $thesepriv{$privilege}='F';
 4064:                 } elsif ($thesepriv{$privilege} ne 'F') {
 4065:                     $thesepriv{$privilege}.=$restrictions;
 4066:                 }
 4067:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 4068:             }
 4069:         }
 4070:         my $thesestr='';
 4071:         foreach my $priv (keys(%thesepriv)) {
 4072: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 4073: 	}
 4074:         $userroles->{'user.priv.'.$role} = $thesestr;
 4075:     }
 4076:     return ($author,$adv);
 4077: }
 4078: 
 4079: sub role_status {
 4080:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 4081:     my @pwhere = ();
 4082:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 4083:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 4084:         unless (!defined($$role) || $$role eq '') {
 4085:             $$where=join('.',@pwhere);
 4086:             $$trolecode=$$role.'.'.$$where;
 4087:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 4088:             $$tstatus='is';
 4089:             if ($$tstart && $$tstart>$then) {
 4090:                 $$tstatus='future';
 4091:                 if ($$tstart<$now) {
 4092:                     if ($$tstart && $$tstart>$refresh) {
 4093:                         if (($$where ne '') && ($$role ne '')) {
 4094:                             my (%allroles,%allgroups,$group_privs);
 4095:                             my %userroles = (
 4096:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 4097:                             );
 4098:                             my $spec=$$role.'.'.$$where;
 4099:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 4100:                             if ($$role =~ /^cr\//) {
 4101:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 4102:                             } elsif ($$role eq 'gr') {
 4103:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 4104:                                                     $env{'user.name'});
 4105:                                 my $trole = split('_',$rolehash{$$where.'_'.$$role},1);
 4106:                                 (undef,my $group_privs) = split(/\//,$trole);
 4107:                                 $group_privs = &unescape($group_privs);
 4108:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 4109:                             } else {
 4110:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 4111:                             }
 4112:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups);
 4113:                             &appenv(\%userroles,[$$role,'cm']);
 4114:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4115:                         }
 4116:                     }
 4117:                     $$tstatus = 'is';
 4118:                 }
 4119:             }
 4120:             if ($$tend) {
 4121:                 if ($$tend<$then) {
 4122:                     $$tstatus='expired';
 4123:                 } elsif ($$tend<$now) {
 4124:                     $$tstatus='will_not';
 4125:                 }
 4126:             }
 4127:         }
 4128:     }
 4129: }
 4130: 
 4131: sub check_adhoc_privs {
 4132:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
 4133:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 4134:     if ($env{$cckey}) {
 4135:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 4136:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 4137:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 4138:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
 4139:         }
 4140:     } else {
 4141:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
 4142:     }
 4143: }
 4144: 
 4145: sub set_adhoc_privileges {
 4146: # role can be cc or ca
 4147:     my ($dcdom,$pickedcourse,$role) = @_;
 4148:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 4149:     my $spec = $role.'.'.$area;
 4150:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 4151:                                   $env{'user.name'});
 4152:     my %ccrole = ();
 4153:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 4154:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 4155:     &appenv(\%userroles,[$role,'cm']);
 4156:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4157:     &appenv( {'request.role'        => $spec,
 4158:               'request.role.domain' => $dcdom,
 4159:               'request.course.sec'  => ''
 4160:              }
 4161:            );
 4162:     my $tadv=0;
 4163:     if (&allowed('adv') eq 'F') { $tadv=1; }
 4164:     &appenv({'request.role.adv'    => $tadv});
 4165: }
 4166: 
 4167: # --------------------------------------------------------------- get interface
 4168: 
 4169: sub get {
 4170:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4171:    my $items='';
 4172:    foreach my $item (@$storearr) {
 4173:        $items.=&escape($item).'&';
 4174:    }
 4175:    $items=~s/\&$//;
 4176:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4177:    if (!$uname) { $uname=$env{'user.name'}; }
 4178:    my $uhome=&homeserver($uname,$udomain);
 4179: 
 4180:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 4181:    my @pairs=split(/\&/,$rep);
 4182:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 4183:      return @pairs;
 4184:    }
 4185:    my %returnhash=();
 4186:    my $i=0;
 4187:    foreach my $item (@$storearr) {
 4188:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4189:       $i++;
 4190:    }
 4191:    return %returnhash;
 4192: }
 4193: 
 4194: # --------------------------------------------------------------- del interface
 4195: 
 4196: sub del {
 4197:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4198:    my $items='';
 4199:    foreach my $item (@$storearr) {
 4200:        $items.=&escape($item).'&';
 4201:    }
 4202: 
 4203:    $items=~s/\&$//;
 4204:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4205:    if (!$uname) { $uname=$env{'user.name'}; }
 4206:    my $uhome=&homeserver($uname,$udomain);
 4207:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 4208: }
 4209: 
 4210: # -------------------------------------------------------------- dump interface
 4211: 
 4212: sub dump {
 4213:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4214:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4215:     if (!$uname) { $uname=$env{'user.name'}; }
 4216:     my $uhome=&homeserver($uname,$udomain);
 4217:     if ($regexp) {
 4218: 	$regexp=&escape($regexp);
 4219:     } else {
 4220: 	$regexp='.';
 4221:     }
 4222:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4223:     my @pairs=split(/\&/,$rep);
 4224:     my %returnhash=();
 4225:     foreach my $item (@pairs) {
 4226: 	my ($key,$value)=split(/=/,$item,2);
 4227: 	$key = &unescape($key);
 4228: 	next if ($key =~ /^error: 2 /);
 4229: 	$returnhash{$key}=&thaw_unescape($value);
 4230:     }
 4231:     return %returnhash;
 4232: }
 4233: 
 4234: # --------------------------------------------------------- dumpstore interface
 4235: 
 4236: sub dumpstore {
 4237:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4238:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4239:    if (!$uname) { $uname=$env{'user.name'}; }
 4240:    my $uhome=&homeserver($uname,$udomain);
 4241:    if ($regexp) {
 4242:        $regexp=&escape($regexp);
 4243:    } else {
 4244:        $regexp='.';
 4245:    }
 4246:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4247:    my @pairs=split(/\&/,$rep);
 4248:    my %returnhash=();
 4249:    foreach my $item (@pairs) {
 4250:        my ($key,$value)=split(/=/,$item,2);
 4251:        next if ($key =~ /^error: 2 /);
 4252:        $returnhash{$key}=&thaw_unescape($value);
 4253:    }
 4254:    return %returnhash;
 4255: }
 4256: 
 4257: # -------------------------------------------------------------- keys interface
 4258: 
 4259: sub getkeys {
 4260:    my ($namespace,$udomain,$uname)=@_;
 4261:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4262:    if (!$uname) { $uname=$env{'user.name'}; }
 4263:    my $uhome=&homeserver($uname,$udomain);
 4264:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 4265:    my @keyarray=();
 4266:    foreach my $key (split(/\&/,$rep)) {
 4267:       next if ($key =~ /^error: 2 /);
 4268:       push(@keyarray,&unescape($key));
 4269:    }
 4270:    return @keyarray;
 4271: }
 4272: 
 4273: # --------------------------------------------------------------- currentdump
 4274: sub currentdump {
 4275:    my ($courseid,$sdom,$sname)=@_;
 4276:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 4277:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 4278:    $sname    = $env{'user.name'}         if (! defined($sname));
 4279:    my $uhome = &homeserver($sname,$sdom);
 4280:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 4281:    return if ($rep =~ /^(error:|no_such_host)/);
 4282:    #
 4283:    my %returnhash=();
 4284:    #
 4285:    if ($rep eq "unknown_cmd") { 
 4286:        # an old lond will not know currentdump
 4287:        # Do a dump and make it look like a currentdump
 4288:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 4289:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 4290:        my %hash = @tmp;
 4291:        @tmp=();
 4292:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 4293:    } else {
 4294:        my @pairs=split(/\&/,$rep);
 4295:        foreach my $pair (@pairs) {
 4296:            my ($key,$value)=split(/=/,$pair,2);
 4297:            my ($symb,$param) = split(/:/,$key);
 4298:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 4299:                                                         &thaw_unescape($value);
 4300:        }
 4301:    }
 4302:    return %returnhash;
 4303: }
 4304: 
 4305: sub convert_dump_to_currentdump{
 4306:     my %hash = %{shift()};
 4307:     my %returnhash;
 4308:     # Code ripped from lond, essentially.  The only difference
 4309:     # here is the unescaping done by lonnet::dump().  Conceivably
 4310:     # we might run in to problems with parameter names =~ /^v\./
 4311:     while (my ($key,$value) = each(%hash)) {
 4312:         my ($v,$symb,$param) = split(/:/,$key);
 4313: 	$symb  = &unescape($symb);
 4314: 	$param = &unescape($param);
 4315:         next if ($v eq 'version' || $symb eq 'keys');
 4316:         next if (exists($returnhash{$symb}) &&
 4317:                  exists($returnhash{$symb}->{$param}) &&
 4318:                  $returnhash{$symb}->{'v.'.$param} > $v);
 4319:         $returnhash{$symb}->{$param}=$value;
 4320:         $returnhash{$symb}->{'v.'.$param}=$v;
 4321:     }
 4322:     #
 4323:     # Remove all of the keys in the hashes which keep track of
 4324:     # the version of the parameter.
 4325:     while (my ($symb,$param_hash) = each(%returnhash)) {
 4326:         # use a foreach because we are going to delete from the hash.
 4327:         foreach my $key (keys(%$param_hash)) {
 4328:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 4329:         }
 4330:     }
 4331:     return \%returnhash;
 4332: }
 4333: 
 4334: # ------------------------------------------------------ critical inc interface
 4335: 
 4336: sub cinc {
 4337:     return &inc(@_,'critical');
 4338: }
 4339: 
 4340: # --------------------------------------------------------------- inc interface
 4341: 
 4342: sub inc {
 4343:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 4344:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4345:     if (!$uname) { $uname=$env{'user.name'}; }
 4346:     my $uhome=&homeserver($uname,$udomain);
 4347:     my $items='';
 4348:     if (! ref($store)) {
 4349:         # got a single value, so use that instead
 4350:         $items = &escape($store).'=&';
 4351:     } elsif (ref($store) eq 'SCALAR') {
 4352:         $items = &escape($$store).'=&';        
 4353:     } elsif (ref($store) eq 'ARRAY') {
 4354:         $items = join('=&',map {&escape($_);} @{$store});
 4355:     } elsif (ref($store) eq 'HASH') {
 4356:         while (my($key,$value) = each(%{$store})) {
 4357:             $items.= &escape($key).'='.&escape($value).'&';
 4358:         }
 4359:     }
 4360:     $items=~s/\&$//;
 4361:     if ($critical) {
 4362: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 4363:     } else {
 4364: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 4365:     }
 4366: }
 4367: 
 4368: # --------------------------------------------------------------- put interface
 4369: 
 4370: sub put {
 4371:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4372:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4373:    if (!$uname) { $uname=$env{'user.name'}; }
 4374:    my $uhome=&homeserver($uname,$udomain);
 4375:    my $items='';
 4376:    foreach my $item (keys(%$storehash)) {
 4377:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4378:    }
 4379:    $items=~s/\&$//;
 4380:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4381: }
 4382: 
 4383: # ------------------------------------------------------------ newput interface
 4384: 
 4385: sub newput {
 4386:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4387:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4388:    if (!$uname) { $uname=$env{'user.name'}; }
 4389:    my $uhome=&homeserver($uname,$udomain);
 4390:    my $items='';
 4391:    foreach my $key (keys(%$storehash)) {
 4392:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4393:    }
 4394:    $items=~s/\&$//;
 4395:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 4396: }
 4397: 
 4398: # ---------------------------------------------------------  putstore interface
 4399: 
 4400: sub putstore {
 4401:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4402:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4403:    if (!$uname) { $uname=$env{'user.name'}; }
 4404:    my $uhome=&homeserver($uname,$udomain);
 4405:    my $items='';
 4406:    foreach my $key (keys(%$storehash)) {
 4407:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 4408:    }
 4409:    $items=~s/\&$//;
 4410:    my $esc_symb=&escape($symb);
 4411:    my $esc_v=&escape($version);
 4412:    my $reply =
 4413:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 4414: 	      $uhome);
 4415:    if ($reply eq 'unknown_cmd') {
 4416:        # gfall back to way things use to be done
 4417:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 4418: 			    $uname);
 4419:    }
 4420:    return $reply;
 4421: }
 4422: 
 4423: sub old_putstore {
 4424:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4425:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4426:     if (!$uname) { $uname=$env{'user.name'}; }
 4427:     my $uhome=&homeserver($uname,$udomain);
 4428:     my %newstorehash;
 4429:     foreach my $item (keys(%$storehash)) {
 4430: 	my $key = $version.':'.&escape($symb).':'.$item;
 4431: 	$newstorehash{$key} = $storehash->{$item};
 4432:     }
 4433:     my $items='';
 4434:     my %allitems = ();
 4435:     foreach my $item (keys(%newstorehash)) {
 4436: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 4437: 	    my $key = $1.':keys:'.$2;
 4438: 	    $allitems{$key} .= $3.':';
 4439: 	}
 4440: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 4441:     }
 4442:     foreach my $item (keys(%allitems)) {
 4443: 	$allitems{$item} =~ s/\:$//;
 4444: 	$items.= $item.'='.$allitems{$item}.'&';
 4445:     }
 4446:     $items=~s/\&$//;
 4447:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4448: }
 4449: 
 4450: # ------------------------------------------------------ critical put interface
 4451: 
 4452: sub cput {
 4453:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4454:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4455:    if (!$uname) { $uname=$env{'user.name'}; }
 4456:    my $uhome=&homeserver($uname,$udomain);
 4457:    my $items='';
 4458:    foreach my $item (keys(%$storehash)) {
 4459:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4460:    }
 4461:    $items=~s/\&$//;
 4462:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 4463: }
 4464: 
 4465: # -------------------------------------------------------------- eget interface
 4466: 
 4467: sub eget {
 4468:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4469:    my $items='';
 4470:    foreach my $item (@$storearr) {
 4471:        $items.=&escape($item).'&';
 4472:    }
 4473:    $items=~s/\&$//;
 4474:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4475:    if (!$uname) { $uname=$env{'user.name'}; }
 4476:    my $uhome=&homeserver($uname,$udomain);
 4477:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 4478:    my @pairs=split(/\&/,$rep);
 4479:    my %returnhash=();
 4480:    my $i=0;
 4481:    foreach my $item (@$storearr) {
 4482:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4483:       $i++;
 4484:    }
 4485:    return %returnhash;
 4486: }
 4487: 
 4488: # ------------------------------------------------------------ tmpput interface
 4489: sub tmpput {
 4490:     my ($storehash,$server,$context)=@_;
 4491:     my $items='';
 4492:     foreach my $item (keys(%$storehash)) {
 4493: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4494:     }
 4495:     $items=~s/\&$//;
 4496:     if (defined($context)) {
 4497:         $items .= ':'.&escape($context);
 4498:     }
 4499:     return &reply("tmpput:$items",$server);
 4500: }
 4501: 
 4502: # ------------------------------------------------------------ tmpget interface
 4503: sub tmpget {
 4504:     my ($token,$server)=@_;
 4505:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4506:     my $rep=&reply("tmpget:$token",$server);
 4507:     my %returnhash;
 4508:     foreach my $item (split(/\&/,$rep)) {
 4509: 	my ($key,$value)=split(/=/,$item);
 4510:         next if ($key =~ /^error: 2 /);
 4511: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 4512:     }
 4513:     return %returnhash;
 4514: }
 4515: 
 4516: # ------------------------------------------------------------ tmpget interface
 4517: sub tmpdel {
 4518:     my ($token,$server)=@_;
 4519:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4520:     return &reply("tmpdel:$token",$server);
 4521: }
 4522: 
 4523: # -------------------------------------------------- portfolio access checking
 4524: 
 4525: sub portfolio_access {
 4526:     my ($requrl) = @_;
 4527:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4528:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4529:     if ($result) {
 4530:         my %setters;
 4531:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4532:             my ($startblock,$endblock) =
 4533:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4534:             if ($startblock && $endblock) {
 4535:                 return 'B';
 4536:             }
 4537:         } else {
 4538:             my ($startblock,$endblock) =
 4539:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4540:             if ($startblock && $endblock) {
 4541:                 return 'B';
 4542:             }
 4543:         }
 4544:     }
 4545:     if ($result eq 'ok') {
 4546:        return 'F';
 4547:     } elsif ($result =~ /^[^:]+:guest_/) {
 4548:        return 'A';
 4549:     }
 4550:     return '';
 4551: }
 4552: 
 4553: sub get_portfolio_access {
 4554:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4555: 
 4556:     if (!ref($access_hash)) {
 4557: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4558: 	my %access_controls = &get_access_controls($current_perms,$group,
 4559: 						   $file_name);
 4560: 	$access_hash = $access_controls{$file_name};
 4561:     }
 4562: 
 4563:     my ($public,$guest,@domains,@users,@courses,@groups);
 4564:     my $now = time;
 4565:     if (ref($access_hash) eq 'HASH') {
 4566:         foreach my $key (keys(%{$access_hash})) {
 4567:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4568:             if ($start > $now) {
 4569:                 next;
 4570:             }
 4571:             if ($end && $end<$now) {
 4572:                 next;
 4573:             }
 4574:             if ($scope eq 'public') {
 4575:                 $public = $key;
 4576:                 last;
 4577:             } elsif ($scope eq 'guest') {
 4578:                 $guest = $key;
 4579:             } elsif ($scope eq 'domains') {
 4580:                 push(@domains,$key);
 4581:             } elsif ($scope eq 'users') {
 4582:                 push(@users,$key);
 4583:             } elsif ($scope eq 'course') {
 4584:                 push(@courses,$key);
 4585:             } elsif ($scope eq 'group') {
 4586:                 push(@groups,$key);
 4587:             }
 4588:         }
 4589:         if ($public) {
 4590:             return 'ok';
 4591:         }
 4592:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4593:             if ($guest) {
 4594:                 return $guest;
 4595:             }
 4596:         } else {
 4597:             if (@domains > 0) {
 4598:                 foreach my $domkey (@domains) {
 4599:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4600:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4601:                             return 'ok';
 4602:                         }
 4603:                     }
 4604:                 }
 4605:             }
 4606:             if (@users > 0) {
 4607:                 foreach my $userkey (@users) {
 4608:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4609:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4610:                             if (ref($item) eq 'HASH') {
 4611:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4612:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4613:                                     return 'ok';
 4614:                                 }
 4615:                             }
 4616:                         }
 4617:                     } 
 4618:                 }
 4619:             }
 4620:             my %roleshash;
 4621:             my @courses_and_groups = @courses;
 4622:             push(@courses_and_groups,@groups); 
 4623:             if (@courses_and_groups > 0) {
 4624:                 my (%allgroups,%allroles); 
 4625:                 my ($start,$end,$role,$sec,$group);
 4626:                 foreach my $envkey (%env) {
 4627:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4628:                         my $cid = $2.'_'.$3; 
 4629:                         if ($1 eq 'gr') {
 4630:                             $group = $4;
 4631:                             $allgroups{$cid}{$group} = $env{$envkey};
 4632:                         } else {
 4633:                             if ($4 eq '') {
 4634:                                 $sec = 'none';
 4635:                             } else {
 4636:                                 $sec = $4;
 4637:                             }
 4638:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4639:                         }
 4640:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4641:                         my $cid = $2.'_'.$3;
 4642:                         if ($4 eq '') {
 4643:                             $sec = 'none';
 4644:                         } else {
 4645:                             $sec = $4;
 4646:                         }
 4647:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4648:                     }
 4649:                 }
 4650:                 if (keys(%allroles) == 0) {
 4651:                     return;
 4652:                 }
 4653:                 foreach my $key (@courses_and_groups) {
 4654:                     my %content = %{$$access_hash{$key}};
 4655:                     my $cnum = $content{'number'};
 4656:                     my $cdom = $content{'domain'};
 4657:                     my $cid = $cdom.'_'.$cnum;
 4658:                     if (!exists($allroles{$cid})) {
 4659:                         next;
 4660:                     }    
 4661:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4662:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4663:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4664:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4665:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4666:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4667:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4668:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4669:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4670:                                         if (grep/^all$/,@sections) {
 4671:                                             return 'ok';
 4672:                                         } else {
 4673:                                             if (grep/^$sec$/,@sections) {
 4674:                                                 return 'ok';
 4675:                                             }
 4676:                                         }
 4677:                                     }
 4678:                                 }
 4679:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4680:                                     if (grep/^none$/,@groups) {
 4681:                                         return 'ok';
 4682:                                     }
 4683:                                 } else {
 4684:                                     if (grep/^all$/,@groups) {
 4685:                                         return 'ok';
 4686:                                     } 
 4687:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4688:                                         if (grep/^$group$/,@groups) {
 4689:                                             return 'ok';
 4690:                                         }
 4691:                                     }
 4692:                                 } 
 4693:                             }
 4694:                         }
 4695:                     }
 4696:                 }
 4697:             }
 4698:             if ($guest) {
 4699:                 return $guest;
 4700:             }
 4701:         }
 4702:     }
 4703:     return;
 4704: }
 4705: 
 4706: sub course_group_datechecker {
 4707:     my ($dates,$now,$status) = @_;
 4708:     my ($start,$end) = split(/\./,$dates);
 4709:     if (!$start && !$end) {
 4710:         return 'ok';
 4711:     }
 4712:     if (grep/^active$/,@{$status}) {
 4713:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4714:             return 'ok';
 4715:         }
 4716:     }
 4717:     if (grep/^previous$/,@{$status}) {
 4718:         if ($end > $now ) {
 4719:             return 'ok';
 4720:         }
 4721:     }
 4722:     if (grep/^future$/,@{$status}) {
 4723:         if ($start > $now) {
 4724:             return 'ok';
 4725:         }
 4726:     }
 4727:     return; 
 4728: }
 4729: 
 4730: sub parse_portfolio_url {
 4731:     my ($url) = @_;
 4732: 
 4733:     my ($type,$udom,$unum,$group,$file_name);
 4734:     
 4735:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4736: 	$type = 1;
 4737:         $udom = $1;
 4738:         $unum = $2;
 4739:         $file_name = $3;
 4740:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4741: 	$type = 2;
 4742:         $udom = $1;
 4743:         $unum = $2;
 4744:         $group = $3;
 4745:         $file_name = $3.'/'.$4;
 4746:     }
 4747:     if (wantarray) {
 4748: 	return ($type,$udom,$unum,$file_name,$group);
 4749:     }
 4750:     return $type;
 4751: }
 4752: 
 4753: sub is_portfolio_url {
 4754:     my ($url) = @_;
 4755:     return scalar(&parse_portfolio_url($url));
 4756: }
 4757: 
 4758: sub is_portfolio_file {
 4759:     my ($file) = @_;
 4760:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4761:         return 1;
 4762:     }
 4763:     return;
 4764: }
 4765: 
 4766: sub usertools_access {
 4767:     my ($uname,$udom,$tool,$action,$context) = @_;
 4768:     my ($access,%tools);
 4769:     if ($context eq '') {
 4770:         $context = 'tools';
 4771:     }
 4772:     if ($context eq 'requestcourses') {
 4773:         %tools = (
 4774:                       official   => 1,
 4775:                       unofficial => 1,
 4776:                       community  => 1,
 4777:                  );
 4778:     } else {
 4779:         %tools = (
 4780:                       aboutme   => 1,
 4781:                       blog      => 1,
 4782:                       portfolio => 1,
 4783:                  );
 4784:     }
 4785:     return if (!defined($tools{$tool}));
 4786: 
 4787:     if ((!defined($udom)) || (!defined($uname))) {
 4788:         $udom = $env{'user.domain'};
 4789:         $uname = $env{'user.name'};
 4790:     }
 4791: 
 4792:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4793:         if ($action ne 'reload') {
 4794:             if ($context eq 'requestcourses') {
 4795:                 return $env{'environment.canrequest.'.$tool};
 4796:             } else {
 4797:                 return $env{'environment.availabletools.'.$tool};
 4798:             }
 4799:         }
 4800:     }
 4801: 
 4802:     my ($toolstatus,$inststatus);
 4803: 
 4804:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 4805:          ($action ne 'reload')) {
 4806:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 4807:         $inststatus = $env{'environment.inststatus'};
 4808:     } else {
 4809:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
 4810:         $toolstatus = $userenv{$context.'.'.$tool};
 4811:         $inststatus = $userenv{'inststatus'};
 4812:     }
 4813: 
 4814:     if ($toolstatus ne '') {
 4815:         if ($toolstatus) {
 4816:             $access = 1;
 4817:         } else {
 4818:             $access = 0;
 4819:         }
 4820:         return $access;
 4821:     }
 4822: 
 4823:     my $is_adv = &is_advanced_user($udom,$uname);
 4824:     my %domdef = &get_domain_defaults($udom);
 4825:     if (ref($domdef{$tool}) eq 'HASH') {
 4826:         if ($is_adv) {
 4827:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 4828:                 if ($domdef{$tool}{'_LC_adv'}) { 
 4829:                     $access = 1;
 4830:                 } else {
 4831:                     $access = 0;
 4832:                 }
 4833:                 return $access;
 4834:             }
 4835:         }
 4836:         if ($inststatus ne '') {
 4837:             my ($hasaccess,$hasnoaccess);
 4838:             foreach my $affiliation (split(/:/,$inststatus)) {
 4839:                 if ($domdef{$tool}{$affiliation} ne '') { 
 4840:                     if ($domdef{$tool}{$affiliation}) {
 4841:                         $hasaccess = 1;
 4842:                     } else {
 4843:                         $hasnoaccess = 1;
 4844:                     }
 4845:                 }
 4846:             }
 4847:             if ($hasaccess || $hasnoaccess) {
 4848:                 if ($hasaccess) {
 4849:                     $access = 1;
 4850:                 } elsif ($hasnoaccess) {
 4851:                     $access = 0; 
 4852:                 }
 4853:                 return $access;
 4854:             }
 4855:         } else {
 4856:             if ($domdef{$tool}{'default'} ne '') {
 4857:                 if ($domdef{$tool}{'default'}) {
 4858:                     $access = 1;
 4859:                 } elsif ($domdef{$tool}{'default'} == 0) {
 4860:                     $access = 0;
 4861:                 }
 4862:                 return $access;
 4863:             }
 4864:         }
 4865:     } else {
 4866:         if ($context eq 'tools') {
 4867:             $access = 1;
 4868:         } else {
 4869:             $access = 0;
 4870:         }
 4871:         return $access;
 4872:     }
 4873: }
 4874: 
 4875: sub is_course_owner {
 4876:     my ($cdom,$cnum,$udom,$uname) = @_;
 4877:     if (($udom eq '') || ($uname eq '')) {
 4878:         $udom = $env{'user.domain'};
 4879:         $uname = $env{'user.name'};
 4880:     }
 4881:     unless (($udom eq '') || ($uname eq '')) {
 4882:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 4883:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 4884:                 return 1;
 4885:             } else {
 4886:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 4887:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 4888:                     return 1;
 4889:                 }
 4890:             }
 4891:         }
 4892:     }
 4893:     return;
 4894: }
 4895: 
 4896: sub is_advanced_user {
 4897:     my ($udom,$uname) = @_;
 4898:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 4899:     my %allroles;
 4900:     my $is_adv;
 4901:     foreach my $role (keys(%roleshash)) {
 4902:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 4903:         my $area = '/'.$tdomain.'/'.$trest;
 4904:         if ($sec ne '') {
 4905:             $area .= '/'.$sec;
 4906:         }
 4907:         if (($area ne '') && ($trole ne '')) {
 4908:             my $spec=$trole.'.'.$area;
 4909:             if ($trole =~ /^cr\//) {
 4910:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4911:             } elsif ($trole ne 'gr') {
 4912:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4913:             }
 4914:         }
 4915:     }
 4916:     foreach my $role (keys(%allroles)) {
 4917:         last if ($is_adv);
 4918:         foreach my $item (split(/:/,$allroles{$role})) {
 4919:             if ($item ne '') {
 4920:                 my ($privilege,$restrictions)=split(/&/,$item);
 4921:                 if ($privilege eq 'adv') {
 4922:                     $is_adv = 1;
 4923:                     last;
 4924:                 }
 4925:             }
 4926:         }
 4927:     }
 4928:     return $is_adv;
 4929: }
 4930: 
 4931: sub check_can_request {
 4932:     my ($dom,$can_request,$request_domains) = @_;
 4933:     my $canreq = 0;
 4934:     my ($types,$typename) = &Apache::loncommon::course_types();
 4935:     my @options = ('approval','validate','autolimit');
 4936:     my $optregex = join('|',@options);
 4937:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 4938:         foreach my $type (@{$types}) {
 4939:             if (&usertools_access($env{'user.name'},
 4940:                                   $env{'user.domain'},
 4941:                                   $type,undef,'requestcourses')) {
 4942:                 $canreq ++;
 4943:                 if (ref($request_domains) eq 'HASH') {
 4944:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 4945:                 }
 4946:                 if ($dom eq $env{'user.domain'}) {
 4947:                     $can_request->{$type} = 1;
 4948:                 }
 4949:             }
 4950:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 4951:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 4952:                 if (@curr > 0) {
 4953:                     foreach my $item (@curr) {
 4954:                         if (ref($request_domains) eq 'HASH') {
 4955:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 4956:                             if ($otherdom ne '') {
 4957:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 4958:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 4959:                                         push(@{$request_domains->{$type}},$otherdom);
 4960:                                     }
 4961:                                 } else {
 4962:                                     push(@{$request_domains->{$type}},$otherdom);
 4963:                                 }
 4964:                             }
 4965:                         }
 4966:                     }
 4967:                     unless($dom eq $env{'user.domain'}) {
 4968:                         $canreq ++;
 4969:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 4970:                             $can_request->{$type} = 1;
 4971:                         }
 4972:                     }
 4973:                 }
 4974:             }
 4975:         }
 4976:     }
 4977:     return $canreq;
 4978: }
 4979: 
 4980: # ---------------------------------------------- Custom access rule evaluation
 4981: 
 4982: sub customaccess {
 4983:     my ($priv,$uri)=@_;
 4984:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4985:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4986:     $udom = &LONCAPA::clean_domain($udom);
 4987:     $ucrs = &LONCAPA::clean_username($ucrs);
 4988:     my $access=0;
 4989:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4990: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4991: 	if ($type eq 'user') {
 4992: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4993: 		my ($tdom,$tuname)=split(m{/},$scope);
 4994: 		if ($tdom) {
 4995: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4996: 		}
 4997: 		if ($tuname) {
 4998: 		    if ($tuname ne $env{'user.name'}) { next; }
 4999: 		}
 5000: 		$access=($effect eq 'allow');
 5001: 		last;
 5002: 	    }
 5003: 	} else {
 5004: 	    if ($role) {
 5005: 		if ($role ne $urole) { next; }
 5006: 	    }
 5007: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5008: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 5009: 		if ($tdom) {
 5010: 		    if ($tdom ne $udom) { next; }
 5011: 		}
 5012: 		if ($tcrs) {
 5013: 		    if ($tcrs ne $ucrs) { next; }
 5014: 		}
 5015: 		if ($tsec) {
 5016: 		    if ($tsec ne $usec) { next; }
 5017: 		}
 5018: 		$access=($effect eq 'allow');
 5019: 		last;
 5020: 	    }
 5021: 	    if ($realm eq '' && $role eq '') {
 5022: 		$access=($effect eq 'allow');
 5023: 	    }
 5024: 	}
 5025:     }
 5026:     return $access;
 5027: }
 5028: 
 5029: # ------------------------------------------------- Check for a user privilege
 5030: 
 5031: sub allowed {
 5032:     my ($priv,$uri,$symb,$role)=@_;
 5033:     my $ver_orguri=$uri;
 5034:     $uri=&deversion($uri);
 5035:     my $orguri=$uri;
 5036:     $uri=&declutter($uri);
 5037: 
 5038:     if ($priv eq 'evb') {
 5039: # Evade communication block restrictions for specified role in a course
 5040:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 5041:             return $1;
 5042:         } else {
 5043:             return;
 5044:         }
 5045:     }
 5046: 
 5047:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 5048: # Free bre access to adm and meta resources
 5049:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 5050: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 5051: 	&& ($priv eq 'bre')) {
 5052: 	return 'F';
 5053:     }
 5054: 
 5055: # Free bre access to user's own portfolio contents
 5056:     my ($space,$domain,$name,@dir)=split('/',$uri);
 5057:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 5058: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 5059:         my %setters;
 5060:         my ($startblock,$endblock) = 
 5061:             &Apache::loncommon::blockcheck(\%setters,'port');
 5062:         if ($startblock && $endblock) {
 5063:             return 'B';
 5064:         } else {
 5065:             return 'F';
 5066:         }
 5067:     }
 5068: 
 5069: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 5070:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 5071:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 5072:         if (exists($env{'request.course.id'})) {
 5073:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5074:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5075:             if (($domain eq $cdom) && ($name eq $cnum)) {
 5076:                 my $courseprivid=$env{'request.course.id'};
 5077:                 $courseprivid=~s/\_/\//;
 5078:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 5079:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 5080:                     return $1; 
 5081:                 } else {
 5082:                     if ($env{'request.course.sec'}) {
 5083:                         $courseprivid.='/'.$env{'request.course.sec'};
 5084:                     }
 5085:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 5086:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 5087:                         return $2;
 5088:                     }
 5089:                 }
 5090:             }
 5091:         }
 5092:     }
 5093: 
 5094: # Free bre to public access
 5095: 
 5096:     if ($priv eq 'bre') {
 5097:         my $copyright=&metadata($uri,'copyright');
 5098: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 5099:            return 'F'; 
 5100:         }
 5101:         if ($copyright eq 'priv') {
 5102:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5103: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 5104: 		return '';
 5105:             }
 5106:         }
 5107:         if ($copyright eq 'domain') {
 5108:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5109: 	    unless (($env{'user.domain'} eq $1) ||
 5110:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 5111: 		return '';
 5112:             }
 5113:         }
 5114:         if ($env{'request.role'}=~ /li\.\//) {
 5115:             # Library role, so allow browsing of resources in this domain.
 5116:             return 'F';
 5117:         }
 5118:         if ($copyright eq 'custom') {
 5119: 	    unless (&customaccess($priv,$uri)) { return ''; }
 5120:         }
 5121:     }
 5122:     # Domain coordinator is trying to create a course
 5123:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 5124:         # uri is the requested domain in this case.
 5125:         # comparison to 'request.role.domain' shows if the user has selected
 5126:         # a role of dc for the domain in question.
 5127:         return 'F' if ($uri eq $env{'request.role.domain'});
 5128:     }
 5129: 
 5130:     my $thisallowed='';
 5131:     my $statecond=0;
 5132:     my $courseprivid='';
 5133: 
 5134:     my $ownaccess;
 5135:     # Community Coordinator or Assistant Co-author browsing resource space.
 5136:     if (($priv eq 'bro') && ($env{'user.author'})) {
 5137:         if ($uri eq '') {
 5138:             $ownaccess = 1;
 5139:         } else {
 5140:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 5141:                 my $udom = $env{'user.domain'};
 5142:                 my $uname = $env{'user.name'};
 5143:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 5144:                     $ownaccess = 1;
 5145:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 5146:                     unless ($uri =~ m{\.\./}) {
 5147:                         $ownaccess = 1;
 5148:                     }
 5149:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 5150:                     my $now = time;
 5151:                     if ($uri =~ m{^([^/]+)/?$}) {
 5152:                         my $adom = $1;
 5153:                         foreach my $key (keys(%env)) {
 5154:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 5155:                                 my ($start,$end) = split('.',$env{$key});
 5156:                                 if (($now >= $start) && (!$end || $end < $now)) {
 5157:                                     $ownaccess = 1;
 5158:                                     last;
 5159:                                 }
 5160:                             }
 5161:                         }
 5162:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 5163:                         my $adom = $1;
 5164:                         my $aname = $2;
 5165:                         foreach my $role ('ca','aa') { 
 5166:                             if ($env{"user.role.$role./$adom/$aname"}) {
 5167:                                 my ($start,$end) =
 5168:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 5169:                                 if (($now >= $start) && (!$end || $end < $now)) {
 5170:                                     $ownaccess = 1;
 5171:                                     last;
 5172:                                 }
 5173:                             }
 5174:                         }
 5175:                     }
 5176:                 }
 5177:             }
 5178:         }
 5179:     }
 5180: 
 5181: # Course
 5182: 
 5183:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 5184:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5185:             $thisallowed.=$1;
 5186:         }
 5187:     }
 5188: 
 5189: # Domain
 5190: 
 5191:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 5192:        =~/\Q$priv\E\&([^\:]*)/) {
 5193:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5194:             $thisallowed.=$1;
 5195:         }
 5196:     }
 5197: 
 5198: # Course: uri itself is a course
 5199:     my $courseuri=$uri;
 5200:     $courseuri=~s/\_(\d)/\/$1/;
 5201:     $courseuri=~s/^([^\/])/\/$1/;
 5202: 
 5203:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 5204:        =~/\Q$priv\E\&([^\:]*)/) {
 5205:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5206:             $thisallowed.=$1;
 5207:         }
 5208:     }
 5209: 
 5210: # URI is an uploaded document for this course, default permissions don't matter
 5211: # not allowing 'edit' access (editupload) to uploaded course docs
 5212:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 5213: 	$thisallowed='';
 5214:         my ($match)=&is_on_map($uri);
 5215:         if ($match) {
 5216:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 5217:                   =~/\Q$priv\E\&([^\:]*)/) {
 5218:                 $thisallowed.=$1;
 5219:             }
 5220:         } else {
 5221:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 5222:             if ($refuri) {
 5223:                 if ($refuri =~ m|^/adm/|) {
 5224:                     $thisallowed='F';
 5225:                 } else {
 5226:                     $refuri=&declutter($refuri);
 5227:                     my ($match) = &is_on_map($refuri);
 5228:                     if ($match) {
 5229:                         $thisallowed='F';
 5230:                     }
 5231:                 }
 5232:             }
 5233:         }
 5234:     }
 5235: 
 5236:     if ($priv eq 'bre'
 5237: 	&& $thisallowed ne 'F' 
 5238: 	&& $thisallowed ne '2'
 5239: 	&& &is_portfolio_url($uri)) {
 5240: 	$thisallowed = &portfolio_access($uri);
 5241:     }
 5242:     
 5243: # Full access at system, domain or course-wide level? Exit.
 5244:     if ($thisallowed=~/F/) {
 5245: 	return 'F';
 5246:     }
 5247: 
 5248: # If this is generating or modifying users, exit with special codes
 5249: 
 5250:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 5251: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 5252: 	    my ($audom,$auname)=split('/',$uri);
 5253: # no author name given, so this just checks on the general right to make a co-author in this domain
 5254: 	    unless ($auname) { return $thisallowed; }
 5255: # an author name is given, so we are about to actually make a co-author for a certain account
 5256: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 5257: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 5258: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 5259: 	}
 5260: 	return $thisallowed;
 5261:     }
 5262: #
 5263: # Gathered so far: system, domain and course wide privileges
 5264: #
 5265: # Course: See if uri or referer is an individual resource that is part of 
 5266: # the course
 5267: 
 5268:     if ($env{'request.course.id'}) {
 5269: 
 5270:        $courseprivid=$env{'request.course.id'};
 5271:        if ($env{'request.course.sec'}) {
 5272:           $courseprivid.='/'.$env{'request.course.sec'};
 5273:        }
 5274:        $courseprivid=~s/\_/\//;
 5275:        my $checkreferer=1;
 5276:        my ($match,$cond)=&is_on_map($uri);
 5277:        if ($match) {
 5278:            $statecond=$cond;
 5279:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 5280:                =~/\Q$priv\E\&([^\:]*)/) {
 5281:                $thisallowed.=$1;
 5282:                $checkreferer=0;
 5283:            }
 5284:        }
 5285:        
 5286:        if ($checkreferer) {
 5287: 	  my $refuri=$env{'httpref.'.$orguri};
 5288:             unless ($refuri) {
 5289:                 foreach my $key (keys(%env)) {
 5290: 		    if ($key=~/^httpref\..*\*/) {
 5291: 			my $pattern=$key;
 5292:                         $pattern=~s/^httpref\.\/res\///;
 5293:                         $pattern=~s/\*/\[\^\/\]\+/g;
 5294:                         $pattern=~s/\//\\\//g;
 5295:                         if ($orguri=~/$pattern/) {
 5296: 			    $refuri=$env{$key};
 5297:                         }
 5298:                     }
 5299:                 }
 5300:             }
 5301: 
 5302:          if ($refuri) { 
 5303: 	  $refuri=&declutter($refuri);
 5304:           my ($match,$cond)=&is_on_map($refuri);
 5305:             if ($match) {
 5306:               my $refstatecond=$cond;
 5307:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 5308:                   =~/\Q$priv\E\&([^\:]*)/) {
 5309:                   $thisallowed.=$1;
 5310:                   $uri=$refuri;
 5311:                   $statecond=$refstatecond;
 5312:               }
 5313:           }
 5314:         }
 5315:        }
 5316:    }
 5317: 
 5318: #
 5319: # Gathered now: all privileges that could apply, and condition number
 5320: # 
 5321: #
 5322: # Full or no access?
 5323: #
 5324: 
 5325:     if ($thisallowed=~/F/) {
 5326: 	return 'F';
 5327:     }
 5328: 
 5329:     unless ($thisallowed) {
 5330:         return '';
 5331:     }
 5332: 
 5333: # Restrictions exist, deal with them
 5334: #
 5335: #   C:according to course preferences
 5336: #   R:according to resource settings
 5337: #   L:unless locked
 5338: #   X:according to user session state
 5339: #
 5340: 
 5341: # Possibly locked functionality, check all courses
 5342: # Locks might take effect only after 10 minutes cache expiration for other
 5343: # courses, and 2 minutes for current course
 5344: 
 5345:     my $envkey;
 5346:     if ($thisallowed=~/L/) {
 5347:         foreach $envkey (keys(%env)) {
 5348:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 5349:                my $courseid=$2;
 5350:                my $roleid=$1.'.'.$2;
 5351:                $courseid=~s/^\///;
 5352:                my $expiretime=600;
 5353:                if ($env{'request.role'} eq $roleid) {
 5354: 		  $expiretime=120;
 5355:                }
 5356: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 5357:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 5358:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 5359: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 5360:                }
 5361:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5362:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 5363: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 5364:                        &log($env{'user.domain'},$env{'user.name'},
 5365:                             $env{'user.home'},
 5366:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 5367:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5368:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5369: 		       return '';
 5370:                    }
 5371:                }
 5372:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5373:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 5374: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 5375:                        &log($env{'user.domain'},$env{'user.name'},
 5376:                             $env{'user.home'},
 5377:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 5378:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5379:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5380: 		       return '';
 5381:                    }
 5382:                }
 5383: 	   }
 5384:        }
 5385:     }
 5386:    
 5387: #
 5388: # Rest of the restrictions depend on selected course
 5389: #
 5390: 
 5391:     unless ($env{'request.course.id'}) {
 5392: 	if ($thisallowed eq 'A') {
 5393: 	    return 'A';
 5394:         } elsif ($thisallowed eq 'B') {
 5395:             return 'B';
 5396: 	} else {
 5397: 	    return '1';
 5398: 	}
 5399:     }
 5400: 
 5401: #
 5402: # Now user is definitely in a course
 5403: #
 5404: 
 5405: 
 5406: # Course preferences
 5407: 
 5408:    if ($thisallowed=~/C/) {
 5409:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5410:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 5411:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 5412: 	   =~/\Q$rolecode\E/) {
 5413: 	   if ($priv ne 'pch') { 
 5414: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5415: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 5416: 			$env{'request.course.id'});
 5417: 	   }
 5418:            return '';
 5419:        }
 5420: 
 5421:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 5422: 	   =~/\Q$unamedom\E/) {
 5423: 	   if ($priv ne 'pch') { 
 5424: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 5425: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 5426: 			$env{'request.course.id'});
 5427: 	   }
 5428:            return '';
 5429:        }
 5430:    }
 5431: 
 5432: # Resource preferences
 5433: 
 5434:    if ($thisallowed=~/R/) {
 5435:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5436:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 5437: 	   if ($priv ne 'pch') { 
 5438: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5439: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 5440: 	   }
 5441: 	   return '';
 5442:        }
 5443:    }
 5444: 
 5445: # Restricted by state or randomout?
 5446: 
 5447:    if ($thisallowed=~/X/) {
 5448:       if ($env{'acc.randomout'}) {
 5449: 	 if (!$symb) { $symb=&symbread($uri,1); }
 5450:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 5451:             return ''; 
 5452:          }
 5453:       }
 5454:       if (&condval($statecond)) {
 5455: 	 return '2';
 5456:       } else {
 5457:          return '';
 5458:       }
 5459:    }
 5460: 
 5461:     if ($thisallowed eq 'A') {
 5462: 	return 'A';
 5463:     } elsif ($thisallowed eq 'B') {
 5464:         return 'B';
 5465:     }
 5466:    return 'F';
 5467: }
 5468: 
 5469: sub split_uri_for_cond {
 5470:     my $uri=&deversion(&declutter(shift));
 5471:     my @uriparts=split(/\//,$uri);
 5472:     my $filename=pop(@uriparts);
 5473:     my $pathname=join('/',@uriparts);
 5474:     return ($pathname,$filename);
 5475: }
 5476: # --------------------------------------------------- Is a resource on the map?
 5477: 
 5478: sub is_on_map {
 5479:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 5480:     #Trying to find the conditional for the file
 5481:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 5482: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 5483:     if ($match) {
 5484: 	return (1,$1);
 5485:     } else {
 5486: 	return (0,0);
 5487:     }
 5488: }
 5489: 
 5490: # --------------------------------------------------------- Get symb from alias
 5491: 
 5492: sub get_symb_from_alias {
 5493:     my $symb=shift;
 5494:     my ($map,$resid,$url)=&decode_symb($symb);
 5495: # Already is a symb
 5496:     if ($url) { return $symb; }
 5497: # Must be an alias
 5498:     my $aliassymb='';
 5499:     my %bighash;
 5500:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5501:                             &GDBM_READER(),0640)) {
 5502:         my $rid=$bighash{'mapalias_'.$symb};
 5503: 	if ($rid) {
 5504: 	    my ($mapid,$resid)=split(/\./,$rid);
 5505: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 5506: 				    $resid,$bighash{'src_'.$rid});
 5507: 	}
 5508:         untie %bighash;
 5509:     }
 5510:     return $aliassymb;
 5511: }
 5512: 
 5513: # ----------------------------------------------------------------- Define Role
 5514: 
 5515: sub definerole {
 5516:   if (allowed('mcr','/')) {
 5517:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 5518:     foreach my $role (split(':',$sysrole)) {
 5519: 	my ($crole,$cqual)=split(/\&/,$role);
 5520:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 5521:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 5522: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5523:                return "refused:s:$crole&$cqual"; 
 5524:             }
 5525:         }
 5526:     }
 5527:     foreach my $role (split(':',$domrole)) {
 5528: 	my ($crole,$cqual)=split(/\&/,$role);
 5529:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 5530:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 5531: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 5532:                return "refused:d:$crole&$cqual"; 
 5533:             }
 5534:         }
 5535:     }
 5536:     foreach my $role (split(':',$courole)) {
 5537: 	my ($crole,$cqual)=split(/\&/,$role);
 5538:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 5539:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 5540: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5541:                return "refused:c:$crole&$cqual"; 
 5542:             }
 5543:         }
 5544:     }
 5545:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5546:                 "$env{'user.domain'}:$env{'user.name'}:".
 5547: 	        "rolesdef_$rolename=".
 5548:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 5549:     return reply($command,$env{'user.home'});
 5550:   } else {
 5551:     return 'refused';
 5552:   }
 5553: }
 5554: 
 5555: # ---------------- Make a metadata query against the network of library servers
 5556: 
 5557: sub metadata_query {
 5558:     my ($query,$custom,$customshow,$server_array)=@_;
 5559:     my %rhash;
 5560:     my %libserv = &all_library();
 5561:     my @server_list = (defined($server_array) ? @$server_array
 5562:                                               : keys(%libserv) );
 5563:     for my $server (@server_list) {
 5564: 	unless ($custom or $customshow) {
 5565: 	    my $reply=&reply("querysend:".&escape($query),$server);
 5566: 	    $rhash{$server}=$reply;
 5567: 	}
 5568: 	else {
 5569: 	    my $reply=&reply("querysend:".&escape($query).':'.
 5570: 			     &escape($custom).':'.&escape($customshow),
 5571: 			     $server);
 5572: 	    $rhash{$server}=$reply;
 5573: 	}
 5574:     }
 5575:     return \%rhash;
 5576: }
 5577: 
 5578: # ----------------------------------------- Send log queries and wait for reply
 5579: 
 5580: sub log_query {
 5581:     my ($uname,$udom,$query,%filters)=@_;
 5582:     my $uhome=&homeserver($uname,$udom);
 5583:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 5584:     my $uhost=&hostname($uhome);
 5585:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 5586:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 5587:                        $uhome);
 5588:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 5589:     return get_query_reply($queryid);
 5590: }
 5591: 
 5592: # -------------------------- Update MySQL table for portfolio file
 5593: 
 5594: sub update_portfolio_table {
 5595:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 5596:     if ($group ne '') {
 5597:         $file_name =~s /^\Q$group\E//;
 5598:     }
 5599:     my $homeserver = &homeserver($uname,$udom);
 5600:     my $queryid=
 5601:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 5602:                ':'.&escape($file_name).':'.$action,$homeserver);
 5603:     my $reply = &get_query_reply($queryid);
 5604:     return $reply;
 5605: }
 5606: 
 5607: # -------------------------- Update MySQL allusers table
 5608: 
 5609: sub update_allusers_table {
 5610:     my ($uname,$udom,$names) = @_;
 5611:     my $homeserver = &homeserver($uname,$udom);
 5612:     my $queryid=
 5613:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 5614:                'lastname='.&escape($names->{'lastname'}).'%%'.
 5615:                'firstname='.&escape($names->{'firstname'}).'%%'.
 5616:                'middlename='.&escape($names->{'middlename'}).'%%'.
 5617:                'generation='.&escape($names->{'generation'}).'%%'.
 5618:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 5619:                'id='.&escape($names->{'id'}),$homeserver);
 5620:     my $reply = &get_query_reply($queryid);
 5621:     return $reply;
 5622: }
 5623: 
 5624: # ------- Request retrieval of institutional classlists for course(s)
 5625: 
 5626: sub fetch_enrollment_query {
 5627:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 5628:     my $homeserver;
 5629:     my $maxtries = 1;
 5630:     if ($context eq 'automated') {
 5631:         $homeserver = $perlvar{'lonHostID'};
 5632:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 5633:     } else {
 5634:         $homeserver = &homeserver($cnum,$dom);
 5635:     }
 5636:     my $host=&hostname($homeserver);
 5637:     my $cmd = '';
 5638:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5639:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5640:     }
 5641:     $cmd =~ s/%%$//;
 5642:     $cmd = &escape($cmd);
 5643:     my $query = 'fetchenrollment';
 5644:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 5645:     unless ($queryid=~/^\Q$host\E\_/) { 
 5646:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 5647:         return 'error: '.$queryid;
 5648:     }
 5649:     my $reply = &get_query_reply($queryid);
 5650:     my $tries = 1;
 5651:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5652:         $reply = &get_query_reply($queryid);
 5653:         $tries ++;
 5654:     }
 5655:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5656:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5657:     } else {
 5658:         my @responses = split(/:/,$reply);
 5659:         if ($homeserver eq $perlvar{'lonHostID'}) {
 5660:             foreach my $line (@responses) {
 5661:                 my ($key,$value) = split(/=/,$line,2);
 5662:                 $$replyref{$key} = $value;
 5663:             }
 5664:         } else {
 5665:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 5666:             foreach my $line (@responses) {
 5667:                 my ($key,$value) = split(/=/,$line);
 5668:                 $$replyref{$key} = $value;
 5669:                 if ($value > 0) {
 5670:                     foreach my $item (@{$$affiliatesref{$key}}) {
 5671:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 5672:                         my $destname = $pathname.'/'.$filename;
 5673:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 5674:                         if ($xml_classlist =~ /^error/) {
 5675:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 5676:                         } else {
 5677:                             if ( open(FILE,">$destname") ) {
 5678:                                 print FILE &unescape($xml_classlist);
 5679:                                 close(FILE);
 5680:                             } else {
 5681:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 5682:                             }
 5683:                         }
 5684:                     }
 5685:                 }
 5686:             }
 5687:         }
 5688:         return 'ok';
 5689:     }
 5690:     return 'error';
 5691: }
 5692: 
 5693: sub get_query_reply {
 5694:     my $queryid=shift;
 5695:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 5696:     my $reply='';
 5697:     for (1..100) {
 5698: 	sleep 2;
 5699:         if (-e $replyfile.'.end') {
 5700: 	    if (open(my $fh,$replyfile)) {
 5701: 		$reply = join('',<$fh>);
 5702: 		close($fh);
 5703: 	   } else { return 'error: reply_file_error'; }
 5704:            return &unescape($reply);
 5705: 	}
 5706:     }
 5707:     return 'timeout:'.$queryid;
 5708: }
 5709: 
 5710: sub courselog_query {
 5711: #
 5712: # possible filters:
 5713: # url: url or symb
 5714: # username
 5715: # domain
 5716: # action: view, submit, grade
 5717: # start: timestamp
 5718: # end: timestamp
 5719: #
 5720:     my (%filters)=@_;
 5721:     unless ($env{'request.course.id'}) { return 'no_course'; }
 5722:     if ($filters{'url'}) {
 5723: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 5724:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 5725:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 5726:     }
 5727:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5728:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5729:     return &log_query($cname,$cdom,'courselog',%filters);
 5730: }
 5731: 
 5732: sub userlog_query {
 5733: #
 5734: # possible filters:
 5735: # action: log check role
 5736: # start: timestamp
 5737: # end: timestamp
 5738: #
 5739:     my ($uname,$udom,%filters)=@_;
 5740:     return &log_query($uname,$udom,'userlog',%filters);
 5741: }
 5742: 
 5743: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 5744: 
 5745: sub auto_run {
 5746:     my ($cnum,$cdom) = @_;
 5747:     my $response = 0;
 5748:     my $settings;
 5749:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 5750:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5751:         $settings = $domconfig{'autoenroll'};
 5752:         if ($settings->{'run'} eq '1') {
 5753:             $response = 1;
 5754:         }
 5755:     } else {
 5756:         my $homeserver;
 5757:         if (&is_course($cdom,$cnum)) {
 5758:             $homeserver = &homeserver($cnum,$cdom);
 5759:         } else {
 5760:             $homeserver = &domain($cdom,'primary');
 5761:         }
 5762:         if ($homeserver ne 'no_host') {
 5763:             $response = &reply('autorun:'.$cdom,$homeserver);
 5764:         }
 5765:     }
 5766:     return $response;
 5767: }
 5768: 
 5769: sub auto_get_sections {
 5770:     my ($cnum,$cdom,$inst_coursecode) = @_;
 5771:     my $homeserver;
 5772:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 5773:         $homeserver = &homeserver($cnum,$cdom);
 5774:     }
 5775:     if (!defined($homeserver)) { 
 5776:         if ($cdom =~ /^$match_domain$/) {
 5777:             $homeserver = &domain($cdom,'primary');
 5778:         }
 5779:     }
 5780:     my @secs;
 5781:     if (defined($homeserver)) {
 5782:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 5783:         unless ($response eq 'refused') {
 5784:             @secs = split(/:/,$response);
 5785:         }
 5786:     }
 5787:     return @secs;
 5788: }
 5789: 
 5790: sub auto_new_course {
 5791:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 5792:     my $homeserver = &homeserver($cnum,$cdom);
 5793:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 5794:     return $response;
 5795: }
 5796: 
 5797: sub auto_validate_courseID {
 5798:     my ($cnum,$cdom,$inst_course_id) = @_;
 5799:     my $homeserver = &homeserver($cnum,$cdom);
 5800:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5801:     return $response;
 5802: }
 5803: 
 5804: sub auto_validate_instcode {
 5805:     my ($cnum,$cdom,$instcode,$owner) = @_;
 5806:     my ($homeserver,$response);
 5807:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5808:         $homeserver = &homeserver($cnum,$cdom);
 5809:     }
 5810:     if (!defined($homeserver)) {
 5811:         if ($cdom =~ /^$match_domain$/) {
 5812:             $homeserver = &domain($cdom,'primary');
 5813:         }
 5814:     }
 5815:     my $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 5816:                            &escape($instcode).':'.&escape($owner),$homeserver));
 5817:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
 5818:     return ($outcome,$description);
 5819: }
 5820: 
 5821: sub auto_create_password {
 5822:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5823:     my ($homeserver,$response);
 5824:     my $create_passwd = 0;
 5825:     my $authchk = '';
 5826:     if ($udom =~ /^$match_domain$/) {
 5827:         $homeserver = &domain($udom,'primary');
 5828:     }
 5829:     if ($homeserver eq '') {
 5830:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5831:             $homeserver = &homeserver($cnum,$cdom);
 5832:         }
 5833:     }
 5834:     if ($homeserver eq '') {
 5835:         $authchk = 'nodomain';
 5836:     } else {
 5837:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5838:         if ($response eq 'refused') {
 5839:             $authchk = 'refused';
 5840:         } else {
 5841:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5842:         }
 5843:     }
 5844:     return ($authparam,$create_passwd,$authchk);
 5845: }
 5846: 
 5847: sub auto_photo_permission {
 5848:     my ($cnum,$cdom,$students) = @_;
 5849:     my $homeserver = &homeserver($cnum,$cdom);
 5850:     my ($outcome,$perm_reqd,$conditions) = 
 5851: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5852:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5853: 	return (undef,undef);
 5854:     }
 5855:     return ($outcome,$perm_reqd,$conditions);
 5856: }
 5857: 
 5858: sub auto_checkphotos {
 5859:     my ($uname,$udom,$pid) = @_;
 5860:     my $homeserver = &homeserver($uname,$udom);
 5861:     my ($result,$resulttype);
 5862:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5863: 				   &escape($uname).':'.&escape($pid),
 5864: 				   $homeserver));
 5865:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5866: 	return (undef,undef);
 5867:     }
 5868:     if ($outcome) {
 5869:         ($result,$resulttype) = split(/:/,$outcome);
 5870:     } 
 5871:     return ($result,$resulttype);
 5872: }
 5873: 
 5874: sub auto_photochoice {
 5875:     my ($cnum,$cdom) = @_;
 5876:     my $homeserver = &homeserver($cnum,$cdom);
 5877:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5878: 						       &escape($cdom),
 5879: 						       $homeserver)));
 5880:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5881: 	return (undef,undef);
 5882:     }
 5883:     return ($update,$comment);
 5884: }
 5885: 
 5886: sub auto_photoupdate {
 5887:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5888:     my $homeserver = &homeserver($cnum,$dom);
 5889:     my $host=&hostname($homeserver);
 5890:     my $cmd = '';
 5891:     my $maxtries = 1;
 5892:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5893:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5894:     }
 5895:     $cmd =~ s/%%$//;
 5896:     $cmd = &escape($cmd);
 5897:     my $query = 'institutionalphotos';
 5898:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5899:     unless ($queryid=~/^\Q$host\E\_/) {
 5900:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5901:         return 'error: '.$queryid;
 5902:     }
 5903:     my $reply = &get_query_reply($queryid);
 5904:     my $tries = 1;
 5905:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5906:         $reply = &get_query_reply($queryid);
 5907:         $tries ++;
 5908:     }
 5909:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5910:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5911:     } else {
 5912:         my @responses = split(/:/,$reply);
 5913:         my $outcome = shift(@responses); 
 5914:         foreach my $item (@responses) {
 5915:             my ($key,$value) = split(/=/,$item);
 5916:             $$photo{$key} = $value;
 5917:         }
 5918:         return $outcome;
 5919:     }
 5920:     return 'error';
 5921: }
 5922: 
 5923: sub auto_instcode_format {
 5924:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5925: 	$cat_order) = @_;
 5926:     my $courses = '';
 5927:     my @homeservers;
 5928:     if ($caller eq 'global') {
 5929: 	my %servers = &get_servers($codedom,'library');
 5930: 	foreach my $tryserver (keys(%servers)) {
 5931: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5932: 		push(@homeservers,$tryserver);
 5933: 	    }
 5934:         }
 5935:     } elsif ($caller eq 'requests') {
 5936:         if ($codedom =~ /^$match_domain$/) {
 5937:             my $chome = &domain($codedom,'primary');
 5938:             unless ($chome eq 'no_host') {
 5939:                 push(@homeservers,$chome);
 5940:             }
 5941:         }
 5942:     } else {
 5943:         push(@homeservers,&homeserver($caller,$codedom));
 5944:     }
 5945:     foreach my $code (keys(%{$instcodes})) {
 5946:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5947:     }
 5948:     chop($courses);
 5949:     my $ok_response = 0;
 5950:     my $response;
 5951:     while (@homeservers > 0 && $ok_response == 0) {
 5952:         my $server = shift(@homeservers); 
 5953:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5954:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5955:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5956: 		split(/:/,$response);
 5957:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5958:             push(@{$codetitles},&str2array($codetitles_str));
 5959:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5960:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5961:             $ok_response = 1;
 5962:         }
 5963:     }
 5964:     if ($ok_response) {
 5965:         return 'ok';
 5966:     } else {
 5967:         return $response;
 5968:     }
 5969: }
 5970: 
 5971: sub auto_instcode_defaults {
 5972:     my ($domain,$returnhash,$code_order) = @_;
 5973:     my @homeservers;
 5974: 
 5975:     my %servers = &get_servers($domain,'library');
 5976:     foreach my $tryserver (keys(%servers)) {
 5977: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5978: 	    push(@homeservers,$tryserver);
 5979: 	}
 5980:     }
 5981: 
 5982:     my $response;
 5983:     foreach my $server (@homeservers) {
 5984:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5985:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5986: 	
 5987: 	foreach my $pair (split(/\&/,$response)) {
 5988: 	    my ($name,$value)=split(/\=/,$pair);
 5989: 	    if ($name eq 'code_order') {
 5990: 		@{$code_order} = split(/\&/,&unescape($value));
 5991: 	    } else {
 5992: 		$returnhash->{&unescape($name)}=&unescape($value);
 5993: 	    }
 5994: 	}
 5995: 	return 'ok';
 5996:     }
 5997: 
 5998:     return $response;
 5999: }
 6000: 
 6001: sub auto_possible_instcodes {
 6002:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 6003:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 6004:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 6005:         return;
 6006:     }
 6007:     my (@homeservers,$uhome);
 6008:     if (defined(&domain($domain,'primary'))) {
 6009:         $uhome=&domain($domain,'primary');
 6010:         push(@homeservers,&domain($domain,'primary'));
 6011:     } else {
 6012:         my %servers = &get_servers($domain,'library');
 6013:         foreach my $tryserver (keys(%servers)) {
 6014:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 6015:                 push(@homeservers,$tryserver);
 6016:             }
 6017:         }
 6018:     }
 6019:     my $response;
 6020:     foreach my $server (@homeservers) {
 6021:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 6022:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 6023:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 6024:             split(':',$response);
 6025:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 6026:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 6027:         foreach my $item (split('&',$cat_title)) {   
 6028:             my ($name,$value)=split('=',$item);
 6029:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 6030:         }
 6031:         foreach my $item (split('&',$cat_order)) {
 6032:             my ($name,$value)=split('=',$item);
 6033:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 6034:         }
 6035:         return 'ok';
 6036:     }
 6037:     return $response;
 6038: }
 6039: 
 6040: sub auto_courserequest_checks {
 6041:     my ($dom) = @_;
 6042:     my ($homeserver,%validations);
 6043:     if ($dom =~ /^$match_domain$/) {
 6044:         $homeserver = &domain($dom,'primary');
 6045:     }
 6046:     unless ($homeserver eq 'no_host') {
 6047:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 6048:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 6049:             my @items = split(/&/,$response);
 6050:             foreach my $item (@items) {
 6051:                 my ($key,$value) = split('=',$item);
 6052:                 $validations{&unescape($key)} = &thaw_unescape($value);
 6053:             }
 6054:         }
 6055:     }
 6056:     return %validations; 
 6057: }
 6058: 
 6059: sub auto_courserequest_validation {
 6060:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 6061:     my ($homeserver,$response);
 6062:     if ($dom =~ /^$match_domain$/) {
 6063:         $homeserver = &domain($dom,'primary');
 6064:     }
 6065:     unless ($homeserver eq 'no_host') {  
 6066:           
 6067:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 6068:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 6069:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 6070:                                     $homeserver));
 6071:     }
 6072:     return $response;
 6073: }
 6074: 
 6075: sub auto_validate_class_sec {
 6076:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 6077:     my $homeserver = &homeserver($cnum,$cdom);
 6078:     my $ownerlist;
 6079:     if (ref($owners) eq 'ARRAY') {
 6080:         $ownerlist = join(',',@{$owners});
 6081:     } else {
 6082:         $ownerlist = $owners;
 6083:     }
 6084:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 6085:                         &escape($ownerlist).':'.$cdom,$homeserver);
 6086:     return $response;
 6087: }
 6088: 
 6089: # ------------------------------------------------------- Course Group routines
 6090: 
 6091: sub get_coursegroups {
 6092:     my ($cdom,$cnum,$group,$namespace) = @_;
 6093:     return(&dump($namespace,$cdom,$cnum,$group));
 6094: }
 6095: 
 6096: sub modify_coursegroup {
 6097:     my ($cdom,$cnum,$groupsettings) = @_;
 6098:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 6099: }
 6100: 
 6101: sub toggle_coursegroup_status {
 6102:     my ($cdom,$cnum,$group,$action) = @_;
 6103:     my ($from_namespace,$to_namespace);
 6104:     if ($action eq 'delete') {
 6105:         $from_namespace = 'coursegroups';
 6106:         $to_namespace = 'deleted_groups';
 6107:     } else {
 6108:         $from_namespace = 'deleted_groups';
 6109:         $to_namespace = 'coursegroups';
 6110:     }
 6111:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 6112:     if (my $tmp = &error(%curr_group)) {
 6113:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 6114:         return ('read error',$tmp);
 6115:     } else {
 6116:         my %savedsettings = %curr_group; 
 6117:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 6118:         my $deloutcome;
 6119:         if ($result eq 'ok') {
 6120:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 6121:         } else {
 6122:             return ('write error',$result);
 6123:         }
 6124:         if ($deloutcome eq 'ok') {
 6125:             return 'ok';
 6126:         } else {
 6127:             return ('delete error',$deloutcome);
 6128:         }
 6129:     }
 6130: }
 6131: 
 6132: sub modify_group_roles {
 6133:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 6134:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 6135:     my $role = 'gr/'.&escape($userprivs);
 6136:     my ($uname,$udom) = split(/:/,$user);
 6137:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 6138:     if ($result eq 'ok') {
 6139:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 6140:     }
 6141:     return $result;
 6142: }
 6143: 
 6144: sub modify_coursegroup_membership {
 6145:     my ($cdom,$cnum,$membership) = @_;
 6146:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 6147:     return $result;
 6148: }
 6149: 
 6150: sub get_active_groups {
 6151:     my ($udom,$uname,$cdom,$cnum) = @_;
 6152:     my $now = time;
 6153:     my %groups = ();
 6154:     foreach my $key (keys(%env)) {
 6155:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 6156:             my ($start,$end) = split(/\./,$env{$key});
 6157:             if (($end!=0) && ($end<$now)) { next; }
 6158:             if (($start!=0) && ($start>$now)) { next; }
 6159:             if ($1 eq $cdom && $2 eq $cnum) {
 6160:                 $groups{$3} = $env{$key} ;
 6161:             }
 6162:         }
 6163:     }
 6164:     return %groups;
 6165: }
 6166: 
 6167: sub get_group_membership {
 6168:     my ($cdom,$cnum,$group) = @_;
 6169:     return(&dump('groupmembership',$cdom,$cnum,$group));
 6170: }
 6171: 
 6172: sub get_users_groups {
 6173:     my ($udom,$uname,$courseid) = @_;
 6174:     my @usersgroups;
 6175:     my $cachetime=1800;
 6176: 
 6177:     my $hashid="$udom:$uname:$courseid";
 6178:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 6179:     if (defined($cached)) {
 6180:         @usersgroups = split(/:/,$grouplist);
 6181:     } else {  
 6182:         $grouplist = '';
 6183:         my $courseurl = &courseid_to_courseurl($courseid);
 6184:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 6185:         my $access_end = $env{'course.'.$courseid.
 6186:                               '.default_enrollment_end_date'};
 6187:         my $now = time;
 6188:         foreach my $key (keys(%roleshash)) {
 6189:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 6190:                 my $group = $1;
 6191:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 6192:                     my $start = $2;
 6193:                     my $end = $1;
 6194:                     if ($start == -1) { next; } # deleted from group
 6195:                     if (($start!=0) && ($start>$now)) { next; }
 6196:                     if (($end!=0) && ($end<$now)) {
 6197:                         if ($access_end && $access_end < $now) {
 6198:                             if ($access_end - $end < 86400) {
 6199:                                 push(@usersgroups,$group);
 6200:                             }
 6201:                         }
 6202:                         next;
 6203:                     }
 6204:                     push(@usersgroups,$group);
 6205:                 }
 6206:             }
 6207:         }
 6208:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 6209:         $grouplist = join(':',@usersgroups);
 6210:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 6211:     }
 6212:     return @usersgroups;
 6213: }
 6214: 
 6215: sub devalidate_getgroups_cache {
 6216:     my ($udom,$uname,$cdom,$cnum)=@_;
 6217:     my $courseid = $cdom.'_'.$cnum;
 6218: 
 6219:     my $hashid="$udom:$uname:$courseid";
 6220:     &devalidate_cache_new('getgroups',$hashid);
 6221: }
 6222: 
 6223: # ------------------------------------------------------------------ Plain Text
 6224: 
 6225: sub plaintext {
 6226:     my ($short,$type,$cid,$forcedefault) = @_;
 6227:     if ($short =~ m{^cr/}) {
 6228: 	return (split('/',$short))[-1];
 6229:     }
 6230:     if (!defined($cid)) {
 6231:         $cid = $env{'request.course.id'};
 6232:     }
 6233:     my %rolenames = (
 6234:                       Course    => 'std',
 6235:                       Community => 'alt1',
 6236:                     );
 6237:     if ($cid ne '') {
 6238:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 6239:             unless ($forcedefault) {
 6240:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 6241:                 &Apache::lonlocal::mt_escape(\$roletext);
 6242:                 return &Apache::lonlocal::mt($roletext);
 6243:             }
 6244:         }
 6245:     }
 6246:     if ((defined($type)) && (defined($rolenames{$type})) &&
 6247:         (defined($rolenames{$type})) && 
 6248:         (defined($prp{$short}{$rolenames{$type}}))) {
 6249:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 6250:     } elsif ($cid ne '') {
 6251:         my $crstype = $env{'course.'.$cid.'.type'};
 6252:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 6253:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 6254:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 6255:         }
 6256:     }
 6257:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 6258: }
 6259: 
 6260: # ----------------------------------------------------------------- Assign Role
 6261: 
 6262: sub assignrole {
 6263:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 6264:         $context)=@_;
 6265:     my $mrole;
 6266:     if ($role =~ /^cr\//) {
 6267:         my $cwosec=$url;
 6268:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 6269: 	unless (&allowed('ccr',$cwosec)) {
 6270:            my $refused = 1;
 6271:            if ($context eq 'requestcourses') {
 6272:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 6273:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 6274:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 6275:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 6276:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 6277:                            if ($crsenv{'internal.courseowner'} eq
 6278:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 6279:                                $refused = '';
 6280:                            }
 6281:                        }
 6282:                    }
 6283:                }
 6284:            }
 6285:            if ($refused) {
 6286:                &logthis('Refused custom assignrole: '.
 6287:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 6288:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 6289:                return 'refused';
 6290:            }
 6291:         }
 6292:         $mrole='cr';
 6293:     } elsif ($role =~ /^gr\//) {
 6294:         my $cwogrp=$url;
 6295:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 6296:         unless (&allowed('mdg',$cwogrp)) {
 6297:             &logthis('Refused group assignrole: '.
 6298:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 6299:                     $env{'user.name'}.' at '.$env{'user.domain'});
 6300:             return 'refused';
 6301:         }
 6302:         $mrole='gr';
 6303:     } else {
 6304:         my $cwosec=$url;
 6305:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 6306:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 6307:             my $refused;
 6308:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 6309:                 if (!(&allowed('c'.$role,$url))) {
 6310:                     $refused = 1;
 6311:                 }
 6312:             } else {
 6313:                 $refused = 1;
 6314:             }
 6315:             if ($refused) {
 6316:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 6317:                 if (!$selfenroll && $context eq 'course') {
 6318:                     my %crsenv;
 6319:                     if ($role eq 'cc' || $role eq 'co') {
 6320:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 6321:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 6322:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 6323:                                 if ($crsenv{'internal.courseowner'} eq 
 6324:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 6325:                                     $refused = '';
 6326:                                 }
 6327:                             }
 6328:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 6329:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 6330:                                 if ($crsenv{'internal.courseowner'} eq 
 6331:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 6332:                                     $refused = '';
 6333:                                 }
 6334:                             }
 6335:                         }
 6336:                     }
 6337:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6338:                     $refused = '';
 6339:                 } elsif ($context eq 'requestcourses') {
 6340:                     my @possroles = ('st','ta','ep','in','cc','co');
 6341:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 6342:                         my $wrongcc;
 6343:                         if ($cnum =~ /^$match_community$/) {
 6344:                             $wrongcc = 1 if ($role eq 'cc');
 6345:                         } else {
 6346:                             $wrongcc = 1 if ($role eq 'co');
 6347:                         }
 6348:                         unless ($wrongcc) {
 6349:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 6350:                             if ($crsenv{'internal.courseowner'} eq 
 6351:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 6352:                                 $refused = '';
 6353:                             }
 6354:                         }
 6355:                     }
 6356:                 }
 6357:                 if ($refused) {
 6358:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 6359:                              ' '.$role.' '.$end.' '.$start.' by '.
 6360: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 6361:                     return 'refused';
 6362:                 }
 6363:             }
 6364:         }
 6365:         $mrole=$role;
 6366:     }
 6367:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 6368:                 "$udom:$uname:$url".'_'."$mrole=$role";
 6369:     if ($end) { $command.='_'.$end; }
 6370:     if ($start) {
 6371: 	if ($end) { 
 6372:            $command.='_'.$start; 
 6373:         } else {
 6374:            $command.='_0_'.$start;
 6375:         }
 6376:     }
 6377:     my $origstart = $start;
 6378:     my $origend = $end;
 6379:     my $delflag;
 6380: # actually delete
 6381:     if ($deleteflag) {
 6382: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 6383: # modify command to delete the role
 6384:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 6385:                 "$udom:$uname:$url".'_'."$mrole";
 6386: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 6387: # set start and finish to negative values for userrolelog
 6388:            $start=-1;
 6389:            $end=-1;
 6390:            $delflag = 1;
 6391:         }
 6392:     }
 6393: # send command
 6394:     my $answer=&reply($command,&homeserver($uname,$udom));
 6395: # log new user role if status is ok
 6396:     if ($answer eq 'ok') {
 6397: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 6398: # for course roles, perform group memberships changes triggered by role change.
 6399:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 6400:         unless ($role =~ /^gr/) {
 6401:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 6402:                                              $origstart,$selfenroll,$context);
 6403:         }
 6404:         if ($role eq 'cc') {
 6405:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 6406:         }
 6407:     }
 6408:     return $answer;
 6409: }
 6410: 
 6411: sub autoupdate_coowners {
 6412:     my ($url,$end,$start,$uname,$udom) = @_;
 6413:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 6414:     if (($cdom ne '') && ($cnum ne '')) {
 6415:         my $now = time;
 6416:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 6417:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 6418:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 6419:             my $instcode = $coursehash{'internal.coursecode'};
 6420:             if ($instcode ne '') {
 6421:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 6422:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 6423:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 6424:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 6425:                         if ($result eq 'valid') {
 6426:                             if ($coursehash{'internal.co-owners'}) {
 6427:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 6428:                                     push(@newcoowners,$coowner);
 6429:                                 }
 6430:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 6431:                                     push(@newcoowners,$uname.':'.$udom);
 6432:                                 }
 6433:                                 @newcoowners = sort(@newcoowners);
 6434:                             } else {
 6435:                                 push(@newcoowners,$uname.':'.$udom);
 6436:                             }
 6437:                         } else {
 6438:                             if ($coursehash{'internal.co-owners'}) {
 6439:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 6440:                                     unless ($coowner eq $uname.':'.$udom) {
 6441:                                         push(@newcoowners,$coowner);
 6442:                                     }
 6443:                                 }
 6444:                                 unless (@newcoowners > 0) {
 6445:                                     $delcoowners = 1;
 6446:                                     $coowners = '';
 6447:                                 }
 6448:                             }
 6449:                         }
 6450:                         if (@newcoowners || $delcoowners) {
 6451:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 6452:                                             $delcoowners,@newcoowners);
 6453:                         }
 6454:                     }
 6455:                 }
 6456:             }
 6457:         }
 6458:     }
 6459: }
 6460: 
 6461: sub store_coowners {
 6462:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 6463:     my $cid = $cdom.'_'.$cnum;
 6464:     my ($coowners,$delresult,$putresult);
 6465:     if (@newcoowners) {
 6466:         $coowners = join(',',@newcoowners);
 6467:         my %coownershash = (
 6468:                             'internal.co-owners' => $coowners,
 6469:                            );
 6470:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 6471:         if ($putresult eq 'ok') {
 6472:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 6473:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 6474:             }
 6475:         }
 6476:     }
 6477:     if ($delcoowners) {
 6478:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 6479:         if ($delresult eq 'ok') {
 6480:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 6481:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 6482:             }
 6483:         }
 6484:     }
 6485:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 6486:         my %crsinfo =
 6487:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6488:         if (ref($crsinfo{$cid}) eq 'HASH') {
 6489:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 6490:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 6491:         }
 6492:     }
 6493: }
 6494: 
 6495: # -------------------------------------------------- Modify user authentication
 6496: # Overrides without validation
 6497: 
 6498: sub modifyuserauth {
 6499:     my ($udom,$uname,$umode,$upass)=@_;
 6500:     my $uhome=&homeserver($uname,$udom);
 6501:     unless (&allowed('mau',$udom)) { return 'refused'; }
 6502:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 6503:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 6504:              ' in domain '.$env{'request.role.domain'});  
 6505:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 6506: 		     &escape($upass),$uhome);
 6507:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 6508:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 6509:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 6510:     &log($udom,,$uname,$uhome,
 6511:         'Authentication changed by '.$env{'user.domain'}.', '.
 6512:                                      $env{'user.name'}.', '.$umode.
 6513:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 6514:     unless ($reply eq 'ok') {
 6515:         &logthis('Authentication mode error: '.$reply);
 6516: 	return 'error: '.$reply;
 6517:     }   
 6518:     return 'ok';
 6519: }
 6520: 
 6521: # --------------------------------------------------------------- Modify a user
 6522: 
 6523: sub modifyuser {
 6524:     my ($udom,    $uname, $uid,
 6525:         $umode,   $upass, $first,
 6526:         $middle,  $last,  $gene,
 6527:         $forceid, $desiredhome, $email, $inststatus)=@_;
 6528:     $udom= &LONCAPA::clean_domain($udom);
 6529:     $uname=&LONCAPA::clean_username($uname);
 6530:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 6531:              $umode.', '.$first.', '.$middle.', '.
 6532: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 6533:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 6534:                                      ' desiredhome not specified'). 
 6535:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 6536:              ' in domain '.$env{'request.role.domain'});
 6537:     my $uhome=&homeserver($uname,$udom,'true');
 6538: # ----------------------------------------------------------------- Create User
 6539:     if (($uhome eq 'no_host') && 
 6540: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 6541:         my $unhome='';
 6542:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 6543:             $unhome = $desiredhome;
 6544: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 6545: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 6546:         } else { # load balancing routine for determining $unhome
 6547:             my $loadm=10000000;
 6548: 	    my %servers = &get_servers($udom,'library');
 6549: 	    foreach my $tryserver (keys(%servers)) {
 6550: 		my $answer=reply('load',$tryserver);
 6551: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 6552: 		    $loadm=$answer;
 6553: 		    $unhome=$tryserver;
 6554: 		}
 6555: 	    }
 6556:         }
 6557:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 6558: 	    return 'error: unable to find a home server for '.$uname.
 6559:                    ' in domain '.$udom;
 6560:         }
 6561:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 6562:                          &escape($upass),$unhome);
 6563: 	unless ($reply eq 'ok') {
 6564:             return 'error: '.$reply;
 6565:         }   
 6566:         $uhome=&homeserver($uname,$udom,'true');
 6567:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 6568: 	    return 'error: unable verify users home machine.';
 6569:         }
 6570:     }   # End of creation of new user
 6571: # ---------------------------------------------------------------------- Add ID
 6572:     if ($uid) {
 6573:        $uid=~tr/A-Z/a-z/;
 6574:        my %uidhash=&idrget($udom,$uname);
 6575:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 6576:          && (!$forceid)) {
 6577: 	  unless ($uid eq $uidhash{$uname}) {
 6578: 	      return 'error: user id "'.$uid.'" does not match '.
 6579:                   'current user id "'.$uidhash{$uname}.'".';
 6580:           }
 6581:        } else {
 6582: 	  &idput($udom,($uname => $uid));
 6583:        }
 6584:     }
 6585: # -------------------------------------------------------------- Add names, etc
 6586:     my @tmp=&get('environment',
 6587: 		   ['firstname','middlename','lastname','generation','id',
 6588:                     'permanentemail','inststatus'],
 6589: 		   $udom,$uname);
 6590:     my %names;
 6591:     if ($tmp[0] =~ m/^error:.*/) { 
 6592:         %names=(); 
 6593:     } else {
 6594:         %names = @tmp;
 6595:     }
 6596: #
 6597: # Make sure to not trash student environment if instructor does not bother
 6598: # to supply name and email information
 6599: #
 6600:     if ($first)  { $names{'firstname'}  = $first; }
 6601:     if (defined($middle)) { $names{'middlename'} = $middle; }
 6602:     if ($last)   { $names{'lastname'}   = $last; }
 6603:     if (defined($gene))   { $names{'generation'} = $gene; }
 6604:     if ($email) {
 6605:        $email=~s/[^\w\@\.\-\,]//gs;
 6606:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 6607:     }
 6608:     if ($uid) { $names{'id'}  = $uid; }
 6609:     if (defined($inststatus)) {
 6610:         $names{'inststatus'} = '';
 6611:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 6612:         if (ref($usertypes) eq 'HASH') {
 6613:             my @okstatuses; 
 6614:             foreach my $item (split(/:/,$inststatus)) {
 6615:                 if (defined($usertypes->{$item})) {
 6616:                     push(@okstatuses,$item);  
 6617:                 }
 6618:             }
 6619:             if (@okstatuses) {
 6620:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 6621:             }
 6622:         }
 6623:     }
 6624:     my $reply = &put('environment', \%names, $udom,$uname);
 6625:     if ($reply ne 'ok') { return 'error: '.$reply; }
 6626:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 6627:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 6628:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 6629:                  $umode.', '.$first.', '.$middle.', '.
 6630: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
 6631:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 6632:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 6633:     } else {
 6634:         $logmsg .= ' during self creation';
 6635:     }
 6636:     &logthis($logmsg);
 6637:     return 'ok';
 6638: }
 6639: 
 6640: # -------------------------------------------------------------- Modify student
 6641: 
 6642: sub modifystudent {
 6643:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 6644:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 6645:         $selfenroll,$context,$inststatus)=@_;
 6646:     if (!$cid) {
 6647: 	unless ($cid=$env{'request.course.id'}) {
 6648: 	    return 'not_in_class';
 6649: 	}
 6650:     }
 6651: # --------------------------------------------------------------- Make the user
 6652:     my $reply=&modifyuser
 6653: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 6654:          $desiredhome,$email,$inststatus);
 6655:     unless ($reply eq 'ok') { return $reply; }
 6656:     # This will cause &modify_student_enrollment to get the uid from the
 6657:     # students environment
 6658:     $uid = undef if (!$forceid);
 6659:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 6660: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 6661:     return $reply;
 6662: }
 6663: 
 6664: sub modify_student_enrollment {
 6665:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 6666:     my ($cdom,$cnum,$chome);
 6667:     if (!$cid) {
 6668: 	unless ($cid=$env{'request.course.id'}) {
 6669: 	    return 'not_in_class';
 6670: 	}
 6671: 	$cdom=$env{'course.'.$cid.'.domain'};
 6672: 	$cnum=$env{'course.'.$cid.'.num'};
 6673:     } else {
 6674: 	($cdom,$cnum)=split(/_/,$cid);
 6675:     }
 6676:     $chome=$env{'course.'.$cid.'.home'};
 6677:     if (!$chome) {
 6678: 	$chome=&homeserver($cnum,$cdom);
 6679:     }
 6680:     if (!$chome) { return 'unknown_course'; }
 6681:     # Make sure the user exists
 6682:     my $uhome=&homeserver($uname,$udom);
 6683:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6684: 	return 'error: no such user';
 6685:     }
 6686:     # Get student data if we were not given enough information
 6687:     if (!defined($first)  || $first  eq '' || 
 6688:         !defined($last)   || $last   eq '' || 
 6689:         !defined($uid)    || $uid    eq '' || 
 6690:         !defined($middle) || $middle eq '' || 
 6691:         !defined($gene)   || $gene   eq '') {
 6692:         # They did not supply us with enough data to enroll the student, so
 6693:         # we need to pick up more information.
 6694:         my %tmp = &get('environment',
 6695:                        ['firstname','middlename','lastname', 'generation','id']
 6696:                        ,$udom,$uname);
 6697: 
 6698:         #foreach my $key (keys(%tmp)) {
 6699:         #    &logthis("key $key = ".$tmp{$key});
 6700:         #}
 6701:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 6702:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 6703:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 6704:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 6705:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 6706:     }
 6707:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 6708:     my $reply=cput('classlist',
 6709: 		   {"$uname:$udom" => 
 6710: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 6711: 		   $cdom,$cnum);
 6712:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 6713: 	return 'error: '.$reply;
 6714:     } else {
 6715: 	&devalidate_getsection_cache($udom,$uname,$cid);
 6716:     }
 6717:     # Add student role to user
 6718:     my $uurl='/'.$cid;
 6719:     $uurl=~s/\_/\//g;
 6720:     if ($usec) {
 6721: 	$uurl.='/'.$usec;
 6722:     }
 6723:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 6724: }
 6725: 
 6726: sub format_name {
 6727:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 6728:     my $name;
 6729:     if ($first ne 'lastname') {
 6730: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 6731:     } else {
 6732: 	if ($lastname=~/\S/) {
 6733: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 6734: 	    $name=~s/\s+,/,/;
 6735: 	} else {
 6736: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 6737: 	}
 6738:     }
 6739:     $name=~s/^\s+//;
 6740:     $name=~s/\s+$//;
 6741:     $name=~s/\s+/ /g;
 6742:     return $name;
 6743: }
 6744: 
 6745: # ------------------------------------------------- Write to course preferences
 6746: 
 6747: sub writecoursepref {
 6748:     my ($courseid,%prefs)=@_;
 6749:     $courseid=~s/^\///;
 6750:     $courseid=~s/\_/\//g;
 6751:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6752:     my $chome=homeserver($cnum,$cdomain);
 6753:     if (($chome eq '') || ($chome eq 'no_host')) { 
 6754: 	return 'error: no such course';
 6755:     }
 6756:     my $cstring='';
 6757:     foreach my $pref (keys(%prefs)) {
 6758: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 6759:     }
 6760:     $cstring=~s/\&$//;
 6761:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 6762: }
 6763: 
 6764: # ---------------------------------------------------------- Make/modify course
 6765: 
 6766: sub createcourse {
 6767:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 6768:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 6769:     $url=&declutter($url);
 6770:     my $cid='';
 6771:     if ($context eq 'requestcourses') {
 6772:         my $can_create = 0;
 6773:         my ($ownername,$ownerdom) = split(':',$course_owner);
 6774:         if ($udom eq $ownerdom) {
 6775:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 6776:                                   $context)) {
 6777:                 $can_create = 1;
 6778:             }
 6779:         } else {
 6780:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 6781:                                            $category);
 6782:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 6783:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 6784:                 if (@curr > 0) {
 6785:                     my @options = qw(approval validate autolimit);
 6786:                     my $optregex = join('|',@options);
 6787:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 6788:                         $can_create = 1;
 6789:                     }
 6790:                 }
 6791:             }
 6792:         }
 6793:         if ($can_create) {
 6794:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 6795:                 unless (&allowed('ccc',$udom)) {
 6796:                     return 'refused'; 
 6797:                 }
 6798:             }
 6799:         } else {
 6800:             return 'refused';
 6801:         }
 6802:     } elsif (!&allowed('ccc',$udom)) {
 6803:         return 'refused';
 6804:     }
 6805: # --------------------------------------------------------------- Get Unique ID
 6806:     my $uname;
 6807:     if ($cnum =~ /^$match_courseid$/) {
 6808:         my $chome=&homeserver($cnum,$udom,'true');
 6809:         if (($chome eq '') || ($chome eq 'no_host')) {
 6810:             $uname = $cnum;
 6811:         } else {
 6812:             $uname = &generate_coursenum($udom,$crstype);
 6813:         }
 6814:     } else {
 6815:         $uname = &generate_coursenum($udom,$crstype);
 6816:     }
 6817:     return $uname if ($uname =~ /^error/);
 6818: # -------------------------------------------------- Check supplied server name
 6819:     if (!defined($course_server)) {
 6820:         if (defined(&domain($udom,'primary'))) {
 6821:             $course_server = &domain($udom,'primary');
 6822:         } else {
 6823:             $course_server = $env{'user.home'}; 
 6824:         }
 6825:     }
 6826:     my %host_servers =
 6827:         &Apache::lonnet::get_servers($udom,'library');
 6828:     unless ($host_servers{$course_server}) {
 6829:         return 'error: invalid home server for course: '.$course_server;
 6830:     }
 6831: # ------------------------------------------------------------- Make the course
 6832:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 6833:                       $course_server);
 6834:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 6835:     my $uhome=&homeserver($uname,$udom,'true');
 6836:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6837: 	return 'error: no such course';
 6838:     }
 6839: # ----------------------------------------------------------------- Course made
 6840: # log existence
 6841:     my $now = time;
 6842:     my $newcourse = {
 6843:                     $udom.'_'.$uname => {
 6844:                                      description => $description,
 6845:                                      inst_code   => $inst_code,
 6846:                                      owner       => $course_owner,
 6847:                                      type        => $crstype,
 6848:                                      creator     => $env{'user.name'}.':'.
 6849:                                                     $env{'user.domain'},
 6850:                                      created     => $now,
 6851:                                      context     => $context,
 6852:                                                 },
 6853:                     };
 6854:     &courseidput($udom,$newcourse,$uhome,'notime');
 6855: # set toplevel url
 6856:     my $topurl=$url;
 6857:     unless ($nonstandard) {
 6858: # ------------------------------------------ For standard courses, make top url
 6859:         my $mapurl=&clutter($url);
 6860:         if ($mapurl eq '/res/') { $mapurl=''; }
 6861:         $env{'form.initmap'}=(<<ENDINITMAP);
 6862: <map>
 6863: <resource id="1" type="start"></resource>
 6864: <resource id="2" src="$mapurl"></resource>
 6865: <resource id="3" type="finish"></resource>
 6866: <link index="1" from="1" to="2"></link>
 6867: <link index="2" from="2" to="3"></link>
 6868: </map>
 6869: ENDINITMAP
 6870:         $topurl=&declutter(
 6871:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 6872:                           );
 6873:     }
 6874: # ----------------------------------------------------------- Write preferences
 6875:     &writecoursepref($udom.'_'.$uname,
 6876:                      ('description'              => $description,
 6877:                       'url'                      => $topurl,
 6878:                       'internal.creator'         => $env{'user.name'}.':'.
 6879:                                                     $env{'user.domain'},
 6880:                       'internal.created'         => $now,
 6881:                       'internal.creationcontext' => $context)
 6882:                     );
 6883:     return '/'.$udom.'/'.$uname;
 6884: }
 6885: 
 6886: # ------------------------------------------------------------------- Create ID
 6887: sub generate_coursenum {
 6888:     my ($udom,$crstype) = @_;
 6889:     my $domdesc = &domain($udom);
 6890:     return 'error: invalid domain' if ($domdesc eq '');
 6891:     my $first;
 6892:     if ($crstype eq 'Community') {
 6893:         $first = '0';
 6894:     } else {
 6895:         $first = int(1+rand(9)); 
 6896:     } 
 6897:     my $uname=$first.
 6898:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6899:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6900:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6901: # ----------------------------------------------- Make sure that does not exist
 6902:     my $uhome=&homeserver($uname,$udom,'true');
 6903:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6904:         if ($crstype eq 'Community') {
 6905:             $first = '0';
 6906:         } else {
 6907:             $first = int(1+rand(9));
 6908:         }
 6909:         $uname=$first.
 6910:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6911:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6912:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6913:         $uhome=&homeserver($uname,$udom,'true');
 6914:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6915:             return 'error: unable to generate unique course-ID';
 6916:         }
 6917:     }
 6918:     return $uname;
 6919: }
 6920: 
 6921: sub is_course {
 6922:     my ($cdom,$cnum) = @_;
 6923:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 6924: 				undef,'.');
 6925:     if (exists($courses{$cdom.'_'.$cnum})) {
 6926:         return 1;
 6927:     }
 6928:     return 0;
 6929: }
 6930: 
 6931: sub store_userdata {
 6932:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 6933:     my $result;
 6934:     if ($datakey ne '') {
 6935:         if (ref($storehash) eq 'HASH') {
 6936:             if ($udom eq '' || $uname eq '') {
 6937:                 $udom = $env{'user.domain'};
 6938:                 $uname = $env{'user.name'};
 6939:             }
 6940:             my $uhome=&homeserver($uname,$udom);
 6941:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 6942:                 $result = 'error: no_host';
 6943:             } else {
 6944:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 6945:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 6946: 
 6947:                 my $namevalue='';
 6948:                 foreach my $key (keys(%{$storehash})) {
 6949:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6950:                 }
 6951:                 $namevalue=~s/\&$//;
 6952:                 $result =  &reply("store:$env{'user.domain'}:$env{'user.name'}:".
 6953:                                   "$namespace:$datakey:$namevalue",$uhome);
 6954:             }
 6955:         } else {
 6956:             $result = 'error: data to store was not a hash reference'; 
 6957:         }
 6958:     } else {
 6959:         $result= 'error: invalid requestkey'; 
 6960:     }
 6961:     return $result;
 6962: }
 6963: 
 6964: # ---------------------------------------------------------- Assign Custom Role
 6965: 
 6966: sub assigncustomrole {
 6967:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 6968:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 6969:                        $end,$start,$deleteflag,$selfenroll,$context);
 6970: }
 6971: 
 6972: # ----------------------------------------------------------------- Revoke Role
 6973: 
 6974: sub revokerole {
 6975:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 6976:     my $now=time;
 6977:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 6978: }
 6979: 
 6980: # ---------------------------------------------------------- Revoke Custom Role
 6981: 
 6982: sub revokecustomrole {
 6983:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 6984:     my $now=time;
 6985:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 6986:            $deleteflag,$selfenroll,$context);
 6987: }
 6988: 
 6989: # ------------------------------------------------------------ Disk usage
 6990: sub diskusage {
 6991:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 6992:     $directorypath =~ s/\/$//;
 6993:     my $listing=&reply('du2:'.&escape($directorypath).':'
 6994:                        .&escape($getpropath).':'.&escape($uname).':'
 6995:                        .&escape($udom),homeserver($uname,$udom));
 6996:     if ($listing eq 'unknown_cmd') {
 6997:         if ($getpropath) {
 6998:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 6999:         }
 7000:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 7001:     }
 7002:     return $listing;
 7003: }
 7004: 
 7005: sub is_locked {
 7006:     my ($file_name, $domain, $user) = @_;
 7007:     my @check;
 7008:     my $is_locked;
 7009:     push @check, $file_name;
 7010:     my %locked = &get('file_permissions',\@check,
 7011: 		      $env{'user.domain'},$env{'user.name'});
 7012:     my ($tmp)=keys(%locked);
 7013:     if ($tmp=~/^error:/) { undef(%locked); }
 7014:     
 7015:     if (ref($locked{$file_name}) eq 'ARRAY') {
 7016:         $is_locked = 'false';
 7017:         foreach my $entry (@{$locked{$file_name}}) {
 7018:            if (ref($entry) eq 'ARRAY') { 
 7019:                $is_locked = 'true';
 7020:                last;
 7021:            }
 7022:        }
 7023:     } else {
 7024:         $is_locked = 'false';
 7025:     }
 7026: }
 7027: 
 7028: sub declutter_portfile {
 7029:     my ($file) = @_;
 7030:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 7031:     return $file;
 7032: }
 7033: 
 7034: # ------------------------------------------------------------- Mark as Read Only
 7035: 
 7036: sub mark_as_readonly {
 7037:     my ($domain,$user,$files,$what) = @_;
 7038:     my %current_permissions = &dump('file_permissions',$domain,$user);
 7039:     my ($tmp)=keys(%current_permissions);
 7040:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 7041:     foreach my $file (@{$files}) {
 7042: 	$file = &declutter_portfile($file);
 7043:         push(@{$current_permissions{$file}},$what);
 7044:     }
 7045:     &put('file_permissions',\%current_permissions,$domain,$user);
 7046:     return;
 7047: }
 7048: 
 7049: # ------------------------------------------------------------Save Selected Files
 7050: 
 7051: sub save_selected_files {
 7052:     my ($user, $path, @files) = @_;
 7053:     my $filename = $user."savedfiles";
 7054:     my @other_files = &files_not_in_path($user, $path);
 7055:     open (OUT, '>'.$tmpdir.$filename);
 7056:     foreach my $file (@files) {
 7057:         print (OUT $env{'form.currentpath'}.$file."\n");
 7058:     }
 7059:     foreach my $file (@other_files) {
 7060:         print (OUT $file."\n");
 7061:     }
 7062:     close (OUT);
 7063:     return 'ok';
 7064: }
 7065: 
 7066: sub clear_selected_files {
 7067:     my ($user) = @_;
 7068:     my $filename = $user."savedfiles";
 7069:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 7070:     print (OUT undef);
 7071:     close (OUT);
 7072:     return ("ok");    
 7073: }
 7074: 
 7075: sub files_in_path {
 7076:     my ($user, $path) = @_;
 7077:     my $filename = $user."savedfiles";
 7078:     my %return_files;
 7079:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 7080:     while (my $line_in = <IN>) {
 7081:         chomp ($line_in);
 7082:         my @paths_and_file = split (m!/!, $line_in);
 7083:         my $file_part = pop (@paths_and_file);
 7084:         my $path_part = join ('/', @paths_and_file);
 7085:         $path_part.='/';
 7086:         my $path_and_file = $path_part.$file_part;
 7087:         if ($path_part eq $path) {
 7088:             $return_files{$file_part}= 'selected';
 7089:         }
 7090:     }
 7091:     close (IN);
 7092:     return (\%return_files);
 7093: }
 7094: 
 7095: # called in portfolio select mode, to show files selected NOT in current directory
 7096: sub files_not_in_path {
 7097:     my ($user, $path) = @_;
 7098:     my $filename = $user."savedfiles";
 7099:     my @return_files;
 7100:     my $path_part;
 7101:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 7102:     while (my $line = <IN>) {
 7103:         #ok, I know it's clunky, but I want it to work
 7104:         my @paths_and_file = split(m|/|, $line);
 7105:         my $file_part = pop(@paths_and_file);
 7106:         chomp($file_part);
 7107:         my $path_part = join('/', @paths_and_file);
 7108:         $path_part .= '/';
 7109:         my $path_and_file = $path_part.$file_part;
 7110:         if ($path_part ne $path) {
 7111:             push(@return_files, ($path_and_file));
 7112:         }
 7113:     }
 7114:     close(OUT);
 7115:     return (@return_files);
 7116: }
 7117: 
 7118: #----------------------------------------------Get portfolio file permissions
 7119: 
 7120: sub get_portfile_permissions {
 7121:     my ($domain,$user) = @_;
 7122:     my %current_permissions = &dump('file_permissions',$domain,$user);
 7123:     my ($tmp)=keys(%current_permissions);
 7124:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 7125:     return \%current_permissions;
 7126: }
 7127: 
 7128: #---------------------------------------------Get portfolio file access controls
 7129: 
 7130: sub get_access_controls {
 7131:     my ($current_permissions,$group,$file) = @_;
 7132:     my %access;
 7133:     my $real_file = $file;
 7134:     $file =~ s/\.meta$//;
 7135:     if (defined($file)) {
 7136:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 7137:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 7138:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 7139:             }
 7140:         }
 7141:     } else {
 7142:         foreach my $key (keys(%{$current_permissions})) {
 7143:             if ($key =~ /\0accesscontrol$/) {
 7144:                 if (defined($group)) {
 7145:                     if ($key !~ m-^\Q$group\E/-) {
 7146:                         next;
 7147:                     }
 7148:                 }
 7149:                 my ($fullpath) = split(/\0/,$key);
 7150:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 7151:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 7152:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 7153:                     }
 7154:                 }
 7155:             }
 7156:         }
 7157:     }
 7158:     return %access;
 7159: }
 7160: 
 7161: sub modify_access_controls {
 7162:     my ($file_name,$changes,$domain,$user)=@_;
 7163:     my ($outcome,$deloutcome);
 7164:     my %store_permissions;
 7165:     my %new_values;
 7166:     my %new_control;
 7167:     my %translation;
 7168:     my @deletions = ();
 7169:     my $now = time;
 7170:     if (exists($$changes{'activate'})) {
 7171:         if (ref($$changes{'activate'}) eq 'HASH') {
 7172:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 7173:             my $numnew = scalar(@newitems);
 7174:             for (my $i=0; $i<$numnew; $i++) {
 7175:                 my $newkey = $newitems[$i];
 7176:                 my $newid = &Apache::loncommon::get_cgi_id();
 7177:                 if ($newkey =~ /^\d+:/) { 
 7178:                     $newkey =~ s/^(\d+)/$newid/;
 7179:                     $translation{$1} = $newid;
 7180:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 7181:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 7182:                     $translation{$1} = $newid;
 7183:                 }
 7184:                 $new_values{$file_name."\0".$newkey} = 
 7185:                                           $$changes{'activate'}{$newitems[$i]};
 7186:                 $new_control{$newkey} = $now;
 7187:             }
 7188:         }
 7189:     }
 7190:     my %todelete;
 7191:     my %changed_items;
 7192:     foreach my $action ('delete','update') {
 7193:         if (exists($$changes{$action})) {
 7194:             if (ref($$changes{$action}) eq 'HASH') {
 7195:                 foreach my $key (keys(%{$$changes{$action}})) {
 7196:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 7197:                     if ($action eq 'delete') { 
 7198:                         $todelete{$itemnum} = 1;
 7199:                     } else {
 7200:                         $changed_items{$itemnum} = $key;
 7201:                     }
 7202:                 }
 7203:             }
 7204:         }
 7205:     }
 7206:     # get lock on access controls for file.
 7207:     my $lockhash = {
 7208:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 7209:                                                        ':'.$env{'user.domain'},
 7210:                    }; 
 7211:     my $tries = 0;
 7212:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 7213:    
 7214:     while (($gotlock ne 'ok') && $tries <3) {
 7215:         $tries ++;
 7216:         sleep 1;
 7217:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 7218:     }
 7219:     if ($gotlock eq 'ok') {
 7220:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 7221:         my ($tmp)=keys(%curr_permissions);
 7222:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 7223:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 7224:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 7225:             if (ref($curr_controls) eq 'HASH') {
 7226:                 foreach my $control_item (keys(%{$curr_controls})) {
 7227:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 7228:                     if (defined($todelete{$itemnum})) {
 7229:                         push(@deletions,$file_name."\0".$control_item);
 7230:                     } else {
 7231:                         if (defined($changed_items{$itemnum})) {
 7232:                             $new_control{$changed_items{$itemnum}} = $now;
 7233:                             push(@deletions,$file_name."\0".$control_item);
 7234:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 7235:                         } else {
 7236:                             $new_control{$control_item} = $$curr_controls{$control_item};
 7237:                         }
 7238:                     }
 7239:                 }
 7240:             }
 7241:         }
 7242:         my ($group);
 7243:         if (&is_course($domain,$user)) {
 7244:             ($group,my $file) = split(/\//,$file_name,2);
 7245:         }
 7246:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 7247:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 7248:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 7249:         #  remove lock
 7250:         my @del_lock = ($file_name."\0".'locked_access_records');
 7251:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 7252:         my $sqlresult =
 7253:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 7254:                                     $group);
 7255:     } else {
 7256:         $outcome = "error: could not obtain lockfile\n";  
 7257:     }
 7258:     return ($outcome,$deloutcome,\%new_values,\%translation);
 7259: }
 7260: 
 7261: sub make_public_indefinitely {
 7262:     my ($requrl) = @_;
 7263:     my $now = time;
 7264:     my $action = 'activate';
 7265:     my $aclnum = 0;
 7266:     if (&is_portfolio_url($requrl)) {
 7267:         my (undef,$udom,$unum,$file_name,$group) =
 7268:             &parse_portfolio_url($requrl);
 7269:         my $current_perms = &get_portfile_permissions($udom,$unum);
 7270:         my %access_controls = &get_access_controls($current_perms,
 7271:                                                    $group,$file_name);
 7272:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 7273:             my ($num,$scope,$end,$start) = 
 7274:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7275:             if ($scope eq 'public') {
 7276:                 if ($start <= $now && $end == 0) {
 7277:                     $action = 'none';
 7278:                 } else {
 7279:                     $action = 'update';
 7280:                     $aclnum = $num;
 7281:                 }
 7282:                 last;
 7283:             }
 7284:         }
 7285:         if ($action eq 'none') {
 7286:              return 'ok';
 7287:         } else {
 7288:             my %changes;
 7289:             my $newend = 0;
 7290:             my $newstart = $now;
 7291:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 7292:             $changes{$action}{$newkey} = {
 7293:                 type => 'public',
 7294:                 time => {
 7295:                     start => $newstart,
 7296:                     end   => $newend,
 7297:                 },
 7298:             };
 7299:             my ($outcome,$deloutcome,$new_values,$translation) =
 7300:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 7301:             return $outcome;
 7302:         }
 7303:     } else {
 7304:         return 'invalid';
 7305:     }
 7306: }
 7307: 
 7308: #------------------------------------------------------Get Marked as Read Only
 7309: 
 7310: sub get_marked_as_readonly {
 7311:     my ($domain,$user,$what,$group) = @_;
 7312:     my $current_permissions = &get_portfile_permissions($domain,$user);
 7313:     my @readonly_files;
 7314:     my $cmp1=$what;
 7315:     if (ref($what)) { $cmp1=join('',@{$what}) };
 7316:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 7317:         if (defined($group)) {
 7318:             if ($file_name !~ m-^\Q$group\E/-) {
 7319:                 next;
 7320:             }
 7321:         }
 7322:         if (ref($value) eq "ARRAY"){
 7323:             foreach my $stored_what (@{$value}) {
 7324:                 my $cmp2=$stored_what;
 7325:                 if (ref($stored_what) eq 'ARRAY') {
 7326:                     $cmp2=join('',@{$stored_what});
 7327:                 }
 7328:                 if ($cmp1 eq $cmp2) {
 7329:                     push(@readonly_files, $file_name);
 7330:                     last;
 7331:                 } elsif (!defined($what)) {
 7332:                     push(@readonly_files, $file_name);
 7333:                     last;
 7334:                 }
 7335:             }
 7336:         }
 7337:     }
 7338:     return @readonly_files;
 7339: }
 7340: #-----------------------------------------------------------Get Marked as Read Only Hash
 7341: 
 7342: sub get_marked_as_readonly_hash {
 7343:     my ($current_permissions,$group,$what) = @_;
 7344:     my %readonly_files;
 7345:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 7346:         if (defined($group)) {
 7347:             if ($file_name !~ m-^\Q$group\E/-) {
 7348:                 next;
 7349:             }
 7350:         }
 7351:         if (ref($value) eq "ARRAY"){
 7352:             foreach my $stored_what (@{$value}) {
 7353:                 if (ref($stored_what) eq 'ARRAY') {
 7354:                     foreach my $lock_descriptor(@{$stored_what}) {
 7355:                         if ($lock_descriptor eq 'graded') {
 7356:                             $readonly_files{$file_name} = 'graded';
 7357:                         } elsif ($lock_descriptor eq 'handback') {
 7358:                             $readonly_files{$file_name} = 'handback';
 7359:                         } else {
 7360:                             if (!exists($readonly_files{$file_name})) {
 7361:                                 $readonly_files{$file_name} = 'locked';
 7362:                             }
 7363:                         }
 7364:                     }
 7365:                 } 
 7366:             }
 7367:         } 
 7368:     }
 7369:     return %readonly_files;
 7370: }
 7371: # ------------------------------------------------------------ Unmark as Read Only
 7372: 
 7373: sub unmark_as_readonly {
 7374:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 7375:     # for portfolio submissions, $what contains [$symb,$crsid] 
 7376:     my ($domain,$user,$what,$file_name,$group) = @_;
 7377:     $file_name = &declutter_portfile($file_name);
 7378:     my $symb_crs = $what;
 7379:     if (ref($what)) { $symb_crs=join('',@$what); }
 7380:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 7381:     my ($tmp)=keys(%current_permissions);
 7382:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 7383:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 7384:     foreach my $file (@readonly_files) {
 7385: 	my $clean_file = &declutter_portfile($file);
 7386: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 7387: 	my $current_locks = $current_permissions{$file};
 7388:         my @new_locks;
 7389:         my @del_keys;
 7390:         if (ref($current_locks) eq "ARRAY"){
 7391:             foreach my $locker (@{$current_locks}) {
 7392:                 my $compare=$locker;
 7393:                 if (ref($locker) eq 'ARRAY') {
 7394:                     $compare=join('',@{$locker});
 7395:                     if ($compare ne $symb_crs) {
 7396:                         push(@new_locks, $locker);
 7397:                     }
 7398:                 }
 7399:             }
 7400:             if (scalar(@new_locks) > 0) {
 7401:                 $current_permissions{$file} = \@new_locks;
 7402:             } else {
 7403:                 push(@del_keys, $file);
 7404:                 &del('file_permissions',\@del_keys, $domain, $user);
 7405:                 delete($current_permissions{$file});
 7406:             }
 7407:         }
 7408:     }
 7409:     &put('file_permissions',\%current_permissions,$domain,$user);
 7410:     return;
 7411: }
 7412: 
 7413: # ------------------------------------------------------------ Directory lister
 7414: 
 7415: sub dirlist {
 7416:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 7417:     $uri=~s/^\///;
 7418:     $uri=~s/\/$//;
 7419:     my ($udom, $uname);
 7420:     if ($getuserdir) {
 7421:         $udom = $userdomain;
 7422:         $uname = $username;
 7423:     } else {
 7424:         (undef,$udom,$uname)=split(/\//,$uri);
 7425:         if(defined($userdomain)) {
 7426:             $udom = $userdomain;
 7427:         }
 7428:         if(defined($username)) {
 7429:             $uname = $username;
 7430:         }
 7431:     }
 7432:     my ($dirRoot,$listing,@listing_results);
 7433: 
 7434:     $dirRoot = $perlvar{'lonDocRoot'};
 7435:     if (defined($getpropath)) {
 7436:         $dirRoot = &propath($udom,$uname);
 7437:         $dirRoot =~ s/\/$//;
 7438:     } elsif (defined($getuserdir)) {
 7439:         my $subdir=$uname.'__';
 7440:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 7441:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 7442:                    ."/$udom/$subdir/$uname";
 7443:     } elsif (defined($alternateRoot)) {
 7444:         $dirRoot = $alternateRoot;
 7445:     }
 7446: 
 7447:     if($udom) {
 7448:         if($uname) {
 7449:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 7450:                               .$getuserdir.':'.&escape($dirRoot)
 7451:                               .':'.&escape($uname).':'.&escape($udom),
 7452:                               &homeserver($uname,$udom));
 7453:             if ($listing eq 'unknown_cmd') {
 7454:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 7455:                                   &homeserver($uname,$udom));
 7456:             } else {
 7457:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 7458:             }
 7459:             if ($listing eq 'unknown_cmd') {
 7460:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 7461: 				  &homeserver($uname,$udom));
 7462:                 @listing_results = split(/:/,$listing);
 7463:             } else {
 7464:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 7465:             }
 7466:             return @listing_results;
 7467:         } elsif(!$alternateRoot) {
 7468:             my %allusers;
 7469: 	    my %servers = &get_servers($udom,'library');
 7470:  	    foreach my $tryserver (keys(%servers)) {
 7471:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 7472:                                   &escape($udom),$tryserver);
 7473:                 if ($listing eq 'unknown_cmd') {
 7474: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 7475: 				      $udom, $tryserver);
 7476:                 } else {
 7477:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 7478:                 }
 7479: 		if ($listing eq 'unknown_cmd') {
 7480: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 7481: 				      $udom, $tryserver);
 7482: 		    @listing_results = split(/:/,$listing);
 7483: 		} else {
 7484: 		    @listing_results =
 7485: 			map { &unescape($_); } split(/:/,$listing);
 7486: 		}
 7487: 		if ($listing_results[0] ne 'no_such_dir' && 
 7488: 		    $listing_results[0] ne 'empty'       &&
 7489: 		    $listing_results[0] ne 'con_lost') {
 7490: 		    foreach my $line (@listing_results) {
 7491: 			my ($entry) = split(/&/,$line,2);
 7492: 			$allusers{$entry} = 1;
 7493: 		    }
 7494: 		}
 7495:             }
 7496:             my $alluserstr='';
 7497:             foreach my $user (sort(keys(%allusers))) {
 7498:                 $alluserstr.=$user.'&user:';
 7499:             }
 7500:             $alluserstr=~s/:$//;
 7501:             return split(/:/,$alluserstr);
 7502:         } else {
 7503:             return ('missing user name');
 7504:         }
 7505:     } elsif(!defined($getpropath)) {
 7506:         my @all_domains = sort(&all_domains());
 7507:         foreach my $domain (@all_domains) {
 7508:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 7509:         }
 7510:         return @all_domains;
 7511:     } else {
 7512:         return ('missing domain');
 7513:     }
 7514: }
 7515: 
 7516: # --------------------------------------------- GetFileTimestamp
 7517: # This function utilizes dirlist and returns the date stamp for
 7518: # when it was last modified.  It will also return an error of -1
 7519: # if an error occurs
 7520: 
 7521: sub GetFileTimestamp {
 7522:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 7523:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 7524:     $studentName   = &LONCAPA::clean_username($studentName);
 7525:     my ($fileStat) = 
 7526:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
 7527:                                  undef,$getuserdir);
 7528:     my @stats = split('&', $fileStat);
 7529:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 7530:         # @stats contains first the filename, then the stat output
 7531:         return $stats[10]; # so this is 10 instead of 9.
 7532:     } else {
 7533:         return -1;
 7534:     }
 7535: }
 7536: 
 7537: sub stat_file {
 7538:     my ($uri) = @_;
 7539:     $uri = &clutter_with_no_wrapper($uri);
 7540: 
 7541:     my ($udom,$uname,$file);
 7542:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 7543: 	($udom,$uname,$file) =
 7544: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 7545: 	$file = 'userfiles/'.$file;
 7546:     }
 7547:     if ($uri =~ m-^/res/-) {
 7548: 	($udom,$uname) = 
 7549: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 7550: 	$file = $uri;
 7551:     }
 7552: 
 7553:     if (!$udom || !$uname || !$file) {
 7554: 	# unable to handle the uri
 7555: 	return ();
 7556:     }
 7557:     my $getpropath;
 7558:     if ($file =~ /^userfiles\//) {
 7559:         $getpropath = 1;
 7560:     }
 7561:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
 7562:     my @stats = split('&', $result);
 7563:     
 7564:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 7565: 	shift(@stats); #filename is first
 7566: 	return @stats;
 7567:     }
 7568:     return ();
 7569: }
 7570: 
 7571: # -------------------------------------------------------- Value of a Condition
 7572: 
 7573: # gets the value of a specific preevaluated condition
 7574: #    stored in the string  $env{user.state.<cid>}
 7575: # or looks up a condition reference in the bighash and if if hasn't
 7576: # already been evaluated recurses into docondval to get the value of
 7577: # the condition, then memoizing it to 
 7578: #   $env{user.state.<cid>.<condition>}
 7579: sub directcondval {
 7580:     my $number=shift;
 7581:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 7582: 	&Apache::lonuserstate::evalstate();
 7583:     }
 7584:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 7585: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 7586:     } elsif ($number =~ /^_/) {
 7587: 	my $sub_condition;
 7588: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7589: 		&GDBM_READER(),0640)) {
 7590: 	    $sub_condition=$bighash{'conditions'.$number};
 7591: 	    untie(%bighash);
 7592: 	}
 7593: 	my $value = &docondval($sub_condition);
 7594: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 7595: 	return $value;
 7596:     }
 7597:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 7598:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 7599:     } else {
 7600:        return 2;
 7601:     }
 7602: }
 7603: 
 7604: # get the collection of conditions for this resource
 7605: sub condval {
 7606:     my $condidx=shift;
 7607:     my $allpathcond='';
 7608:     foreach my $cond (split(/\|/,$condidx)) {
 7609: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 7610: 	    $allpathcond.=
 7611: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 7612: 	}
 7613:     }
 7614:     $allpathcond=~s/\|$//;
 7615:     return &docondval($allpathcond);
 7616: }
 7617: 
 7618: #evaluates an expression of conditions
 7619: sub docondval {
 7620:     my ($allpathcond) = @_;
 7621:     my $result=0;
 7622:     if ($env{'request.course.id'}
 7623: 	&& defined($allpathcond)) {
 7624: 	my $operand='|';
 7625: 	my @stack;
 7626: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 7627: 	    if ($chunk eq '(') {
 7628: 		push @stack,($operand,$result);
 7629: 	    } elsif ($chunk eq ')') {
 7630: 		my $before=pop @stack;
 7631: 		if (pop @stack eq '&') {
 7632: 		    $result=$result>$before?$before:$result;
 7633: 		} else {
 7634: 		    $result=$result>$before?$result:$before;
 7635: 		}
 7636: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 7637: 		$operand=$chunk;
 7638: 	    } else {
 7639: 		my $new=directcondval($chunk);
 7640: 		if ($operand eq '&') {
 7641: 		    $result=$result>$new?$new:$result;
 7642: 		} else {
 7643: 		    $result=$result>$new?$result:$new;
 7644: 		}
 7645: 	    }
 7646: 	}
 7647:     }
 7648:     return $result;
 7649: }
 7650: 
 7651: # ---------------------------------------------------- Devalidate courseresdata
 7652: 
 7653: sub devalidatecourseresdata {
 7654:     my ($coursenum,$coursedomain)=@_;
 7655:     my $hashid=$coursenum.':'.$coursedomain;
 7656:     &devalidate_cache_new('courseres',$hashid);
 7657: }
 7658: 
 7659: 
 7660: # --------------------------------------------------- Course Resourcedata Query
 7661: #
 7662: #  Parameters:
 7663: #      $coursenum    - Number of the course.
 7664: #      $coursedomain - Domain at which the course was created.
 7665: #  Returns:
 7666: #     A hash of the course parameters along (I think) with timestamps
 7667: #     and version info.
 7668: 
 7669: sub get_courseresdata {
 7670:     my ($coursenum,$coursedomain)=@_;
 7671:     my $coursehom=&homeserver($coursenum,$coursedomain);
 7672:     my $hashid=$coursenum.':'.$coursedomain;
 7673:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 7674:     my %dumpreply;
 7675:     unless (defined($cached)) {
 7676: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 7677: 	$result=\%dumpreply;
 7678: 	my ($tmp) = keys(%dumpreply);
 7679: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 7680: 	    &do_cache_new('courseres',$hashid,$result,600);
 7681: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 7682: 	    return $tmp;
 7683: 	} elsif ($tmp =~ /^(error)/) {
 7684: 	    $result=undef;
 7685: 	    &do_cache_new('courseres',$hashid,$result,600);
 7686: 	}
 7687:     }
 7688:     return $result;
 7689: }
 7690: 
 7691: sub devalidateuserresdata {
 7692:     my ($uname,$udom)=@_;
 7693:     my $hashid="$udom:$uname";
 7694:     &devalidate_cache_new('userres',$hashid);
 7695: }
 7696: 
 7697: sub get_userresdata {
 7698:     my ($uname,$udom)=@_;
 7699:     #most student don\'t have any data set, check if there is some data
 7700:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 7701: 
 7702:     my $hashid="$udom:$uname";
 7703:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 7704:     if (!defined($cached)) {
 7705: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 7706: 	$result=\%resourcedata;
 7707: 	&do_cache_new('userres',$hashid,$result,600);
 7708:     }
 7709:     my ($tmp)=keys(%$result);
 7710:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 7711: 	return $result;
 7712:     }
 7713:     #error 2 occurs when the .db doesn't exist
 7714:     if ($tmp!~/error: 2 /) {
 7715: 	&logthis("<font color=\"blue\">WARNING:".
 7716: 		 " Trying to get resource data for ".
 7717: 		 $uname." at ".$udom.": ".
 7718: 		 $tmp."</font>");
 7719:     } elsif ($tmp=~/error: 2 /) {
 7720: 	#&EXT_cache_set($udom,$uname);
 7721: 	&do_cache_new('userres',$hashid,undef,600);
 7722: 	undef($tmp); # not really an error so don't send it back
 7723:     }
 7724:     return $tmp;
 7725: }
 7726: #----------------------------------------------- resdata - return resource data
 7727: #  Purpose:
 7728: #    Return resource data for either users or for a course.
 7729: #  Parameters:
 7730: #     $name      - Course/user name.
 7731: #     $domain    - Name of the domain the user/course is registered on.
 7732: #     $type      - Type of thing $name is (must be 'course' or 'user'
 7733: #     @which     - Array of names of resources desired.
 7734: #  Returns:
 7735: #     The value of the first reasource in @which that is found in the
 7736: #     resource hash.
 7737: #  Exceptional Conditions:
 7738: #     If the $type passed in is not valid (not the string 'course' or 
 7739: #     'user', an undefined  reference is returned.
 7740: #     If none of the resources are found, an undef is returned
 7741: sub resdata {
 7742:     my ($name,$domain,$type,@which)=@_;
 7743:     my $result;
 7744:     if ($type eq 'course') {
 7745: 	$result=&get_courseresdata($name,$domain);
 7746:     } elsif ($type eq 'user') {
 7747: 	$result=&get_userresdata($name,$domain);
 7748:     }
 7749:     if (!ref($result)) { return $result; }    
 7750:     foreach my $item (@which) {
 7751: 	if (defined($result->{$item->[0]})) {
 7752: 	    return [$result->{$item->[0]},$item->[1]];
 7753: 	}
 7754:     }
 7755:     return undef;
 7756: }
 7757: 
 7758: #
 7759: # EXT resource caching routines
 7760: #
 7761: 
 7762: sub clear_EXT_cache_status {
 7763:     &delenv('cache.EXT.');
 7764: }
 7765: 
 7766: sub EXT_cache_status {
 7767:     my ($target_domain,$target_user) = @_;
 7768:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7769:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 7770:         # We know already the user has no data
 7771:         return 1;
 7772:     } else {
 7773:         return 0;
 7774:     }
 7775: }
 7776: 
 7777: sub EXT_cache_set {
 7778:     my ($target_domain,$target_user) = @_;
 7779:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7780:     #&appenv({$cachename => time});
 7781: }
 7782: 
 7783: # --------------------------------------------------------- Value of a Variable
 7784: sub EXT {
 7785: 
 7786:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 7787:     unless ($varname) { return ''; }
 7788:     #get real user name/domain, courseid and symb
 7789:     my $courseid;
 7790:     my $publicuser;
 7791:     if ($symbparm) {
 7792: 	$symbparm=&get_symb_from_alias($symbparm);
 7793:     }
 7794:     if (!($uname && $udom)) {
 7795:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 7796:       if (!$symbparm) {	$symbparm=$cursymb; }
 7797:     } else {
 7798: 	$courseid=$env{'request.course.id'};
 7799:     }
 7800:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 7801:     my $rest;
 7802:     if (defined($therest[0])) {
 7803:        $rest=join('.',@therest);
 7804:     } else {
 7805:        $rest='';
 7806:     }
 7807: 
 7808:     my $qualifierrest=$qualifier;
 7809:     if ($rest) { $qualifierrest.='.'.$rest; }
 7810:     my $spacequalifierrest=$space;
 7811:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 7812:     if ($realm eq 'user') {
 7813: # --------------------------------------------------------------- user.resource
 7814: 	if ($space eq 'resource') {
 7815: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 7816: 		  || defined($Apache::lonhomework::parsing_a_task))
 7817: 		 &&
 7818: 		 ($symbparm eq &symbread()) ) {	
 7819: 		# if we are in the middle of processing the resource the
 7820: 		# get the value we are planning on committing
 7821:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 7822:                     return $Apache::lonhomework::results{$qualifierrest};
 7823:                 } else {
 7824:                     return $Apache::lonhomework::history{$qualifierrest};
 7825:                 }
 7826: 	    } else {
 7827: 		my %restored;
 7828: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 7829: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 7830: 		} else {
 7831: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 7832: 		}
 7833: 		return $restored{$qualifierrest};
 7834: 	    }
 7835: # ----------------------------------------------------------------- user.access
 7836:         } elsif ($space eq 'access') {
 7837: 	    # FIXME - not supporting calls for a specific user
 7838:             return &allowed($qualifier,$rest);
 7839: # ------------------------------------------ user.preferences, user.environment
 7840:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 7841: 	    if (($uname eq $env{'user.name'}) &&
 7842: 		($udom eq $env{'user.domain'})) {
 7843: 		return $env{join('.',('environment',$qualifierrest))};
 7844: 	    } else {
 7845: 		my %returnhash;
 7846: 		if (!$publicuser) {
 7847: 		    %returnhash=&userenvironment($udom,$uname,
 7848: 						 $qualifierrest);
 7849: 		}
 7850: 		return $returnhash{$qualifierrest};
 7851: 	    }
 7852: # ----------------------------------------------------------------- user.course
 7853:         } elsif ($space eq 'course') {
 7854: 	    # FIXME - not supporting calls for a specific user
 7855:             return $env{join('.',('request.course',$qualifier))};
 7856: # ------------------------------------------------------------------- user.role
 7857:         } elsif ($space eq 'role') {
 7858: 	    # FIXME - not supporting calls for a specific user
 7859:             my ($role,$where)=split(/\./,$env{'request.role'});
 7860:             if ($qualifier eq 'value') {
 7861: 		return $role;
 7862:             } elsif ($qualifier eq 'extent') {
 7863:                 return $where;
 7864:             }
 7865: # ----------------------------------------------------------------- user.domain
 7866:         } elsif ($space eq 'domain') {
 7867:             return $udom;
 7868: # ------------------------------------------------------------------- user.name
 7869:         } elsif ($space eq 'name') {
 7870:             return $uname;
 7871: # ---------------------------------------------------- Any other user namespace
 7872:         } else {
 7873: 	    my %reply;
 7874: 	    if (!$publicuser) {
 7875: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 7876: 	    }
 7877: 	    return $reply{$qualifierrest};
 7878:         }
 7879:     } elsif ($realm eq 'query') {
 7880: # ---------------------------------------------- pull stuff out of query string
 7881:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 7882: 						[$spacequalifierrest]);
 7883: 	return $env{'form.'.$spacequalifierrest}; 
 7884:    } elsif ($realm eq 'request') {
 7885: # ------------------------------------------------------------- request.browser
 7886:         if ($space eq 'browser') {
 7887: 	    if ($qualifier eq 'textremote') {
 7888: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 7889: 		    return 1;
 7890: 		} else {
 7891: 		    return 0;
 7892: 		}
 7893: 	    } else {
 7894: 		return $env{'browser.'.$qualifier};
 7895: 	    }
 7896: # ------------------------------------------------------------ request.filename
 7897:         } else {
 7898:             return $env{'request.'.$spacequalifierrest};
 7899:         }
 7900:     } elsif ($realm eq 'course') {
 7901: # ---------------------------------------------------------- course.description
 7902:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 7903:     } elsif ($realm eq 'resource') {
 7904: 
 7905: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 7906: 	    if (!$symbparm) { $symbparm=&symbread(); }
 7907: 	}
 7908: 
 7909: 	if ($space eq 'title') {
 7910: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 7911: 	    return &gettitle($symbparm);
 7912: 	}
 7913: 	
 7914: 	if ($space eq 'map') {
 7915: 	    my ($map) = &decode_symb($symbparm);
 7916: 	    return &symbread($map);
 7917: 	}
 7918: 	if ($space eq 'filename') {
 7919: 	    if ($symbparm) {
 7920: 		return &clutter((&decode_symb($symbparm))[2]);
 7921: 	    }
 7922: 	    return &hreflocation('',$env{'request.filename'});
 7923: 	}
 7924: 
 7925: 	my ($section, $group, @groups);
 7926: 	my ($courselevelm,$courselevel);
 7927: 	if ($symbparm && defined($courseid) && 
 7928: 	    $courseid eq $env{'request.course.id'}) {
 7929: 
 7930: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 7931: 
 7932: # ----------------------------------------------------- Cascading lookup scheme
 7933: 	    my $symbp=$symbparm;
 7934: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 7935: 
 7936: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 7937: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 7938: 
 7939: 	    if (($env{'user.name'} eq $uname) &&
 7940: 		($env{'user.domain'} eq $udom)) {
 7941: 		$section=$env{'request.course.sec'};
 7942:                 @groups = split(/:/,$env{'request.course.groups'});  
 7943:                 @groups=&sort_course_groups($courseid,@groups); 
 7944: 	    } else {
 7945: 		if (! defined($usection)) {
 7946: 		    $section=&getsection($udom,$uname,$courseid);
 7947: 		} else {
 7948: 		    $section = $usection;
 7949: 		}
 7950:                 @groups = &get_users_groups($udom,$uname,$courseid);
 7951: 	    }
 7952: 
 7953: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 7954: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 7955: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 7956: 
 7957: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 7958: 	    my $courselevelr=$courseid.'.'.$symbparm;
 7959: 	    $courselevelm=$courseid.'.'.$mapparm;
 7960: 
 7961: # ----------------------------------------------------------- first, check user
 7962: 
 7963: 	    my $userreply=&resdata($uname,$udom,'user',
 7964: 				       ([$courselevelr,'resource'],
 7965: 					[$courselevelm,'map'     ],
 7966: 					[$courselevel, 'course'  ]));
 7967: 	    if (defined($userreply)) { return &get_reply($userreply); }
 7968: 
 7969: # ------------------------------------------------ second, check some of course
 7970:             my $coursereply;
 7971:             if (@groups > 0) {
 7972:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 7973:                                        $mapparm,$spacequalifierrest);
 7974:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 7975:             }
 7976: 
 7977: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7978: 				  $env{'course.'.$courseid.'.domain'},
 7979: 				  'course',
 7980: 				  ([$seclevelr,   'resource'],
 7981: 				   [$seclevelm,   'map'     ],
 7982: 				   [$seclevel,    'course'  ],
 7983: 				   [$courselevelr,'resource']));
 7984: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7985: 
 7986: # ------------------------------------------------------ third, check map parms
 7987: 	    my %parmhash=();
 7988: 	    my $thisparm='';
 7989: 	    if (tie(%parmhash,'GDBM_File',
 7990: 		    $env{'request.course.fn'}.'_parms.db',
 7991: 		    &GDBM_READER(),0640)) {
 7992: 		$thisparm=$parmhash{$symbparm};
 7993: 		untie(%parmhash);
 7994: 	    }
 7995: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 7996: 	}
 7997: # ------------------------------------------ fourth, look in resource metadata
 7998: 
 7999: 	$spacequalifierrest=~s/\./\_/;
 8000: 	my $filename;
 8001: 	if (!$symbparm) { $symbparm=&symbread(); }
 8002: 	if ($symbparm) {
 8003: 	    $filename=(&decode_symb($symbparm))[2];
 8004: 	} else {
 8005: 	    $filename=$env{'request.filename'};
 8006: 	}
 8007: 	my $metadata=&metadata($filename,$spacequalifierrest);
 8008: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 8009: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 8010: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 8011: 
 8012: # ---------------------------------------------- fourth, look in rest of course
 8013: 	if ($symbparm && defined($courseid) && 
 8014: 	    $courseid eq $env{'request.course.id'}) {
 8015: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 8016: 				     $env{'course.'.$courseid.'.domain'},
 8017: 				     'course',
 8018: 				     ([$courselevelm,'map'   ],
 8019: 				      [$courselevel, 'course']));
 8020: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 8021: 	}
 8022: # ------------------------------------------------------------------ Cascade up
 8023: 	unless ($space eq '0') {
 8024: 	    my @parts=split(/_/,$space);
 8025: 	    my $id=pop(@parts);
 8026: 	    my $part=join('_',@parts);
 8027: 	    if ($part eq '') { $part='0'; }
 8028: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 8029: 				 $symbparm,$udom,$uname,$section,1);
 8030: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 8031: 	}
 8032: 	if ($recurse) { return undef; }
 8033: 	my $pack_def=&packages_tab_default($filename,$varname);
 8034: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 8035: # ---------------------------------------------------- Any other user namespace
 8036:     } elsif ($realm eq 'environment') {
 8037: # ----------------------------------------------------------------- environment
 8038: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 8039: 	    return $env{'environment.'.$spacequalifierrest};
 8040: 	} else {
 8041: 	    if ($uname eq 'anonymous' && $udom eq '') {
 8042: 		return '';
 8043: 	    }
 8044: 	    my %returnhash=&userenvironment($udom,$uname,
 8045: 					    $spacequalifierrest);
 8046: 	    return $returnhash{$spacequalifierrest};
 8047: 	}
 8048:     } elsif ($realm eq 'system') {
 8049: # ----------------------------------------------------------------- system.time
 8050: 	if ($space eq 'time') {
 8051: 	    return time;
 8052:         }
 8053:     } elsif ($realm eq 'server') {
 8054: # ----------------------------------------------------------------- system.time
 8055: 	if ($space eq 'name') {
 8056: 	    return $ENV{'SERVER_NAME'};
 8057:         }
 8058:     }
 8059:     return '';
 8060: }
 8061: 
 8062: sub get_reply {
 8063:     my ($reply_value) = @_;
 8064:     if (ref($reply_value) eq 'ARRAY') {
 8065:         if (wantarray) {
 8066: 	    return @$reply_value;
 8067:         }
 8068:         return $reply_value->[0];
 8069:     } else {
 8070:         return $reply_value;
 8071:     }
 8072: }
 8073: 
 8074: sub check_group_parms {
 8075:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 8076:     my @groupitems = ();
 8077:     my $resultitem;
 8078:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 8079:     foreach my $group (@{$groups}) {
 8080:         foreach my $level (@levels) {
 8081:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 8082:              push(@groupitems,[$item,$level->[1]]);
 8083:         }
 8084:     }
 8085:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 8086:                             $env{'course.'.$courseid.'.domain'},
 8087:                                      'course',@groupitems);
 8088:     return $coursereply;
 8089: }
 8090: 
 8091: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 8092:     my ($courseid,@groups) = @_;
 8093:     @groups = sort(@groups);
 8094:     return @groups;
 8095: }
 8096: 
 8097: sub packages_tab_default {
 8098:     my ($uri,$varname)=@_;
 8099:     my (undef,$part,$name)=split(/\./,$varname);
 8100: 
 8101:     my (@extension,@specifics,$do_default);
 8102:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 8103: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 8104: 	if ($pack_type eq 'default') {
 8105: 	    $do_default=1;
 8106: 	} elsif ($pack_type eq 'extension') {
 8107: 	    push(@extension,[$package,$pack_type,$pack_part]);
 8108: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 8109: 	    # only look at packages defaults for packages that this id is
 8110: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 8111: 	}
 8112:     }
 8113:     # first look for a package that matches the requested part id
 8114:     foreach my $package (@specifics) {
 8115: 	my (undef,$pack_type,$pack_part)=@{$package};
 8116: 	next if ($pack_part ne $part);
 8117: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 8118: 	    return $packagetab{"$pack_type&$name&default"};
 8119: 	}
 8120:     }
 8121:     # look for any possible matching non extension_ package
 8122:     foreach my $package (@specifics) {
 8123: 	my (undef,$pack_type,$pack_part)=@{$package};
 8124: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 8125: 	    return $packagetab{"$pack_type&$name&default"};
 8126: 	}
 8127: 	if ($pack_type eq 'part') { $pack_part='0'; }
 8128: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 8129: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 8130: 	}
 8131:     }
 8132:     # look for any posible extension_ match
 8133:     foreach my $package (@extension) {
 8134: 	my ($package,$pack_type)=@{$package};
 8135: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 8136: 	    return $packagetab{"$pack_type&$name&default"};
 8137: 	}
 8138: 	if (defined($packagetab{$package."&$name&default"})) {
 8139: 	    return $packagetab{$package."&$name&default"};
 8140: 	}
 8141:     }
 8142:     # look for a global default setting
 8143:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 8144: 	return $packagetab{"default&$name&default"};
 8145:     }
 8146:     return undef;
 8147: }
 8148: 
 8149: sub add_prefix_and_part {
 8150:     my ($prefix,$part)=@_;
 8151:     my $keyroot;
 8152:     if (defined($prefix) && $prefix !~ /^__/) {
 8153: 	# prefix that has a part already
 8154: 	$keyroot=$prefix;
 8155:     } elsif (defined($prefix)) {
 8156: 	# prefix that is missing a part
 8157: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 8158:     } else {
 8159: 	# no prefix at all
 8160: 	if (defined($part)) { $keyroot='_'.$part; }
 8161:     }
 8162:     return $keyroot;
 8163: }
 8164: 
 8165: # ---------------------------------------------------------------- Get metadata
 8166: 
 8167: my %metaentry;
 8168: sub metadata {
 8169:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 8170:     $uri=&declutter($uri);
 8171:     # if it is a non metadata possible uri return quickly
 8172:     if (($uri eq '') || 
 8173: 	(($uri =~ m|^/*adm/|) && 
 8174: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 8175:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 8176: 	return undef;
 8177:     }
 8178:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 8179: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 8180: 	return undef;
 8181:     }
 8182:     my $filename=$uri;
 8183:     $uri=~s/\.meta$//;
 8184: #
 8185: # Is the metadata already cached?
 8186: # Look at timestamp of caching
 8187: # Everything is cached by the main uri, libraries are never directly cached
 8188: #
 8189:     if (!defined($liburi)) {
 8190: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 8191: 	if (defined($cached)) { return $result->{':'.$what}; }
 8192:     }
 8193:     {
 8194: #
 8195: # Is this a recursive call for a library?
 8196: #
 8197: #	if (! exists($metacache{$uri})) {
 8198: #	    $metacache{$uri}={};
 8199: #	}
 8200: 	my $cachetime = 60*60;
 8201:         if ($liburi) {
 8202: 	    $liburi=&declutter($liburi);
 8203:             $filename=$liburi;
 8204:         } else {
 8205: 	    &devalidate_cache_new('meta',$uri);
 8206: 	    undef(%metaentry);
 8207: 	}
 8208:         my %metathesekeys=();
 8209:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 8210: 	my $metastring;
 8211: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 8212: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 8213: 	    $metastring = 
 8214: 		&Apache::lonnet::ssi_body($which,
 8215: 					  ('grade_target' => 'meta'));
 8216: 	    $cachetime = 1; # only want this cached in the child not long term
 8217: 	} elsif ($uri !~ m -^(editupload)/-) {
 8218: 	    my $file=&filelocation('',&clutter($filename));
 8219: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 8220: 	    $metastring=&getfile($file);
 8221: 	}
 8222:         my $parser=HTML::LCParser->new(\$metastring);
 8223:         my $token;
 8224:         undef %metathesekeys;
 8225:         while ($token=$parser->get_token) {
 8226: 	    if ($token->[0] eq 'S') {
 8227: 		if (defined($token->[2]->{'package'})) {
 8228: #
 8229: # This is a package - get package info
 8230: #
 8231: 		    my $package=$token->[2]->{'package'};
 8232: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 8233: 		    if (defined($token->[2]->{'id'})) { 
 8234: 			$keyroot.='_'.$token->[2]->{'id'}; 
 8235: 		    }
 8236: 		    if ($metaentry{':packages'}) {
 8237: 			$metaentry{':packages'}.=','.$package.$keyroot;
 8238: 		    } else {
 8239: 			$metaentry{':packages'}=$package.$keyroot;
 8240: 		    }
 8241: 		    foreach my $pack_entry (keys(%packagetab)) {
 8242: 			my $part=$keyroot;
 8243: 			$part=~s/^\_//;
 8244: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 8245: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 8246: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 8247: 			    # ignore package.tab specified default values
 8248:                             # here &package_tab_default() will fetch those
 8249: 			    if ($subp eq 'default') { next; }
 8250: 			    my $value=$packagetab{$pack_entry};
 8251: 			    my $unikey;
 8252: 			    if ($pack =~ /_0$/) {
 8253: 				$unikey='parameter_0_'.$name;
 8254: 				$part=0;
 8255: 			    } else {
 8256: 				$unikey='parameter'.$keyroot.'_'.$name;
 8257: 			    }
 8258: 			    if ($subp eq 'display') {
 8259: 				$value.=' [Part: '.$part.']';
 8260: 			    }
 8261: 			    $metaentry{':'.$unikey.'.part'}=$part;
 8262: 			    $metathesekeys{$unikey}=1;
 8263: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 8264: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 8265: 			    }
 8266: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 8267: 				$metaentry{':'.$unikey}=
 8268: 				    $metaentry{':'.$unikey.'.default'};
 8269: 			    }
 8270: 			}
 8271: 		    }
 8272: 		} else {
 8273: #
 8274: # This is not a package - some other kind of start tag
 8275: #
 8276: 		    my $entry=$token->[1];
 8277: 		    my $unikey;
 8278: 		    if ($entry eq 'import') {
 8279: 			$unikey='';
 8280: 		    } else {
 8281: 			$unikey=$entry;
 8282: 		    }
 8283: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 8284: 
 8285: 		    if (defined($token->[2]->{'id'})) { 
 8286: 			$unikey.='_'.$token->[2]->{'id'}; 
 8287: 		    }
 8288: 
 8289: 		    if ($entry eq 'import') {
 8290: #
 8291: # Importing a library here
 8292: #
 8293: 			if ($depthcount<20) {
 8294: 			    my $location=$parser->get_text('/import');
 8295: 			    my $dir=$filename;
 8296: 			    $dir=~s|[^/]*$||;
 8297: 			    $location=&filelocation($dir,$location);
 8298: 			    my $metadata = 
 8299: 				&metadata($uri,'keys', $location,$unikey,
 8300: 					  $depthcount+1);
 8301: 			    foreach my $meta (split(',',$metadata)) {
 8302: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 8303: 				$metathesekeys{$meta}=1;
 8304: 			    }
 8305: 			}
 8306: 		    } else { 
 8307: 			
 8308: 			if (defined($token->[2]->{'name'})) { 
 8309: 			    $unikey.='_'.$token->[2]->{'name'}; 
 8310: 			}
 8311: 			$metathesekeys{$unikey}=1;
 8312: 			foreach my $param (@{$token->[3]}) {
 8313: 			    $metaentry{':'.$unikey.'.'.$param} =
 8314: 				$token->[2]->{$param};
 8315: 			}
 8316: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 8317: 			my $default=$metaentry{':'.$unikey.'.default'};
 8318: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 8319: 		 # only ws inside the tag, and not in default, so use default
 8320: 		 # as value
 8321: 			    $metaentry{':'.$unikey}=$default;
 8322: 			} elsif ( $internaltext =~ /\S/ ) {
 8323: 		  # something interesting inside the tag
 8324: 			    $metaentry{':'.$unikey}=$internaltext;
 8325: 			} else {
 8326: 		  # no interesting values, don't set a default
 8327: 			}
 8328: # end of not-a-package not-a-library import
 8329: 		    }
 8330: # end of not-a-package start tag
 8331: 		}
 8332: # the next is the end of "start tag"
 8333: 	    }
 8334: 	}
 8335: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 8336: 	$extension = lc($extension);
 8337: 	if ($extension eq 'htm') { $extension='html'; }
 8338: 
 8339: 	foreach my $key (keys(%packagetab)) {
 8340: 	    #no specific packages #how's our extension
 8341: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 8342: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 8343: 					 \%metathesekeys);
 8344: 	}
 8345: 
 8346: 	if (!exists($metaentry{':packages'})
 8347: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 8348: 	    foreach my $key (keys(%packagetab)) {
 8349: 		#no specific packages well let's get default then
 8350: 		if ($key!~/^default&/) { next; }
 8351: 		&metadata_create_package_def($uri,$key,'default',
 8352: 					     \%metathesekeys);
 8353: 	    }
 8354: 	}
 8355: # are there custom rights to evaluate
 8356: 	if ($metaentry{':copyright'} eq 'custom') {
 8357: 
 8358:     #
 8359:     # Importing a rights file here
 8360:     #
 8361: 	    unless ($depthcount) {
 8362: 		my $location=$metaentry{':customdistributionfile'};
 8363: 		my $dir=$filename;
 8364: 		$dir=~s|[^/]*$||;
 8365: 		$location=&filelocation($dir,$location);
 8366: 		my $rights_metadata =
 8367: 		    &metadata($uri,'keys',$location,'_rights',
 8368: 			      $depthcount+1);
 8369: 		foreach my $rights (split(',',$rights_metadata)) {
 8370: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 8371: 		    $metathesekeys{$rights}=1;
 8372: 		}
 8373: 	    }
 8374: 	}
 8375: 	# uniqifiy package listing
 8376: 	my %seen;
 8377: 	my @uniq_packages =
 8378: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 8379: 	$metaentry{':packages'} = join(',',@uniq_packages);
 8380: 
 8381: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 8382: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 8383: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 8384: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 8385: # this is the end of "was not already recently cached
 8386:     }
 8387:     return $metaentry{':'.$what};
 8388: }
 8389: 
 8390: sub metadata_create_package_def {
 8391:     my ($uri,$key,$package,$metathesekeys)=@_;
 8392:     my ($pack,$name,$subp)=split(/\&/,$key);
 8393:     if ($subp eq 'default') { next; }
 8394:     
 8395:     if (defined($metaentry{':packages'})) {
 8396: 	$metaentry{':packages'}.=','.$package;
 8397:     } else {
 8398: 	$metaentry{':packages'}=$package;
 8399:     }
 8400:     my $value=$packagetab{$key};
 8401:     my $unikey;
 8402:     $unikey='parameter_0_'.$name;
 8403:     $metaentry{':'.$unikey.'.part'}=0;
 8404:     $$metathesekeys{$unikey}=1;
 8405:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 8406: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 8407:     }
 8408:     if (defined($metaentry{':'.$unikey.'.default'})) {
 8409: 	$metaentry{':'.$unikey}=
 8410: 	    $metaentry{':'.$unikey.'.default'};
 8411:     }
 8412: }
 8413: 
 8414: sub metadata_generate_part0 {
 8415:     my ($metadata,$metacache,$uri) = @_;
 8416:     my %allnames;
 8417:     foreach my $metakey (keys(%$metadata)) {
 8418: 	if ($metakey=~/^parameter\_(.*)/) {
 8419: 	  my $part=$$metacache{':'.$metakey.'.part'};
 8420: 	  my $name=$$metacache{':'.$metakey.'.name'};
 8421: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 8422: 	    $allnames{$name}=$part;
 8423: 	  }
 8424: 	}
 8425:     }
 8426:     foreach my $name (keys(%allnames)) {
 8427:       $$metadata{"parameter_0_$name"}=1;
 8428:       my $key=":parameter_0_$name";
 8429:       $$metacache{"$key.part"}='0';
 8430:       $$metacache{"$key.name"}=$name;
 8431:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 8432: 					   $allnames{$name}.'_'.$name.
 8433: 					   '.type'};
 8434:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 8435: 			     '.display'};
 8436:       my $expr='[Part: '.$allnames{$name}.']';
 8437:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 8438:       $$metacache{"$key.display"}=$olddis;
 8439:     }
 8440: }
 8441: 
 8442: # ------------------------------------------------------ Devalidate title cache
 8443: 
 8444: sub devalidate_title_cache {
 8445:     my ($url)=@_;
 8446:     if (!$env{'request.course.id'}) { return; }
 8447:     my $symb=&symbread($url);
 8448:     if (!$symb) { return; }
 8449:     my $key=$env{'request.course.id'}."\0".$symb;
 8450:     &devalidate_cache_new('title',$key);
 8451: }
 8452: 
 8453: # ------------------------------------------------- Get the title of a course
 8454: 
 8455: sub current_course_title {
 8456:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
 8457: }
 8458: # ------------------------------------------------- Get the title of a resource
 8459: 
 8460: sub gettitle {
 8461:     my $urlsymb=shift;
 8462:     my $symb=&symbread($urlsymb);
 8463:     if ($symb) {
 8464: 	my $key=$env{'request.course.id'}."\0".$symb;
 8465: 	my ($result,$cached)=&is_cached_new('title',$key);
 8466: 	if (defined($cached)) { 
 8467: 	    return $result;
 8468: 	}
 8469: 	my ($map,$resid,$url)=&decode_symb($symb);
 8470: 	my $title='';
 8471: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 8472: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 8473: 	} else {
 8474: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8475: 		    &GDBM_READER(),0640)) {
 8476: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 8477: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 8478: 		untie(%bighash);
 8479: 	    }
 8480: 	}
 8481: 	$title=~s/\&colon\;/\:/gs;
 8482: 	if ($title) {
 8483: 	    return &do_cache_new('title',$key,$title,600);
 8484: 	}
 8485: 	$urlsymb=$url;
 8486:     }
 8487:     my $title=&metadata($urlsymb,'title');
 8488:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 8489:     return $title;
 8490: }
 8491: 
 8492: sub get_slot {
 8493:     my ($which,$cnum,$cdom)=@_;
 8494:     if (!$cnum || !$cdom) {
 8495: 	(undef,my $courseid)=&whichuser();
 8496: 	$cdom=$env{'course.'.$courseid.'.domain'};
 8497: 	$cnum=$env{'course.'.$courseid.'.num'};
 8498:     }
 8499:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 8500:     my %slotinfo;
 8501:     if (exists($remembered{$key})) {
 8502: 	$slotinfo{$which} = $remembered{$key};
 8503:     } else {
 8504: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 8505: 	&Apache::lonhomework::showhash(%slotinfo);
 8506: 	my ($tmp)=keys(%slotinfo);
 8507: 	if ($tmp=~/^error:/) { return (); }
 8508: 	$remembered{$key} = $slotinfo{$which};
 8509:     }
 8510:     if (ref($slotinfo{$which}) eq 'HASH') {
 8511: 	return %{$slotinfo{$which}};
 8512:     }
 8513:     return $slotinfo{$which};
 8514: }
 8515: # ------------------------------------------------- Update symbolic store links
 8516: 
 8517: sub symblist {
 8518:     my ($mapname,%newhash)=@_;
 8519:     $mapname=&deversion(&declutter($mapname));
 8520:     my %hash;
 8521:     if (($env{'request.course.fn'}) && (%newhash)) {
 8522:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 8523:                       &GDBM_WRCREAT(),0640)) {
 8524: 	    foreach my $url (keys(%newhash)) {
 8525: 		next if ($url eq 'last_known'
 8526: 			 && $env{'form.no_update_last_known'});
 8527: 		$hash{declutter($url)}=&encode_symb($mapname,
 8528: 						    $newhash{$url}->[1],
 8529: 						    $newhash{$url}->[0]);
 8530:             }
 8531:             if (untie(%hash)) {
 8532: 		return 'ok';
 8533:             }
 8534:         }
 8535:     }
 8536:     return 'error';
 8537: }
 8538: 
 8539: # --------------------------------------------------------------- Verify a symb
 8540: 
 8541: sub symbverify {
 8542:     my ($symb,$thisurl)=@_;
 8543:     my $thisfn=$thisurl;
 8544:     $thisfn=&declutter($thisfn);
 8545: # direct jump to resource in page or to a sequence - will construct own symbs
 8546:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 8547: # check URL part
 8548:     my ($map,$resid,$url)=&decode_symb($symb);
 8549: 
 8550:     unless ($url eq $thisfn) { return 0; }
 8551: 
 8552:     $symb=&symbclean($symb);
 8553:     $thisurl=&deversion($thisurl);
 8554:     $thisfn=&deversion($thisfn);
 8555: 
 8556:     my %bighash;
 8557:     my $okay=0;
 8558: 
 8559:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8560:                             &GDBM_READER(),0640)) {
 8561:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
 8562:             $thisurl =~ s/\?.+$//;
 8563:         }
 8564:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 8565:         unless ($ids) { 
 8566:            $ids=$bighash{'ids_/'.$thisurl};
 8567:         }
 8568:         if ($ids) {
 8569: # ------------------------------------------------------------------- Has ID(s)
 8570: 	    foreach my $id (split(/\,/,$ids)) {
 8571: 	       my ($mapid,$resid)=split(/\./,$id);
 8572:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
 8573:                    $symb =~ s/\?.+$//;
 8574:                }
 8575:                if (
 8576:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 8577:    eq $symb) { 
 8578: 		   if (($env{'request.role.adv'}) ||
 8579: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 8580: 		       $okay=1; 
 8581: 		   }
 8582: 	       }
 8583: 	   }
 8584:         }
 8585: 	untie(%bighash);
 8586:     }
 8587:     return $okay;
 8588: }
 8589: 
 8590: # --------------------------------------------------------------- Clean-up symb
 8591: 
 8592: sub symbclean {
 8593:     my $symb=shift;
 8594:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 8595: # remove version from map
 8596:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 8597: 
 8598: # remove version from URL
 8599:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 8600: 
 8601: # remove wrapper
 8602: 
 8603:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 8604:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 8605:     return $symb;
 8606: }
 8607: 
 8608: # ---------------------------------------------- Split symb to find map and url
 8609: 
 8610: sub encode_symb {
 8611:     my ($map,$resid,$url)=@_;
 8612:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 8613: }
 8614: 
 8615: sub decode_symb {
 8616:     my $symb=shift;
 8617:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 8618:     my ($map,$resid,$url)=split(/___/,$symb);
 8619:     return (&fixversion($map),$resid,&fixversion($url));
 8620: }
 8621: 
 8622: sub fixversion {
 8623:     my $fn=shift;
 8624:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 8625:     my %bighash;
 8626:     my $uri=&clutter($fn);
 8627:     my $key=$env{'request.course.id'}.'_'.$uri;
 8628: # is this cached?
 8629:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 8630:     if (defined($cached)) { return $result; }
 8631: # unfortunately not cached, or expired
 8632:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8633: 	    &GDBM_READER(),0640)) {
 8634:  	if ($bighash{'version_'.$uri}) {
 8635:  	    my $version=$bighash{'version_'.$uri};
 8636:  	    unless (($version eq 'mostrecent') || 
 8637: 		    ($version==&getversion($uri))) {
 8638:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 8639:  	    }
 8640:  	}
 8641:  	untie %bighash;
 8642:     }
 8643:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 8644: }
 8645: 
 8646: sub deversion {
 8647:     my $url=shift;
 8648:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 8649:     return $url;
 8650: }
 8651: 
 8652: # ------------------------------------------------------ Return symb list entry
 8653: 
 8654: sub symbread {
 8655:     my ($thisfn,$donotrecurse)=@_;
 8656:     my $cache_str='request.symbread.cached.'.$thisfn;
 8657:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 8658: # no filename provided? try from environment
 8659:     unless ($thisfn) {
 8660:         if ($env{'request.symb'}) {
 8661: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 8662: 	}
 8663: 	$thisfn=$env{'request.filename'};
 8664:     }
 8665:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8666: # is that filename actually a symb? Verify, clean, and return
 8667:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 8668: 	if (&symbverify($thisfn,$1)) {
 8669: 	    return $env{$cache_str}=&symbclean($thisfn);
 8670: 	}
 8671:     }
 8672:     $thisfn=declutter($thisfn);
 8673:     my %hash;
 8674:     my %bighash;
 8675:     my $syval='';
 8676:     if (($env{'request.course.fn'}) && ($thisfn)) {
 8677:         my $targetfn = $thisfn;
 8678:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 8679:             $targetfn = 'adm/wrapper/'.$thisfn;
 8680:         }
 8681: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 8682: 	    $targetfn=$1;
 8683: 	}
 8684:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 8685:                       &GDBM_READER(),0640)) {
 8686: 	    $syval=$hash{$targetfn};
 8687:             untie(%hash);
 8688:         }
 8689: # ---------------------------------------------------------- There was an entry
 8690:         if ($syval) {
 8691: 	    #unless ($syval=~/\_\d+$/) {
 8692: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 8693: 		    #&appenv({'request.ambiguous' => $thisfn});
 8694: 		    #return $env{$cache_str}='';
 8695: 		#}    
 8696: 		#$syval.=$1;
 8697: 	    #}
 8698:         } else {
 8699: # ------------------------------------------------------- Was not in symb table
 8700:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8701:                             &GDBM_READER(),0640)) {
 8702: # ---------------------------------------------- Get ID(s) for current resource
 8703:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 8704:               unless ($ids) { 
 8705:                  $ids=$bighash{'ids_/'.$thisfn};
 8706:               }
 8707:               unless ($ids) {
 8708: # alias?
 8709: 		  $ids=$bighash{'mapalias_'.$thisfn};
 8710:               }
 8711:               if ($ids) {
 8712: # ------------------------------------------------------------------- Has ID(s)
 8713:                  my @possibilities=split(/\,/,$ids);
 8714:                  if ($#possibilities==0) {
 8715: # ----------------------------------------------- There is only one possibility
 8716: 		     my ($mapid,$resid)=split(/\./,$ids);
 8717: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 8718: 						    $resid,$thisfn);
 8719:                  } elsif (!$donotrecurse) {
 8720: # ------------------------------------------ There is more than one possibility
 8721:                      my $realpossible=0;
 8722:                      foreach my $id (@possibilities) {
 8723: 			 my $file=$bighash{'src_'.$id};
 8724:                          if (&allowed('bre',$file)) {
 8725:          		    my ($mapid,$resid)=split(/\./,$id);
 8726:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 8727: 				$realpossible++;
 8728:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 8729: 						    $resid,$thisfn);
 8730:                             }
 8731: 			 }
 8732:                      }
 8733: 		     if ($realpossible!=1) { $syval=''; }
 8734:                  } else {
 8735:                      $syval='';
 8736:                  }
 8737: 	      }
 8738:               untie(%bighash)
 8739:            }
 8740:         }
 8741:         if ($syval) {
 8742: 	    return $env{$cache_str}=$syval;
 8743:         }
 8744:     }
 8745:     &appenv({'request.ambiguous' => $thisfn});
 8746:     return $env{$cache_str}='';
 8747: }
 8748: 
 8749: # ---------------------------------------------------------- Return random seed
 8750: 
 8751: sub numval {
 8752:     my $txt=shift;
 8753:     $txt=~tr/A-J/0-9/;
 8754:     $txt=~tr/a-j/0-9/;
 8755:     $txt=~tr/K-T/0-9/;
 8756:     $txt=~tr/k-t/0-9/;
 8757:     $txt=~tr/U-Z/0-5/;
 8758:     $txt=~tr/u-z/0-5/;
 8759:     $txt=~s/\D//g;
 8760:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 8761:     return int($txt);
 8762: }
 8763: 
 8764: sub numval2 {
 8765:     my $txt=shift;
 8766:     $txt=~tr/A-J/0-9/;
 8767:     $txt=~tr/a-j/0-9/;
 8768:     $txt=~tr/K-T/0-9/;
 8769:     $txt=~tr/k-t/0-9/;
 8770:     $txt=~tr/U-Z/0-5/;
 8771:     $txt=~tr/u-z/0-5/;
 8772:     $txt=~s/\D//g;
 8773:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8774:     my $total;
 8775:     foreach my $val (@txts) { $total+=$val; }
 8776:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 8777:     return int($total);
 8778: }
 8779: 
 8780: sub numval3 {
 8781:     use integer;
 8782:     my $txt=shift;
 8783:     $txt=~tr/A-J/0-9/;
 8784:     $txt=~tr/a-j/0-9/;
 8785:     $txt=~tr/K-T/0-9/;
 8786:     $txt=~tr/k-t/0-9/;
 8787:     $txt=~tr/U-Z/0-5/;
 8788:     $txt=~tr/u-z/0-5/;
 8789:     $txt=~s/\D//g;
 8790:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8791:     my $total;
 8792:     foreach my $val (@txts) { $total+=$val; }
 8793:     if ($_64bit) { $total=(($total<<32)>>32); }
 8794:     return $total;
 8795: }
 8796: 
 8797: sub digest {
 8798:     my ($data)=@_;
 8799:     my $digest=&Digest::MD5::md5($data);
 8800:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 8801:     my ($e,$f);
 8802:     {
 8803:         use integer;
 8804:         $e=($a+$b);
 8805:         $f=($c+$d);
 8806:         if ($_64bit) {
 8807:             $e=(($e<<32)>>32);
 8808:             $f=(($f<<32)>>32);
 8809:         }
 8810:     }
 8811:     if (wantarray) {
 8812: 	return ($e,$f);
 8813:     } else {
 8814: 	my $g;
 8815: 	{
 8816: 	    use integer;
 8817: 	    $g=($e+$f);
 8818: 	    if ($_64bit) {
 8819: 		$g=(($g<<32)>>32);
 8820: 	    }
 8821: 	}
 8822: 	return $g;
 8823:     }
 8824: }
 8825: 
 8826: sub latest_rnd_algorithm_id {
 8827:     return '64bit5';
 8828: }
 8829: 
 8830: sub get_rand_alg {
 8831:     my ($courseid)=@_;
 8832:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 8833:     if ($courseid) {
 8834: 	return $env{"course.$courseid.rndseed"};
 8835:     }
 8836:     return &latest_rnd_algorithm_id();
 8837: }
 8838: 
 8839: sub validCODE {
 8840:     my ($CODE)=@_;
 8841:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 8842:     return 0;
 8843: }
 8844: 
 8845: sub getCODE {
 8846:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 8847:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 8848: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 8849: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 8850: 	return $Apache::lonhomework::history{'resource.CODE'};
 8851:     }
 8852:     return undef;
 8853: }
 8854: 
 8855: sub rndseed {
 8856:     my ($symb,$courseid,$domain,$username)=@_;
 8857:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 8858:     if (!defined($symb)) {
 8859: 	unless ($symb=$wsymb) { return time; }
 8860:     }
 8861:     if (!$courseid) { $courseid=$wcourseid; }
 8862:     if (!$domain) { $domain=$wdomain; }
 8863:     if (!$username) { $username=$wusername }
 8864:     my $which=&get_rand_alg();
 8865: 
 8866:     if (defined(&getCODE())) {
 8867: 	if ($which eq '64bit5') {
 8868: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 8869: 	} elsif ($which eq '64bit4') {
 8870: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 8871: 	} else {
 8872: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 8873: 	}
 8874:     } elsif ($which eq '64bit5') {
 8875: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 8876:     } elsif ($which eq '64bit4') {
 8877: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 8878:     } elsif ($which eq '64bit3') {
 8879: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 8880:     } elsif ($which eq '64bit2') {
 8881: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 8882:     } elsif ($which eq '64bit') {
 8883: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 8884:     }
 8885:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 8886: }
 8887: 
 8888: sub rndseed_32bit {
 8889:     my ($symb,$courseid,$domain,$username)=@_;
 8890:     {
 8891: 	use integer;
 8892: 	my $symbchck=unpack("%32C*",$symb) << 27;
 8893: 	my $symbseed=numval($symb) << 22;
 8894: 	my $namechck=unpack("%32C*",$username) << 17;
 8895: 	my $nameseed=numval($username) << 12;
 8896: 	my $domainseed=unpack("%32C*",$domain) << 7;
 8897: 	my $courseseed=unpack("%32C*",$courseid);
 8898: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 8899: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8900: 	#&logthis("rndseed :$num:$symb");
 8901: 	if ($_64bit) { $num=(($num<<32)>>32); }
 8902: 	return $num;
 8903:     }
 8904: }
 8905: 
 8906: sub rndseed_64bit {
 8907:     my ($symb,$courseid,$domain,$username)=@_;
 8908:     {
 8909: 	use integer;
 8910: 	my $symbchck=unpack("%32S*",$symb) << 21;
 8911: 	my $symbseed=numval($symb) << 10;
 8912: 	my $namechck=unpack("%32S*",$username);
 8913: 	
 8914: 	my $nameseed=numval($username) << 21;
 8915: 	my $domainseed=unpack("%32S*",$domain) << 10;
 8916: 	my $courseseed=unpack("%32S*",$courseid);
 8917: 	
 8918: 	my $num1=$symbchck+$symbseed+$namechck;
 8919: 	my $num2=$nameseed+$domainseed+$courseseed;
 8920: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8921: 	#&logthis("rndseed :$num:$symb");
 8922: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8923: 	return "$num1,$num2";
 8924:     }
 8925: }
 8926: 
 8927: sub rndseed_64bit2 {
 8928:     my ($symb,$courseid,$domain,$username)=@_;
 8929:     {
 8930: 	use integer;
 8931: 	# strings need to be an even # of cahracters long, it it is odd the
 8932:         # last characters gets thrown away
 8933: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8934: 	my $symbseed=numval($symb) << 10;
 8935: 	my $namechck=unpack("%32S*",$username.' ');
 8936: 	
 8937: 	my $nameseed=numval($username) << 21;
 8938: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8939: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8940: 	
 8941: 	my $num1=$symbchck+$symbseed+$namechck;
 8942: 	my $num2=$nameseed+$domainseed+$courseseed;
 8943: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8944: 	#&logthis("rndseed :$num:$symb");
 8945: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8946: 	return "$num1,$num2";
 8947:     }
 8948: }
 8949: 
 8950: sub rndseed_64bit3 {
 8951:     my ($symb,$courseid,$domain,$username)=@_;
 8952:     {
 8953: 	use integer;
 8954: 	# strings need to be an even # of cahracters long, it it is odd the
 8955:         # last characters gets thrown away
 8956: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8957: 	my $symbseed=numval2($symb) << 10;
 8958: 	my $namechck=unpack("%32S*",$username.' ');
 8959: 	
 8960: 	my $nameseed=numval2($username) << 21;
 8961: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8962: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8963: 	
 8964: 	my $num1=$symbchck+$symbseed+$namechck;
 8965: 	my $num2=$nameseed+$domainseed+$courseseed;
 8966: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8967: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8968: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8969: 	
 8970: 	return "$num1:$num2";
 8971:     }
 8972: }
 8973: 
 8974: sub rndseed_64bit4 {
 8975:     my ($symb,$courseid,$domain,$username)=@_;
 8976:     {
 8977: 	use integer;
 8978: 	# strings need to be an even # of cahracters long, it it is odd the
 8979:         # last characters gets thrown away
 8980: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8981: 	my $symbseed=numval3($symb) << 10;
 8982: 	my $namechck=unpack("%32S*",$username.' ');
 8983: 	
 8984: 	my $nameseed=numval3($username) << 21;
 8985: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8986: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8987: 	
 8988: 	my $num1=$symbchck+$symbseed+$namechck;
 8989: 	my $num2=$nameseed+$domainseed+$courseseed;
 8990: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8991: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8992: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8993: 	
 8994: 	return "$num1:$num2";
 8995:     }
 8996: }
 8997: 
 8998: sub rndseed_64bit5 {
 8999:     my ($symb,$courseid,$domain,$username)=@_;
 9000:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 9001:     return "$num1:$num2";
 9002: }
 9003: 
 9004: sub rndseed_CODE_64bit {
 9005:     my ($symb,$courseid,$domain,$username)=@_;
 9006:     {
 9007: 	use integer;
 9008: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 9009: 	my $symbseed=numval2($symb);
 9010: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 9011: 	my $CODEseed=numval(&getCODE());
 9012: 	my $courseseed=unpack("%32S*",$courseid.' ');
 9013: 	my $num1=$symbseed+$CODEchck;
 9014: 	my $num2=$CODEseed+$courseseed+$symbchck;
 9015: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 9016: 	#&logthis("rndseed :$num1:$num2:$symb");
 9017: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 9018: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 9019: 	return "$num1:$num2";
 9020:     }
 9021: }
 9022: 
 9023: sub rndseed_CODE_64bit4 {
 9024:     my ($symb,$courseid,$domain,$username)=@_;
 9025:     {
 9026: 	use integer;
 9027: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 9028: 	my $symbseed=numval3($symb);
 9029: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 9030: 	my $CODEseed=numval3(&getCODE());
 9031: 	my $courseseed=unpack("%32S*",$courseid.' ');
 9032: 	my $num1=$symbseed+$CODEchck;
 9033: 	my $num2=$CODEseed+$courseseed+$symbchck;
 9034: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 9035: 	#&logthis("rndseed :$num1:$num2:$symb");
 9036: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 9037: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 9038: 	return "$num1:$num2";
 9039:     }
 9040: }
 9041: 
 9042: sub rndseed_CODE_64bit5 {
 9043:     my ($symb,$courseid,$domain,$username)=@_;
 9044:     my $code = &getCODE();
 9045:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 9046:     return "$num1:$num2";
 9047: }
 9048: 
 9049: sub setup_random_from_rndseed {
 9050:     my ($rndseed)=@_;
 9051:     if ($rndseed =~/([,:])/) {
 9052: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 9053: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 9054:     } else {
 9055: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 9056:     }
 9057: }
 9058: 
 9059: sub latest_receipt_algorithm_id {
 9060:     return 'receipt3';
 9061: }
 9062: 
 9063: sub recunique {
 9064:     my $fucourseid=shift;
 9065:     my $unique;
 9066:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 9067: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 9068: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 9069:     } else {
 9070: 	$unique=$perlvar{'lonReceipt'};
 9071:     }
 9072:     return unpack("%32C*",$unique);
 9073: }
 9074: 
 9075: sub recprefix {
 9076:     my $fucourseid=shift;
 9077:     my $prefix;
 9078:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 9079: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 9080: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 9081:     } else {
 9082: 	$prefix=$perlvar{'lonHostID'};
 9083:     }
 9084:     return unpack("%32C*",$prefix);
 9085: }
 9086: 
 9087: sub ireceipt {
 9088:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 9089: 
 9090:     my $return =&recprefix($fucourseid).'-';
 9091: 
 9092:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 9093: 	$env{'request.state'} eq 'construct') {
 9094: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 9095: 	return $return;
 9096:     }
 9097: 
 9098:     my $cuname=unpack("%32C*",$funame);
 9099:     my $cudom=unpack("%32C*",$fudom);
 9100:     my $cucourseid=unpack("%32C*",$fucourseid);
 9101:     my $cusymb=unpack("%32C*",$fusymb);
 9102:     my $cunique=&recunique($fucourseid);
 9103:     my $cpart=unpack("%32S*",$part);
 9104:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 9105: 
 9106: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 9107: 			       
 9108: 	$return.= ($cunique%$cuname+
 9109: 		   $cunique%$cudom+
 9110: 		   $cusymb%$cuname+
 9111: 		   $cusymb%$cudom+
 9112: 		   $cucourseid%$cuname+
 9113: 		   $cucourseid%$cudom+
 9114: 		   $cpart%$cuname+
 9115: 		   $cpart%$cudom);
 9116:     } else {
 9117: 	$return.= ($cunique%$cuname+
 9118: 		   $cunique%$cudom+
 9119: 		   $cusymb%$cuname+
 9120: 		   $cusymb%$cudom+
 9121: 		   $cucourseid%$cuname+
 9122: 		   $cucourseid%$cudom);
 9123:     }
 9124:     return $return;
 9125: }
 9126: 
 9127: sub receipt {
 9128:     my ($part)=@_;
 9129:     my ($symb,$courseid,$domain,$name) = &whichuser();
 9130:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 9131: }
 9132: 
 9133: sub whichuser {
 9134:     my ($passedsymb)=@_;
 9135:     my ($symb,$courseid,$domain,$name,$publicuser);
 9136:     if (defined($env{'form.grade_symb'})) {
 9137: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 9138: 	my $allowed=&allowed('vgr',$tmp_courseid);
 9139: 	if (!$allowed &&
 9140: 	    exists($env{'request.course.sec'}) &&
 9141: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 9142: 	    $allowed=&allowed('vgr',$tmp_courseid.
 9143: 			      '/'.$env{'request.course.sec'});
 9144: 	}
 9145: 	if ($allowed) {
 9146: 	    ($symb)=&get_env_multiple('form.grade_symb');
 9147: 	    $courseid=$tmp_courseid;
 9148: 	    ($domain)=&get_env_multiple('form.grade_domain');
 9149: 	    ($name)=&get_env_multiple('form.grade_username');
 9150: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 9151: 	}
 9152:     }
 9153:     if (!$passedsymb) {
 9154: 	$symb=&symbread();
 9155:     } else {
 9156: 	$symb=$passedsymb;
 9157:     }
 9158:     $courseid=$env{'request.course.id'};
 9159:     $domain=$env{'user.domain'};
 9160:     $name=$env{'user.name'};
 9161:     if ($name eq 'public' && $domain eq 'public') {
 9162: 	if (!defined($env{'form.username'})) {
 9163: 	    $env{'form.username'}.=time.rand(10000000);
 9164: 	}
 9165: 	$name.=$env{'form.username'};
 9166:     }
 9167:     return ($symb,$courseid,$domain,$name,$publicuser);
 9168: 
 9169: }
 9170: 
 9171: # ------------------------------------------------------------ Serves up a file
 9172: # returns either the contents of the file or 
 9173: # -1 if the file doesn't exist
 9174: #
 9175: # if the target is a file that was uploaded via DOCS, 
 9176: # a check will be made to see if a current copy exists on the local server,
 9177: # if it does this will be served, otherwise a copy will be retrieved from
 9178: # the home server for the course and stored in /home/httpd/html/userfiles on
 9179: # the local server.   
 9180: 
 9181: sub getfile {
 9182:     my ($file) = @_;
 9183:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 9184:     &repcopy($file);
 9185:     return &readfile($file);
 9186: }
 9187: 
 9188: sub repcopy_userfile {
 9189:     my ($file)=@_;
 9190:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 9191:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 9192:     my ($cdom,$cnum,$filename) = 
 9193: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 9194:     my $uri="/uploaded/$cdom/$cnum/$filename";
 9195:     if (-e "$file") {
 9196: # we already have a local copy, check it out
 9197: 	my @fileinfo = stat($file);
 9198: 	my $rtncode;
 9199: 	my $info;
 9200: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 9201: 	if ($lwpresp ne 'ok') {
 9202: # there is no such file anymore, even though we had a local copy
 9203: 	    if ($rtncode eq '404') {
 9204: 		unlink($file);
 9205: 	    }
 9206: 	    return -1;
 9207: 	}
 9208: 	if ($info < $fileinfo[9]) {
 9209: # nice, the file we have is up-to-date, just say okay
 9210: 	    return 'ok';
 9211: 	} else {
 9212: # the file is outdated, get rid of it
 9213: 	    unlink($file);
 9214: 	}
 9215:     }
 9216: # one way or the other, at this point, we don't have the file
 9217: # construct the correct path for the file
 9218:     my @parts = ($cdom,$cnum); 
 9219:     if ($filename =~ m|^(.+)/[^/]+$|) {
 9220: 	push @parts, split(/\//,$1);
 9221:     }
 9222:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 9223:     foreach my $part (@parts) {
 9224: 	$path .= '/'.$part;
 9225: 	if (!-e $path) {
 9226: 	    mkdir($path,0770);
 9227: 	}
 9228:     }
 9229: # now the path exists for sure
 9230: # get a user agent
 9231:     my $ua=new LWP::UserAgent;
 9232:     my $transferfile=$file.'.in.transfer';
 9233: # FIXME: this should flock
 9234:     if (-e $transferfile) { return 'ok'; }
 9235:     my $request;
 9236:     $uri=~s/^\///;
 9237:     my $homeserver = &homeserver($cnum,$cdom);
 9238:     my $protocol = $protocol{$homeserver};
 9239:     $protocol = 'http' if ($protocol ne 'https');
 9240:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
 9241:     my $response=$ua->request($request,$transferfile);
 9242: # did it work?
 9243:     if ($response->is_error()) {
 9244: 	unlink($transferfile);
 9245: 	&logthis("Userfile repcopy failed for $uri");
 9246: 	return -1;
 9247:     }
 9248: # worked, rename the transfer file
 9249:     rename($transferfile,$file);
 9250:     return 'ok';
 9251: }
 9252: 
 9253: sub tokenwrapper {
 9254:     my $uri=shift;
 9255:     $uri=~s|^https?\://([^/]+)||;
 9256:     $uri=~s|^/||;
 9257:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 9258:     my $token=$1;
 9259:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 9260:     if ($udom && $uname && $file) {
 9261: 	$file=~s|(\?\.*)*$||;
 9262:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 9263:         my $homeserver = &homeserver($uname,$udom);
 9264:         my $protocol = $protocol{$homeserver};
 9265:         $protocol = 'http' if ($protocol ne 'https');
 9266:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
 9267:                (($uri=~/\?/)?'&':'?').'token='.$token.
 9268:                                '&tokenissued='.$perlvar{'lonHostID'};
 9269:     } else {
 9270:         return '/adm/notfound.html';
 9271:     }
 9272: }
 9273: 
 9274: # call with reqtype HEAD: get last modification time
 9275: # call with reqtype GET: get the file contents
 9276: # Do not call this with reqtype GET for large files! It loads everything into memory
 9277: #
 9278: sub getuploaded {
 9279:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 9280:     $uri=~s/^\///;
 9281:     my $homeserver = &homeserver($cnum,$cdom);
 9282:     my $protocol = $protocol{$homeserver};
 9283:     $protocol = 'http' if ($protocol ne 'https');
 9284:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
 9285:     my $ua=new LWP::UserAgent;
 9286:     my $request=new HTTP::Request($reqtype,$uri);
 9287:     my $response=$ua->request($request);
 9288:     $$rtncode = $response->code;
 9289:     if (! $response->is_success()) {
 9290: 	return 'failed';
 9291:     }      
 9292:     if ($reqtype eq 'HEAD') {
 9293: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 9294:     } elsif ($reqtype eq 'GET') {
 9295: 	$$info = $response->content;
 9296:     }
 9297:     return 'ok';
 9298: }
 9299: 
 9300: sub readfile {
 9301:     my $file = shift;
 9302:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 9303:     my $fh;
 9304:     open($fh,"<$file");
 9305:     my $a='';
 9306:     while (my $line = <$fh>) { $a .= $line; }
 9307:     return $a;
 9308: }
 9309: 
 9310: sub filelocation {
 9311:     my ($dir,$file) = @_;
 9312:     my $location;
 9313:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 9314: 
 9315:     if ($file =~ m-^/adm/-) {
 9316: 	$file=~s-^/adm/wrapper/-/-;
 9317: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 9318:     }
 9319: 
 9320:     if ($file=~m:^/~:) { # is a contruction space reference
 9321:         $location = $file;
 9322:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 9323:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 9324: 	# is a correct contruction space reference
 9325:         $location = $file;
 9326:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
 9327:         $location = $file;
 9328:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 9329:         my ($udom,$uname,$filename)=
 9330:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 9331:         my $home=&homeserver($uname,$udom);
 9332:         my $is_me=0;
 9333:         my @ids=&current_machine_ids();
 9334:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 9335:         if ($is_me) {
 9336:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
 9337:         } else {
 9338:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 9339:   	      $udom.'/'.$uname.'/'.$filename;
 9340:         }
 9341:     } elsif ($file =~ m-^/adm/-) {
 9342: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 9343:     } else {
 9344:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 9345:         $file=~s:^/res/:/:;
 9346:         if ( !( $file =~ m:^/:) ) {
 9347:             $location = $dir. '/'.$file;
 9348:         } else {
 9349:             $location = '/home/httpd/html/res'.$file;
 9350:         }
 9351:     }
 9352:     $location=~s://+:/:g; # remove duplicate /
 9353:     while ($location=~m{/\.\./}) {
 9354: 	if ($location =~ m{/[^/]+/\.\./}) {
 9355: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 9356: 	} else {
 9357: 	    $location=~ s{/\.\./}{/}g;
 9358: 	}
 9359:     } #remove dir/..
 9360:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 9361:     return $location;
 9362: }
 9363: 
 9364: sub hreflocation {
 9365:     my ($dir,$file)=@_;
 9366:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
 9367: 	$file=filelocation($dir,$file);
 9368:     } elsif ($file=~m-^/adm/-) {
 9369: 	$file=~s-^/adm/wrapper/-/-;
 9370: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 9371:     }
 9372:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 9373: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 9374:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 9375: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 9376:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 9377: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 9378: 	    -/uploaded/$1/$2/-x;
 9379:     }
 9380:     if ($file=~ m{^/userfiles/}) {
 9381: 	$file =~ s{^/userfiles/}{/uploaded/};
 9382:     }
 9383:     return $file;
 9384: }
 9385: 
 9386: sub current_machine_domains {
 9387:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 9388: }
 9389: 
 9390: sub machine_domains {
 9391:     my ($hostname) = @_;
 9392:     my @domains;
 9393:     my %hostname = &all_hostnames();
 9394:     while( my($id, $name) = each(%hostname)) {
 9395: #	&logthis("-$id-$name-$hostname-");
 9396: 	if ($hostname eq $name) {
 9397: 	    push(@domains,&host_domain($id));
 9398: 	}
 9399:     }
 9400:     return @domains;
 9401: }
 9402: 
 9403: sub current_machine_ids {
 9404:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 9405: }
 9406: 
 9407: sub machine_ids {
 9408:     my ($hostname) = @_;
 9409:     $hostname ||= &hostname($perlvar{'lonHostID'});
 9410:     my @ids;
 9411:     my %name_to_host = &all_names();
 9412:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 9413: 	return @{ $name_to_host{$hostname} };
 9414:     }
 9415:     return;
 9416: }
 9417: 
 9418: sub additional_machine_domains {
 9419:     my @domains;
 9420:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 9421:     while( my $line = <$fh>) {
 9422:         $line =~ s/\s//g;
 9423:         push(@domains,$line);
 9424:     }
 9425:     return @domains;
 9426: }
 9427: 
 9428: sub default_login_domain {
 9429:     my $domain = $perlvar{'lonDefDomain'};
 9430:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 9431:     foreach my $posdom (&current_machine_domains(),
 9432:                         &additional_machine_domains()) {
 9433:         if (lc($posdom) eq lc($testdomain)) {
 9434:             $domain=$posdom;
 9435:             last;
 9436:         }
 9437:     }
 9438:     return $domain;
 9439: }
 9440: 
 9441: # ------------------------------------------------------------- Declutters URLs
 9442: 
 9443: sub declutter {
 9444:     my $thisfn=shift;
 9445:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 9446:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 9447:     $thisfn=~s/^\///;
 9448:     $thisfn=~s|^adm/wrapper/||;
 9449:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 9450:     $thisfn=~s/^res\///;
 9451:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
 9452:         $thisfn=~s/\?.+$//;
 9453:     }
 9454:     return $thisfn;
 9455: }
 9456: 
 9457: # ------------------------------------------------------------- Clutter up URLs
 9458: 
 9459: sub clutter {
 9460:     my $thisfn='/'.&declutter(shift);
 9461:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 9462: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 9463:        $thisfn='/res'.$thisfn; 
 9464:     }
 9465:     if ($thisfn !~m|^/adm|) {
 9466: 	if ($thisfn =~ m|^/ext/|) {
 9467: 	    $thisfn='/adm/wrapper'.$thisfn;
 9468: 	} else {
 9469: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 9470: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 9471: 	    if ($embstyle eq 'ssi'
 9472: 		|| ($embstyle eq 'hdn')
 9473: 		|| ($embstyle eq 'rat')
 9474: 		|| ($embstyle eq 'prv')
 9475: 		|| ($embstyle eq 'ign')) {
 9476: 		#do nothing with these
 9477: 	    } elsif (($embstyle eq 'img') 
 9478: 		|| ($embstyle eq 'emb')
 9479: 		|| ($embstyle eq 'wrp')) {
 9480: 		$thisfn='/adm/wrapper'.$thisfn;
 9481: 	    } elsif ($embstyle eq 'unk'
 9482: 		     && $thisfn!~/\.(sequence|page)$/) {
 9483: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 9484: 	    } else {
 9485: #		&logthis("Got a blank emb style");
 9486: 	    }
 9487: 	}
 9488:     }
 9489:     return $thisfn;
 9490: }
 9491: 
 9492: sub clutter_with_no_wrapper {
 9493:     my $uri = &clutter(shift);
 9494:     if ($uri =~ m-^/adm/-) {
 9495: 	$uri =~ s-^/adm/wrapper/-/-;
 9496: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 9497:     }
 9498:     return $uri;
 9499: }
 9500: 
 9501: sub freeze_escape {
 9502:     my ($value)=@_;
 9503:     if (ref($value)) {
 9504: 	$value=&nfreeze($value);
 9505: 	return '__FROZEN__'.&escape($value);
 9506:     }
 9507:     return &escape($value);
 9508: }
 9509: 
 9510: 
 9511: sub thaw_unescape {
 9512:     my ($value)=@_;
 9513:     if ($value =~ /^__FROZEN__/) {
 9514: 	substr($value,0,10,undef);
 9515: 	$value=&unescape($value);
 9516: 	return &thaw($value);
 9517:     }
 9518:     return &unescape($value);
 9519: }
 9520: 
 9521: sub correct_line_ends {
 9522:     my ($result)=@_;
 9523:     $$result =~s/\r\n/\n/mg;
 9524:     $$result =~s/\r/\n/mg;
 9525: }
 9526: # ================================================================ Main Program
 9527: 
 9528: sub goodbye {
 9529:    &logthis("Starting Shut down");
 9530: #not converted to using infrastruture and probably shouldn't be
 9531:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 9532: #converted
 9533: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 9534:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 9535: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 9536: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 9537: #1.1 only
 9538: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 9539: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 9540: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 9541: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 9542:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 9543:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 9544:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 9545:    &flushcourselogs();
 9546:    &logthis("Shutting down");
 9547: }
 9548: 
 9549: sub get_dns {
 9550:     my ($url,$func,$ignore_cache) = @_;
 9551:     if (!$ignore_cache) {
 9552: 	my ($content,$cached)=
 9553: 	    &Apache::lonnet::is_cached_new('dns',$url);
 9554: 	if ($cached) {
 9555: 	    &$func($content);
 9556: 	    return;
 9557: 	}
 9558:     }
 9559: 
 9560:     my %alldns;
 9561:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 9562:     foreach my $dns (<$config>) {
 9563: 	next if ($dns !~ /^\^(\S*)/x);
 9564:         my $line = $1;
 9565:         my ($host,$protocol) = split(/:/,$line);
 9566:         if ($protocol ne 'https') {
 9567:             $protocol = 'http';
 9568:         }
 9569: 	$alldns{$host} = $protocol;
 9570:     }
 9571:     while (%alldns) {
 9572: 	my ($dns) = keys(%alldns);
 9573: 	my $ua=new LWP::UserAgent;
 9574: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
 9575: 	my $response=$ua->request($request);
 9576:         delete($alldns{$dns});
 9577: 	next if ($response->is_error());
 9578: 	my @content = split("\n",$response->content);
 9579: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 9580: 	&$func(\@content);
 9581: 	return;
 9582:     }
 9583:     close($config);
 9584:     my $which = (split('/',$url))[3];
 9585:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 9586:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 9587:     my @content = <$config>;
 9588:     &$func(\@content);
 9589:     return;
 9590: }
 9591: # ------------------------------------------------------------ Read domain file
 9592: {
 9593:     my $loaded;
 9594:     my %domain;
 9595: 
 9596:     sub parse_domain_tab {
 9597: 	my ($lines) = @_;
 9598: 	foreach my $line (@$lines) {
 9599: 	    next if ($line =~ /^(\#|\s*$ )/x);
 9600: 
 9601: 	    chomp($line);
 9602: 	    my ($name,@elements) = split(/:/,$line,9);
 9603: 	    my %this_domain;
 9604: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 9605: 			       'lang_def', 'city', 'longi', 'lati',
 9606: 			       'primary') {
 9607: 		$this_domain{$field} = shift(@elements);
 9608: 	    }
 9609: 	    $domain{$name} = \%this_domain;
 9610: 	}
 9611:     }
 9612: 
 9613:     sub reset_domain_info {
 9614: 	undef($loaded);
 9615: 	undef(%domain);
 9616:     }
 9617: 
 9618:     sub load_domain_tab {
 9619: 	my ($ignore_cache) = @_;
 9620: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 9621: 	my $fh;
 9622: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 9623: 	    my @lines = <$fh>;
 9624: 	    &parse_domain_tab(\@lines);
 9625: 	}
 9626: 	close($fh);
 9627: 	$loaded = 1;
 9628:     }
 9629: 
 9630:     sub domain {
 9631: 	&load_domain_tab() if (!$loaded);
 9632: 
 9633: 	my ($name,$what) = @_;
 9634: 	return if ( !exists($domain{$name}) );
 9635: 
 9636: 	if (!$what) {
 9637: 	    return $domain{$name}{'description'};
 9638: 	}
 9639: 	return $domain{$name}{$what};
 9640:     }
 9641: 
 9642:     sub domain_info {
 9643:         &load_domain_tab() if (!$loaded);
 9644:         return %domain;
 9645:     }
 9646: 
 9647: }
 9648: 
 9649: 
 9650: # ------------------------------------------------------------- Read hosts file
 9651: {
 9652:     my %hostname;
 9653:     my %hostdom;
 9654:     my %libserv;
 9655:     my $loaded;
 9656:     my %name_to_host;
 9657: 
 9658:     sub parse_hosts_tab {
 9659: 	my ($file) = @_;
 9660: 	foreach my $configline (@$file) {
 9661: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 9662: 	    next if ($configline =~ /^\^/);
 9663: 	    chomp($configline);
 9664: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
 9665: 	    $name=~s/\s//g;
 9666: 	    if ($id && $domain && $role && $name) {
 9667: 		$hostname{$id}=$name;
 9668: 		push(@{$name_to_host{$name}}, $id);
 9669: 		$hostdom{$id}=$domain;
 9670: 		if ($role eq 'library') { $libserv{$id}=$name; }
 9671:                 if (defined($protocol)) {
 9672:                     if ($protocol eq 'https') {
 9673:                         $protocol{$id} = $protocol;
 9674:                     } else {
 9675:                         $protocol{$id} = 'http'; 
 9676:                     }
 9677:                 } else {
 9678:                     $protocol{$id} = 'http';
 9679:                 }
 9680: 	    }
 9681: 	}
 9682:     }
 9683:     
 9684:     sub reset_hosts_info {
 9685: 	&purge_remembered();
 9686: 	&reset_domain_info();
 9687: 	&reset_hosts_ip_info();
 9688: 	undef(%name_to_host);
 9689: 	undef(%hostname);
 9690: 	undef(%hostdom);
 9691: 	undef(%libserv);
 9692: 	undef($loaded);
 9693:     }
 9694: 
 9695:     sub load_hosts_tab {
 9696: 	my ($ignore_cache) = @_;
 9697: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 9698: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 9699: 	my @config = <$config>;
 9700: 	&parse_hosts_tab(\@config);
 9701: 	close($config);
 9702: 	$loaded=1;
 9703:     }
 9704: 
 9705:     sub hostname {
 9706: 	&load_hosts_tab() if (!$loaded);
 9707: 
 9708: 	my ($lonid) = @_;
 9709: 	return $hostname{$lonid};
 9710:     }
 9711: 
 9712:     sub all_hostnames {
 9713: 	&load_hosts_tab() if (!$loaded);
 9714: 
 9715: 	return %hostname;
 9716:     }
 9717: 
 9718:     sub all_names {
 9719: 	&load_hosts_tab() if (!$loaded);
 9720: 
 9721: 	return %name_to_host;
 9722:     }
 9723: 
 9724:     sub all_host_domain {
 9725:         &load_hosts_tab() if (!$loaded);
 9726:         return %hostdom;
 9727:     }
 9728: 
 9729:     sub is_library {
 9730: 	&load_hosts_tab() if (!$loaded);
 9731: 
 9732: 	return exists($libserv{$_[0]});
 9733:     }
 9734: 
 9735:     sub all_library {
 9736: 	&load_hosts_tab() if (!$loaded);
 9737: 
 9738: 	return %libserv;
 9739:     }
 9740: 
 9741:     sub get_servers {
 9742: 	&load_hosts_tab() if (!$loaded);
 9743: 
 9744: 	my ($domain,$type) = @_;
 9745: 	my %possible_hosts = ($type eq 'library') ? %libserv
 9746: 	                                          : %hostname;
 9747: 	my %result;
 9748: 	if (ref($domain) eq 'ARRAY') {
 9749: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9750: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 9751: 		    $result{$host} = $hostname;
 9752: 		}
 9753: 	    }
 9754: 	} else {
 9755: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9756: 		if ($hostdom{$host} eq $domain) {
 9757: 		    $result{$host} = $hostname;
 9758: 		}
 9759: 	    }
 9760: 	}
 9761: 	return %result;
 9762:     }
 9763: 
 9764:     sub host_domain {
 9765: 	&load_hosts_tab() if (!$loaded);
 9766: 
 9767: 	my ($lonid) = @_;
 9768: 	return $hostdom{$lonid};
 9769:     }
 9770: 
 9771:     sub all_domains {
 9772: 	&load_hosts_tab() if (!$loaded);
 9773: 
 9774: 	my %seen;
 9775: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 9776: 	return @uniq;
 9777:     }
 9778: }
 9779: 
 9780: { 
 9781:     my %iphost;
 9782:     my %name_to_ip;
 9783:     my %lonid_to_ip;
 9784: 
 9785:     sub get_hosts_from_ip {
 9786: 	my ($ip) = @_;
 9787: 	my %iphosts = &get_iphost();
 9788: 	if (ref($iphosts{$ip})) {
 9789: 	    return @{$iphosts{$ip}};
 9790: 	}
 9791: 	return;
 9792:     }
 9793:     
 9794:     sub reset_hosts_ip_info {
 9795: 	undef(%iphost);
 9796: 	undef(%name_to_ip);
 9797: 	undef(%lonid_to_ip);
 9798:     }
 9799: 
 9800:     sub get_host_ip {
 9801: 	my ($lonid) = @_;
 9802: 	if (exists($lonid_to_ip{$lonid})) {
 9803: 	    return $lonid_to_ip{$lonid};
 9804: 	}
 9805: 	my $name=&hostname($lonid);
 9806:    	my $ip = gethostbyname($name);
 9807: 	return if (!$ip || length($ip) ne 4);
 9808: 	$ip=inet_ntoa($ip);
 9809: 	$name_to_ip{$name}   = $ip;
 9810: 	$lonid_to_ip{$lonid} = $ip;
 9811: 	return $ip;
 9812:     }
 9813:     
 9814:     sub get_iphost {
 9815: 	my ($ignore_cache) = @_;
 9816: 
 9817: 	if (!$ignore_cache) {
 9818: 	    if (%iphost) {
 9819: 		return %iphost;
 9820: 	    }
 9821: 	    my ($ip_info,$cached)=
 9822: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 9823: 	    if ($cached) {
 9824: 		%iphost      = %{$ip_info->[0]};
 9825: 		%name_to_ip  = %{$ip_info->[1]};
 9826: 		%lonid_to_ip = %{$ip_info->[2]};
 9827: 		return %iphost;
 9828: 	    }
 9829: 	}
 9830: 
 9831: 	# get yesterday's info for fallback
 9832: 	my %old_name_to_ip;
 9833: 	my ($ip_info,$cached)=
 9834: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 9835: 	if ($cached) {
 9836: 	    %old_name_to_ip = %{$ip_info->[1]};
 9837: 	}
 9838: 
 9839: 	my %name_to_host = &all_names();
 9840: 	foreach my $name (keys(%name_to_host)) {
 9841: 	    my $ip;
 9842: 	    if (!exists($name_to_ip{$name})) {
 9843: 		$ip = gethostbyname($name);
 9844: 		if (!$ip || length($ip) ne 4) {
 9845: 		    if (defined($old_name_to_ip{$name})) {
 9846: 			$ip = $old_name_to_ip{$name};
 9847: 			&logthis("Can't find $name defaulting to old $ip");
 9848: 		    } else {
 9849: 			&logthis("Name $name no IP found");
 9850: 			next;
 9851: 		    }
 9852: 		} else {
 9853: 		    $ip=inet_ntoa($ip);
 9854: 		}
 9855: 		$name_to_ip{$name} = $ip;
 9856: 	    } else {
 9857: 		$ip = $name_to_ip{$name};
 9858: 	    }
 9859: 	    foreach my $id (@{ $name_to_host{$name} }) {
 9860: 		$lonid_to_ip{$id} = $ip;
 9861: 	    }
 9862: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 9863: 	}
 9864: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 9865: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 9866: 				      48*60*60);
 9867: 
 9868: 	return %iphost;
 9869:     }
 9870: 
 9871:     #
 9872:     #  Given a DNS returns the loncapa host name for that DNS 
 9873:     # 
 9874:     sub host_from_dns {
 9875:         my ($dns) = @_;
 9876:         my @hosts;
 9877:         my $ip;
 9878: 
 9879:         if (exists($name_to_ip{$dns})) {
 9880:             $ip = $name_to_ip{$dns};
 9881:         }
 9882:         if (!$ip) {
 9883:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
 9884:             if (length($ip) == 4) { 
 9885: 	        $ip   = &IO::Socket::inet_ntoa($ip);
 9886:             }
 9887:         }
 9888:         if ($ip) {
 9889: 	    @hosts = get_hosts_from_ip($ip);
 9890: 	    return $hosts[0];
 9891:         }
 9892:         return undef;
 9893:     }
 9894: 
 9895: }
 9896: 
 9897: BEGIN {
 9898: 
 9899: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 9900:     unless ($readit) {
 9901: {
 9902:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 9903:     %perlvar = (%perlvar,%{$configvars});
 9904: }
 9905: 
 9906: 
 9907: # ------------------------------------------------------ Read spare server file
 9908: {
 9909:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 9910: 
 9911:     while (my $configline=<$config>) {
 9912:        chomp($configline);
 9913:        if ($configline) {
 9914: 	   my ($host,$type) = split(':',$configline,2);
 9915: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 9916: 	   push(@{ $spareid{$type} }, $host);
 9917:        }
 9918:     }
 9919:     close($config);
 9920: }
 9921: # ------------------------------------------------------------ Read permissions
 9922: {
 9923:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 9924: 
 9925:     while (my $configline=<$config>) {
 9926: 	chomp($configline);
 9927: 	if ($configline) {
 9928: 	    my ($role,$perm)=split(/ /,$configline);
 9929: 	    if ($perm ne '') { $pr{$role}=$perm; }
 9930: 	}
 9931:     }
 9932:     close($config);
 9933: }
 9934: 
 9935: # -------------------------------------------- Read plain texts for permissions
 9936: {
 9937:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 9938: 
 9939:     while (my $configline=<$config>) {
 9940: 	chomp($configline);
 9941: 	if ($configline) {
 9942: 	    my ($short,@plain)=split(/:/,$configline);
 9943:             %{$prp{$short}} = ();
 9944: 	    if (@plain > 0) {
 9945:                 $prp{$short}{'std'} = $plain[0];
 9946:                 for (my $i=1; $i<@plain; $i++) {
 9947:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 9948:                 }
 9949:             }
 9950: 	}
 9951:     }
 9952:     close($config);
 9953: }
 9954: 
 9955: # ---------------------------------------------------------- Read package table
 9956: {
 9957:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 9958: 
 9959:     while (my $configline=<$config>) {
 9960: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 9961: 	chomp($configline);
 9962: 	my ($short,$plain)=split(/:/,$configline);
 9963: 	my ($pack,$name)=split(/\&/,$short);
 9964: 	if ($plain ne '') {
 9965: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 9966: 	    $packagetab{$short}=$plain; 
 9967: 	}
 9968:     }
 9969:     close($config);
 9970: }
 9971: 
 9972: # ------------- set up temporary directory
 9973: {
 9974:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 9975: 
 9976: }
 9977: 
 9978: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 9979: 				'compress_threshold'=> 20_000,
 9980:  			        });
 9981: 
 9982: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 9983: $dumpcount=0;
 9984: $locknum=0;
 9985: 
 9986: &logtouch();
 9987: &logthis('<font color="yellow">INFO: Read configuration</font>');
 9988: $readit=1;
 9989:     {
 9990: 	use integer;
 9991: 	my $test=(2**32)+1;
 9992: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 9993: 	&logthis(" Detected 64bit platform ($_64bit)");
 9994:     }
 9995: }
 9996: }
 9997: 
 9998: 1;
 9999: __END__
10000: 
10001: =pod
10002: 
10003: =head1 NAME
10004: 
10005: Apache::lonnet - Subroutines to ask questions about things in the network.
10006: 
10007: =head1 SYNOPSIS
10008: 
10009: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
10010: 
10011:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
10012: 
10013: Common parameters:
10014: 
10015: =over 4
10016: 
10017: =item *
10018: 
10019: $uname : an internal username (if $cname expecting a course Id specifically)
10020: 
10021: =item *
10022: 
10023: $udom : a domain (if $cdom expecting a course's domain specifically)
10024: 
10025: =item *
10026: 
10027: $symb : a resource instance identifier
10028: 
10029: =item *
10030: 
10031: $namespace : the name of a .db file that contains the data needed or
10032: being set.
10033: 
10034: =back
10035: 
10036: =head1 OVERVIEW
10037: 
10038: lonnet provides subroutines which interact with the
10039: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
10040: about classes, users, and resources.
10041: 
10042: For many of these objects you can also use this to store data about
10043: them or modify them in various ways.
10044: 
10045: =head2 Symbs
10046: 
10047: To identify a specific instance of a resource, LON-CAPA uses symbols
10048: or "symbs"X<symb>. These identifiers are built from the URL of the
10049: map, the resource number of the resource in the map, and the URL of
10050: the resource itself. The latter is somewhat redundant, but might help
10051: if maps change.
10052: 
10053: An example is
10054: 
10055:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
10056: 
10057: The respective map entry is
10058: 
10059:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
10060:   title="Problem 2">
10061:  </resource>
10062: 
10063: Symbs are used by the random number generator, as well as to store and
10064: restore data specific to a certain instance of for example a problem.
10065: 
10066: =head2 Storing And Retrieving Data
10067: 
10068: X<store()>X<cstore()>X<restore()>Three of the most important functions
10069: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
10070: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
10071: is is the non-critical message twin of cstore. These functions are for
10072: handlers to store a perl hash to a user's permanent data space in an
10073: easy manner, and to retrieve it again on another call. It is expected
10074: that a handler would use this once at the beginning to retrieve data,
10075: and then again once at the end to send only the new data back.
10076: 
10077: The data is stored in the user's data directory on the user's
10078: homeserver under the ID of the course.
10079: 
10080: The hash that is returned by restore will have all of the previous
10081: value for all of the elements of the hash.
10082: 
10083: Example:
10084: 
10085:  #creating a hash
10086:  my %hash;
10087:  $hash{'foo'}='bar';
10088: 
10089:  #storing it
10090:  &Apache::lonnet::cstore(\%hash);
10091: 
10092:  #changing a value
10093:  $hash{'foo'}='notbar';
10094: 
10095:  #adding a new value
10096:  $hash{'bar'}='foo';
10097:  &Apache::lonnet::cstore(\%hash);
10098: 
10099:  #retrieving the hash
10100:  my %history=&Apache::lonnet::restore();
10101: 
10102:  #print the hash
10103:  foreach my $key (sort(keys(%history))) {
10104:    print("\%history{$key} = $history{$key}");
10105:  }
10106: 
10107: Will print out:
10108: 
10109:  %history{1:foo} = bar
10110:  %history{1:keys} = foo:timestamp
10111:  %history{1:timestamp} = 990455579
10112:  %history{2:bar} = foo
10113:  %history{2:foo} = notbar
10114:  %history{2:keys} = foo:bar:timestamp
10115:  %history{2:timestamp} = 990455580
10116:  %history{bar} = foo
10117:  %history{foo} = notbar
10118:  %history{timestamp} = 990455580
10119:  %history{version} = 2
10120: 
10121: Note that the special hash entries C<keys>, C<version> and
10122: C<timestamp> were added to the hash. C<version> will be equal to the
10123: total number of versions of the data that have been stored. The
10124: C<timestamp> attribute will be the UNIX time the hash was
10125: stored. C<keys> is available in every historical section to list which
10126: keys were added or changed at a specific historical revision of a
10127: hash.
10128: 
10129: B<Warning>: do not store the hash that restore returns directly. This
10130: will cause a mess since it will restore the historical keys as if the
10131: were new keys. I.E. 1:foo will become 1:1:foo etc.
10132: 
10133: Calling convention:
10134: 
10135:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10136:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
10137: 
10138: For more detailed information, see lonnet specific documentation.
10139: 
10140: =head1 RETURN MESSAGES
10141: 
10142: =over 4
10143: 
10144: =item * B<con_lost>: unable to contact remote host
10145: 
10146: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10147: when the connection is brought back up
10148: 
10149: =item * B<con_failed>: unable to contact remote host and unable to save message
10150: for later delivery
10151: 
10152: =item * B<error:>: an error a occurred, a description of the error follows the :
10153: 
10154: =item * B<no_such_host>: unable to fund a host associated with the user/domain
10155: that was requested
10156: 
10157: =back
10158: 
10159: =head1 PUBLIC SUBROUTINES
10160: 
10161: =head2 Session Environment Functions
10162: 
10163: =over 4
10164: 
10165: =item * 
10166: X<appenv()>
10167: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
10168: the user envirnoment file, and will be restored for each access this
10169: user makes during this session, also modifies the %env for the current
10170: process. Optional rolesarrayref - if defined contains a reference to an array
10171: of roles which are exempt from the restriction on modifying user.role entries 
10172: in the user's environment.db and in %env.    
10173: 
10174: =item *
10175: X<delenv()>
10176: B<delenv($delthis,$regexp)>: removes all items from the session
10177: environment file that begin with $delthis. If the 
10178: optional second arg - $regexp - is true, $delthis is treated as a 
10179: regular expression, otherwise \Q$delthis\E is used. 
10180: The values are also deleted from the current processes %env.
10181: 
10182: =item * get_env_multiple($name) 
10183: 
10184: gets $name from the %env hash, it seemlessly handles the cases where multiple
10185: values may be defined and end up as an array ref.
10186: 
10187: returns an array of values
10188: 
10189: =back
10190: 
10191: =head2 User Information
10192: 
10193: =over 4
10194: 
10195: =item *
10196: X<queryauthenticate()>
10197: B<queryauthenticate($uname,$udom)>: try to determine user's current 
10198: authentication scheme
10199: 
10200: =item *
10201: X<authenticate()>
10202: B<authenticate($uname,$upass,$udom)>: try to
10203: authenticate user from domain's lib servers (first use the current
10204: one). C<$upass> should be the users password.
10205: 
10206: =item *
10207: X<homeserver()>
10208: B<homeserver($uname,$udom)>: find the server which has
10209: the user's directory and files (there must be only one), this caches
10210: the answer, and also caches if there is a borken connection.
10211: 
10212: =item *
10213: X<idget()>
10214: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10215: (IDs are a unique resource in a domain, there must be only 1 ID per
10216: username, and only 1 username per ID in a specific domain) (returns
10217: hash: id=>name,id=>name)
10218: 
10219: =item *
10220: X<idrget()>
10221: B<idrget($udom,@unames)>: find the IDs behind a list of
10222: usernames (returns hash: name=>id,name=>id)
10223: 
10224: =item *
10225: X<idput()>
10226: B<idput($udom,%ids)>: store away a list of names and associated IDs
10227: 
10228: =item *
10229: X<rolesinit()>
10230: B<rolesinit($udom,$username,$authhost)>: get user privileges
10231: 
10232: =item *
10233: X<getsection()>
10234: B<getsection($udom,$uname,$cname)>: finds the section of student in the
10235: course $cname, return section name/number or '' for "not in course"
10236: and '-1' for "no section"
10237: 
10238: =item *
10239: X<userenvironment()>
10240: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
10241: passed in @what from the requested user's environment, returns a hash
10242: 
10243: =item * 
10244: X<userlog_query()>
10245: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10246: activity.log file. %filters defines filters applied when parsing the
10247: log file. These can be start or end timestamps, or the type of action
10248: - log to look for Login or Logout events, check for Checkin or
10249: Checkout, role for role selection. The response is in the form
10250: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
10251: escaped strings of the action recorded in the activity.log file.
10252: 
10253: =back
10254: 
10255: =head2 User Roles
10256: 
10257: =over 4
10258: 
10259: =item *
10260: 
10261: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
10262:  F: full access
10263:  U,I,K: authentication modes (cxx only)
10264:  '': forbidden
10265:  1: user needs to choose course
10266:  2: browse allowed
10267:  A: passphrase authentication needed
10268: 
10269: =item *
10270: 
10271: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10272: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10273: and course level
10274: 
10275: =item *
10276: 
10277: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
10278: (rolesplain.tab); plain text explanation of a user role term.
10279: $type is Course (default) or Community.
10280: If $forcedefault evaluates to true, text returned will be default 
10281: text for $type. Otherwise, if this is a course, the text returned 
10282: will be a custom name for the role (if defined in the course's 
10283: environment).  If no custom name is defined the default is returned.
10284:    
10285: =item *
10286: 
10287: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
10288: All arguments are optional. Returns a hash of a roles, either for
10289: co-author/assistant author roles for a user's Construction Space
10290: (default), or if $context is 'userroles', roles for the user himself,
10291: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10292: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10293: For each key, value is set to colon-separated start and end times for
10294: the role.  If no username and domain are specified, will default to
10295: current user/domain. Types, roles, and roledoms are references to arrays
10296: of role statuses (active, future or previous), roles 
10297: (e.g., cc,in, st etc.) and domains of the roles which can be used
10298: to restrict the list of roles reported. If no array ref is 
10299: provided for types, will default to return only active roles.
10300: 
10301: =back
10302: 
10303: =head2 User Modification
10304: 
10305: =over 4
10306: 
10307: =item *
10308: 
10309: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
10310: user for the level given by URL.  Optional start and end dates (leave empty
10311: string or zero for "no date")
10312: 
10313: =item *
10314: 
10315: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10316: change a users, password, possible return values are: ok,
10317: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10318: refused
10319: 
10320: =item *
10321: 
10322: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
10323: 
10324: =item *
10325: 
10326: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
10327:            $forceid,$desiredhome,$email,$inststatus) : 
10328: modify user
10329: 
10330: =item *
10331: 
10332: modifystudent
10333: 
10334: modify a student's enrollment and identification information.
10335: The course id is resolved based on the current users environment.  
10336: This means the envoking user must be a course coordinator or otherwise
10337: associated with a course.
10338: 
10339: This call is essentially a wrapper for lonnet::modifyuser and
10340: lonnet::modify_student_enrollment
10341: 
10342: Inputs: 
10343: 
10344: =over 4
10345: 
10346: =item B<$udom> Student's loncapa domain
10347: 
10348: =item B<$uname> Student's loncapa login name
10349: 
10350: =item B<$uid> Student/Employee ID
10351: 
10352: =item B<$umode> Student's authentication mode
10353: 
10354: =item B<$upass> Student's password
10355: 
10356: =item B<$first> Student's first name
10357: 
10358: =item B<$middle> Student's middle name
10359: 
10360: =item B<$last> Student's last name
10361: 
10362: =item B<$gene> Student's generation
10363: 
10364: =item B<$usec> Student's section in course
10365: 
10366: =item B<$end> Unix time of the roles expiration
10367: 
10368: =item B<$start> Unix time of the roles start date
10369: 
10370: =item B<$forceid> If defined, allow $uid to be changed
10371: 
10372: =item B<$desiredhome> server to use as home server for student
10373: 
10374: =item B<$email> Student's permanent e-mail address
10375: 
10376: =item B<$type> Type of enrollment (auto or manual)
10377: 
10378: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
10379: 
10380: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
10381: 
10382: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
10383: 
10384: =item B<$context> role change context (shown in User Management Logs display in a course)
10385: 
10386: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
10387: 
10388: =back
10389: 
10390: =item *
10391: 
10392: modify_student_enrollment
10393: 
10394: Change a students enrollment status in a class.  The environment variable
10395: 'role.request.course' must be defined for this function to proceed.
10396: 
10397: Inputs:
10398: 
10399: =over 4
10400: 
10401: =item $udom, students domain
10402: 
10403: =item $uname, students name
10404: 
10405: =item $uid, students user id
10406: 
10407: =item $first, students first name
10408: 
10409: =item $middle
10410: 
10411: =item $last
10412: 
10413: =item $gene
10414: 
10415: =item $usec
10416: 
10417: =item $end
10418: 
10419: =item $start
10420: 
10421: =item $type
10422: 
10423: =item $locktype
10424: 
10425: =item $cid
10426: 
10427: =item $selfenroll
10428: 
10429: =item $context
10430: 
10431: =back
10432: 
10433: 
10434: =item *
10435: 
10436: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10437: custom role; give a custom role to a user for the level given by URL.  Specify
10438: name and domain of role author, and role name
10439: 
10440: =item *
10441: 
10442: revokerole($udom,$uname,$url,$role) : revoke a role for url
10443: 
10444: =item *
10445: 
10446: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10447: 
10448: =back
10449: 
10450: =head2 Course Infomation
10451: 
10452: =over 4
10453: 
10454: =item *
10455: 
10456: coursedescription($courseid) : returns a hash of information about the
10457: specified course id, including all environment settings for the
10458: course, the description of the course will be in the hash under the
10459: key 'description'
10460: 
10461: =item *
10462: 
10463: resdata($name,$domain,$type,@which) : request for current parameter
10464: setting for a specific $type, where $type is either 'course' or 'user',
10465: @what should be a list of parameters to ask about. This routine caches
10466: answers for 5 minutes.
10467: 
10468: =item *
10469: 
10470: get_courseresdata($courseid, $domain) : dump the entire course resource
10471: data base, returning a hash that is keyed by the resource name and has
10472: values that are the resource value.  I believe that the timestamps and
10473: versions are also returned.
10474: 
10475: 
10476: =back
10477: 
10478: =head2 Course Modification
10479: 
10480: =over 4
10481: 
10482: =item *
10483: 
10484: writecoursepref($courseid,%prefs) : write preferences (environment
10485: database) for a course
10486: 
10487: =item *
10488: 
10489: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10490: 
10491: =item *
10492: 
10493: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
10494: 
10495: =back
10496: 
10497: =head2 Resource Subroutines
10498: 
10499: =over 4
10500: 
10501: =item *
10502: 
10503: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
10504: 
10505: =item *
10506: 
10507: repcopy($filename) : subscribes to the requested file, and attempts to
10508: replicate from the owning library server, Might return
10509: 'unavailable', 'not_found', 'forbidden', 'ok', or
10510: 'bad_request', also attempts to grab the metadata for the
10511: resource. Expects the local filesystem pathname
10512: (/home/httpd/html/res/....)
10513: 
10514: =back
10515: 
10516: =head2 Resource Information
10517: 
10518: =over 4
10519: 
10520: =item *
10521: 
10522: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10523: a vairety of different possible values, $varname should be a request
10524: string, and the other parameters can be used to specify who and what
10525: one is asking about.
10526: 
10527: Possible values for $varname are environment.lastname (or other item
10528: from the envirnment hash), user.name (or someother aspect about the
10529: user), resource.0.maxtries (or some other part and parameter of a
10530: resource)
10531: 
10532: =item *
10533: 
10534: directcondval($number) : get current value of a condition; reads from a state
10535: string
10536: 
10537: =item *
10538: 
10539: condval($condidx) : value of condition index based on state
10540: 
10541: =item *
10542: 
10543: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
10544: resource's metadata, $what should be either a specific key, or either
10545: 'keys' (to get a list of possible keys) or 'packages' to get a list of
10546: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
10547: 
10548: this function automatically caches all requests
10549: 
10550: =item *
10551: 
10552: metadata_query($query,$custom,$customshow) : make a metadata query against the
10553: network of library servers; returns file handle of where SQL and regex results
10554: will be stored for query
10555: 
10556: =item *
10557: 
10558: symbread($filename) : return symbolic list entry (filename argument optional);
10559: returns the data handle
10560: 
10561: =item *
10562: 
10563: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
10564: a possible symb for the URL in $thisfn, and if is an encryypted
10565: resource that the user accessed using /enc/ returns a 1 on success, 0
10566: on failure, user must be in a course, as it assumes the existance of
10567: the course initial hash, and uses $env('request.course.id'}
10568: 
10569: 
10570: =item *
10571: 
10572: symbclean($symb) : removes versions numbers from a symb, returns the
10573: cleaned symb
10574: 
10575: =item *
10576: 
10577: is_on_map($uri) : checks if the $uri is somewhere on the current
10578: course map, user must be in a course for it to work.
10579: 
10580: =item *
10581: 
10582: numval($salt) : return random seed value (addend for rndseed)
10583: 
10584: =item *
10585: 
10586: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10587: a random seed, all arguments are optional, if they aren't sent it uses the
10588: environment to derive them. Note: if symb isn't sent and it can't get one
10589: from &symbread it will use the current time as its return value
10590: 
10591: =item *
10592: 
10593: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10594: unfakeable, receipt
10595: 
10596: =item *
10597: 
10598: receipt() : API to ireceipt working off of env values; given out to users
10599: 
10600: =item *
10601: 
10602: countacc($url) : count the number of accesses to a given URL
10603: 
10604: =item *
10605: 
10606: 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
10607: 
10608: =item *
10609: 
10610: 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)
10611: 
10612: =item *
10613: 
10614: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
10615: 
10616: =item *
10617: 
10618: devalidate($symb) : devalidate temporary spreadsheet calculations,
10619: forcing spreadsheet to reevaluate the resource scores next time.
10620: 
10621: =back
10622: 
10623: =head2 Storing/Retreiving Data
10624: 
10625: =over 4
10626: 
10627: =item *
10628: 
10629: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
10630: for this url; hashref needs to be given and should be a \%hashname; the
10631: remaining args aren't required and if they aren't passed or are '' they will
10632: be derived from the env
10633: 
10634: =item *
10635: 
10636: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
10637: uses critical subroutine
10638: 
10639: =item *
10640: 
10641: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
10642: all args are optional
10643: 
10644: =item *
10645: 
10646: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
10647: dumps the complete (or key matching regexp) namespace into a hash
10648: ($udom, $uname, $regexp, $range are optional) for a namespace that is
10649: normally &store()ed into
10650: 
10651: $range should be either an integer '100' (give me the first 100
10652:                                            matching records)
10653:               or be  two integers sperated by a - with no spaces
10654:                  '30-50' (give me the 30th through the 50th matching
10655:                           records)
10656: 
10657: 
10658: =item *
10659: 
10660: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
10661: replaces a &store() version of data with a replacement set of data
10662: for a particular resource in a namespace passed in the $storehash hash 
10663: reference
10664: 
10665: =item *
10666: 
10667: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
10668: works very similar to store/cstore, but all data is stored in a
10669: temporary location and can be reset using tmpreset, $storehash should
10670: be a hash reference, returns nothing on success
10671: 
10672: =item *
10673: 
10674: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
10675: similar to restore, but all data is stored in a temporary location and
10676: can be reset using tmpreset. Returns a hash of values on success,
10677: error string otherwise.
10678: 
10679: =item *
10680: 
10681: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
10682: deltes all keys for $symb form the temporary storage hash.
10683: 
10684: =item *
10685: 
10686: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10687: reference filled in from namesp ($udom and $uname are optional)
10688: 
10689: =item *
10690: 
10691: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
10692: namesp ($udom and $uname are optional)
10693: 
10694: =item *
10695: 
10696: dump($namespace,$udom,$uname,$regexp,$range) : 
10697: dumps the complete (or key matching regexp) namespace into a hash
10698: ($udom, $uname, $regexp, $range are optional)
10699: 
10700: $range should be either an integer '100' (give me the first 100
10701:                                            matching records)
10702:               or be  two integers sperated by a - with no spaces
10703:                  '30-50' (give me the 30th through the 50th matching
10704:                           records)
10705: =item *
10706: 
10707: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
10708: $store can be a scalar, an array reference, or if the amount to be 
10709: incremented is > 1, a hash reference.
10710: 
10711: ($udom and $uname are optional)
10712: 
10713: =item *
10714: 
10715: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
10716: ($udom and $uname are optional)
10717: 
10718: =item *
10719: 
10720: cput($namespace,$storehash,$udom,$uname) : critical put
10721: ($udom and $uname are optional)
10722: 
10723: =item *
10724: 
10725: newput($namespace,$storehash,$udom,$uname) :
10726: 
10727: Attempts to store the items in the $storehash, but only if they don't
10728: currently exist, if this succeeds you can be certain that you have 
10729: successfully created a new key value pair in the $namespace db.
10730: 
10731: 
10732: Args:
10733:  $namespace: name of database to store values to
10734:  $storehash: hashref to store to the db
10735:  $udom: (optional) domain of user containing the db
10736:  $uname: (optional) name of user caontaining the db
10737: 
10738: Returns:
10739:  'ok' -> succeeded in storing all keys of $storehash
10740:  'key_exists: <key>' -> failed to anything out of $storehash, as at
10741:                         least <key> already existed in the db (other
10742:                         requested keys may also already exist)
10743:  'error: <msg>' -> unable to tie the DB or other error occurred
10744:  'con_lost' -> unable to contact request server
10745:  'refused' -> action was not allowed by remote machine
10746: 
10747: 
10748: =item *
10749: 
10750: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10751: reference filled in from namesp (encrypts the return communication)
10752: ($udom and $uname are optional)
10753: 
10754: =item *
10755: 
10756: log($udom,$name,$home,$message) : write to permanent log for user; use
10757: critical subroutine
10758: 
10759: =item *
10760: 
10761: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
10762: array reference filled in from namespace found in domain level on either
10763: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
10764: 
10765: =item *
10766: 
10767: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
10768: domain level either on specified domain server ($uhome) or primary domain 
10769: server ($udom and $uhome are optional)
10770: 
10771: =item * 
10772: 
10773: get_domain_defaults($target_domain) : returns hash with defaults for
10774: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
10775: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
10776: or localauth), initial password or a kerberos realm, language (e.g., en-us).
10777: Values are retrieved from cache (if current), or from domain's configuration.db
10778: (if available), or lastly from values in lonTabs/dns_domain,tab, 
10779: or lonTabs/domain.tab. 
10780: 
10781: %domdefaults = &get_auth_defaults($target_domain);
10782: 
10783: =back
10784: 
10785: =head2 Network Status Functions
10786: 
10787: =over 4
10788: 
10789: =item *
10790: 
10791: dirlist($uri) : return directory list based on URI
10792: 
10793: =item *
10794: 
10795: spareserver() : find server with least workload from spare.tab
10796: 
10797: 
10798: =item *
10799: 
10800: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
10801: if there is no corresponding loncapa host.
10802: 
10803: =back
10804: 
10805: 
10806: =head2 Apache Request
10807: 
10808: =over 4
10809: 
10810: =item *
10811: 
10812: ssi($url,%hash) : server side include, does a complete request cycle on url to
10813: localhost, posts hash
10814: 
10815: =back
10816: 
10817: =head2 Data to String to Data
10818: 
10819: =over 4
10820: 
10821: =item *
10822: 
10823: hash2str(%hash) : convert a hash into a string complete with escaping and '='
10824: and '&' separators, supports elements that are arrayrefs and hashrefs
10825: 
10826: =item *
10827: 
10828: hashref2str($hashref) : convert a hashref into a string complete with
10829: escaping and '=' and '&' separators, supports elements that are
10830: arrayrefs and hashrefs
10831: 
10832: =item *
10833: 
10834: arrayref2str($arrayref) : convert an arrayref into a string complete
10835: with escaping and '&' separators, supports elements that are arrayrefs
10836: and hashrefs
10837: 
10838: =item *
10839: 
10840: str2hash($string) : convert string to hash using unescaping and
10841: splitting on '=' and '&', supports elements that are arrayrefs and
10842: hashrefs
10843: 
10844: =item *
10845: 
10846: str2array($string) : convert string to hash using unescaping and
10847: splitting on '&', supports elements that are arrayrefs and hashrefs
10848: 
10849: =back
10850: 
10851: =head2 Logging Routines
10852: 
10853: =over 4
10854: 
10855: These routines allow one to make log messages in the lonnet.log and
10856: lonnet.perm logfiles.
10857: 
10858: =item *
10859: 
10860: logtouch() : make sure the logfile, lonnet.log, exists
10861: 
10862: =item *
10863: 
10864: logthis() : append message to the normal lonnet.log file, it gets
10865: preiodically rolled over and deleted.
10866: 
10867: =item *
10868: 
10869: logperm() : append a permanent message to lonnet.perm.log, this log
10870: file never gets deleted by any automated portion of the system, only
10871: messages of critical importance should go in here.
10872: 
10873: =back
10874: 
10875: =head2 General File Helper Routines
10876: 
10877: =over 4
10878: 
10879: =item *
10880: 
10881: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10882: (a) files in /uploaded
10883:   (i) If a local copy of the file exists - 
10884:       compares modification date of local copy with last-modified date for 
10885:       definitive version stored on home server for course. If local copy is 
10886:       stale, requests a new version from the home server and stores it. 
10887:       If the original has been removed from the home server, then local copy 
10888:       is unlinked.
10889:   (ii) If local copy does not exist -
10890:       requests the file from the home server and stores it. 
10891:   
10892:   If $caller is 'uploadrep':  
10893:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10894:     for request for files originally uploaded via DOCS. 
10895:      - returns 'ok' if fresh local copy now available, -1 otherwise.
10896:   
10897:   Otherwise:
10898:      This indicates a call from the content generation phase of the request.
10899:      -  returns the entire contents of the file or -1.
10900:      
10901: (b) files in /res
10902:    - returns the entire contents of a file or -1; 
10903:    it properly subscribes to and replicates the file if neccessary.
10904: 
10905: 
10906: =item *
10907: 
10908: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10909:                   reference
10910: 
10911: returns either a stat() list of data about the file or an empty list
10912: if the file doesn't exist or couldn't find out about it (connection
10913: problems or user unknown)
10914: 
10915: =item *
10916: 
10917: filelocation($dir,$file) : returns file system location of a file
10918: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10919: directory that relative $file lookups are to looked in ($dir of /a/dir
10920: and a file of ../bob will become /a/bob)
10921: 
10922: =item *
10923: 
10924: hreflocation($dir,$file) : returns file system location or a URL; same as
10925: filelocation except for hrefs
10926: 
10927: =item *
10928: 
10929: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10930: 
10931: =back
10932: 
10933: =head2 Usererfile file routines (/uploaded*)
10934: 
10935: =over 4
10936: 
10937: =item *
10938: 
10939: userfileupload(): main rotine for putting a file in a user or course's
10940:                   filespace, arguments are,
10941: 
10942:  formname - required - this is the name of the element in $env where the
10943:            filename, and the contents of the file to create/modifed exist
10944:            the filename is in $env{'form.'.$formname.'.filename'} and the
10945:            contents of the file is located in $env{'form.'.$formname}
10946:  coursedoc - if true, store the file in the course of the active role
10947:              of the current user
10948:  subdir - required - subdirectory to put the file in under ../userfiles/
10949:          if undefined, it will be placed in "unknown"
10950: 
10951:  (This routine calls clean_filename() to remove any dangerous
10952:  characters from the filename, and then calls finuserfileupload() to
10953:  complete the transaction)
10954: 
10955:  returns either the url of the uploaded file (/uploaded/....) if successful
10956:  and /adm/notfound.html if unsuccessful
10957: 
10958: =item *
10959: 
10960: clean_filename(): routine for cleaing a filename up for storage in
10961:                  userfile space, argument is:
10962: 
10963:  filename - proposed filename
10964: 
10965: returns: the new clean filename
10966: 
10967: =item *
10968: 
10969: finishuserfileupload(): routine that creaes and sends the file to
10970: userspace, probably shouldn't be called directly
10971: 
10972:   docuname: username or courseid of destination for the file
10973:   docudom: domain of user/course of destination for the file
10974:   formname: same as for userfileupload()
10975:   fname: filename (inculding subdirectories) for the file
10976: 
10977:  returns either the url of the uploaded file (/uploaded/....) if successful
10978:  and /adm/notfound.html if unsuccessful
10979: 
10980: =item *
10981: 
10982: renameuserfile(): renames an existing userfile to a new name
10983: 
10984:   Args:
10985:    docuname: username or courseid of destination for the file
10986:    docudom: domain of user/course of destination for the file
10987:    old: current file name (including any subdirs under userfiles)
10988:    new: desired file name (including any subdirs under userfiles)
10989: 
10990: =item *
10991: 
10992: mkdiruserfile(): creates a directory is a userfiles dir
10993: 
10994:   Args:
10995:    docuname: username or courseid of destination for the file
10996:    docudom: domain of user/course of destination for the file
10997:    dir: dir to create (including any subdirs under userfiles)
10998: 
10999: =item *
11000: 
11001: removeuserfile(): removes a file that exists in userfiles
11002: 
11003:   Args:
11004:    docuname: username or courseid of destination for the file
11005:    docudom: domain of user/course of destination for the file
11006:    fname: filname to delete (including any subdirs under userfiles)
11007: 
11008: =item *
11009: 
11010: removeuploadedurl(): convience function for removeuserfile()
11011: 
11012:   Args:
11013:    url:  a full /uploaded/... url to delete
11014: 
11015: =item * 
11016: 
11017: get_portfile_permissions():
11018:   Args:
11019:     domain: domain of user or course contain the portfolio files
11020:     user: name of user or num of course contain the portfolio files
11021:   Returns:
11022:     hashref of a dump of the proper file_permissions.db
11023:    
11024: 
11025: =item * 
11026: 
11027: get_access_controls():
11028: 
11029: Args:
11030:   current_permissions: the hash ref returned from get_portfile_permissions()
11031:   group: (optional) the group you want the files associated with
11032:   file: (optional) the file you want access info on
11033: 
11034: Returns:
11035:     a hash (keys are file names) of hashes containing
11036:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
11037:         values are XML containing access control settings (see below) 
11038: 
11039: Internal notes:
11040: 
11041:  access controls are stored in file_permissions.db as key=value pairs.
11042:     key -> path to file/file_name\0uniqueID:scope_end_start
11043:         where scope -> public,guest,course,group,domains or users.
11044:               end -> UNIX time for end of access (0 -> no end date)
11045:               start -> UNIX time for start of access
11046: 
11047:     value -> XML description of access control
11048:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
11049:             <start></start>
11050:             <end></end>
11051: 
11052:             <password></password>  for scope type = guest
11053: 
11054:             <domain></domain>     for scope type = course or group
11055:             <number></number>
11056:             <roles id="">
11057:              <role></role>
11058:              <access></access>
11059:              <section></section>
11060:              <group></group>
11061:             </roles>
11062: 
11063:             <dom></dom>         for scope type = domains
11064: 
11065:             <users>             for scope type = users
11066:              <user>
11067:               <uname></uname>
11068:               <udom></udom>
11069:              </user>
11070:             </users>
11071:            </scope> 
11072:               
11073:  Access data is also aggregated for each file in an additional key=value pair:
11074:  key -> path to file/file_name\0accesscontrol 
11075:  value -> reference to hash
11076:           hash contains key = value pairs
11077:           where key = uniqueID:scope_end_start
11078:                 value = UNIX time record was last updated
11079: 
11080:           Used to improve speed of look-ups of access controls for each file.  
11081:  
11082:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11083: 
11084: modify_access_controls():
11085: 
11086: Modifies access controls for a portfolio file
11087: Args
11088: 1. file name
11089: 2. reference to hash of required changes,
11090: 3. domain
11091: 4. username
11092:   where domain,username are the domain of the portfolio owner 
11093:   (either a user or a course) 
11094: 
11095: Returns:
11096: 1. result of additions or updates ('ok' or 'error', with error message). 
11097: 2. result of deletions ('ok' or 'error', with error message).
11098: 3. reference to hash of any new or updated access controls.
11099: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11100:    key = integer (inbound ID)
11101:    value = uniqueID  
11102: 
11103: =back
11104: 
11105: =head2 HTTP Helper Routines
11106: 
11107: =over 4
11108: 
11109: =item *
11110: 
11111: escape() : unpack non-word characters into CGI-compatible hex codes
11112: 
11113: =item *
11114: 
11115: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11116: 
11117: =back
11118: 
11119: =head1 PRIVATE SUBROUTINES
11120: 
11121: =head2 Underlying communication routines (Shouldn't call)
11122: 
11123: =over 4
11124: 
11125: =item *
11126: 
11127: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11128: 
11129: =item *
11130: 
11131: reply() : uses subreply to send a message to remote machine, logs all failures
11132: 
11133: =item *
11134: 
11135: critical() : passes a critical message to another server; if cannot
11136: get through then place message in connection buffer directory and
11137: returns con_delayed, if incapable of saving message, returns
11138: con_failed
11139: 
11140: =item *
11141: 
11142: reconlonc() : tries to reconnect lonc client processes.
11143: 
11144: =back
11145: 
11146: =head2 Resource Access Logging
11147: 
11148: =over 4
11149: 
11150: =item *
11151: 
11152: flushcourselogs() : flush (save) buffer logs and access logs
11153: 
11154: =item *
11155: 
11156: courselog($what) : save message for course in hash
11157: 
11158: =item *
11159: 
11160: courseacclog($what) : save message for course using &courselog().  Perform
11161: special processing for specific resource types (problems, exams, quizzes, etc).
11162: 
11163: =item *
11164: 
11165: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11166: as a PerlChildExitHandler
11167: 
11168: =back
11169: 
11170: =head2 Other
11171: 
11172: =over 4
11173: 
11174: =item *
11175: 
11176: symblist($mapname,%newhash) : update symbolic storage links
11177: 
11178: =back
11179: 
11180: =cut
11181: 

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