File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.976.2.9: download - view: text, annotated - select for diffs
Fri May 15 20:31:04 2009 UTC (15 years, 2 months ago) by raeburn
Branches: version_2_8_X
CVS tags: version_2_8_1
Diff to branchpoint 1.976: preferred, unified
- Omitted from backport of 1.999.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.976.2.9 2009/05/15 20:31:04 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 Date::Parse;
   77: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   78:             $_64bit %env %protocol);
   79: 
   80: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   81:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   82:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   83:     %courseownerbuf, %coursetypebuf,$locknum);
   84: 
   85: use IO::Socket;
   86: use GDBM_File;
   87: use HTML::LCParser;
   88: use Fcntl qw(:flock);
   89: use Storable qw(thaw nfreeze);
   90: use Time::HiRes qw( gettimeofday tv_interval );
   91: use Cache::Memcached;
   92: use Digest::MD5;
   93: use Math::Random;
   94: use LONCAPA qw(:DEFAULT :match);
   95: use LONCAPA::Configuration;
   96: 
   97: my $readit;
   98: my $max_connection_retries = 10;     # Or some such value.
   99: 
  100: require Exporter;
  101: 
  102: our @ISA = qw (Exporter);
  103: our @EXPORT = qw(%env);
  104: 
  105: 
  106: # --------------------------------------------------------------------- Logging
  107: {
  108:     my $logid;
  109:     sub instructor_log {
  110: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  111:         if (($cnum eq '') || ($cdom eq '')) {
  112:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  113:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  114:         }
  115: 	$logid++;
  116:         my $now = time();
  117: 	my $id=$now.'00000'.$$.'00000'.$logid;
  118: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  119: 				    { $id => {
  120: 					'exe_uname' => $env{'user.name'},
  121: 					'exe_udom'  => $env{'user.domain'},
  122: 					'exe_time'  => $now,
  123: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  124: 					'delflag'   => $delflag,
  125: 					'logentry'  => $storehash,
  126: 					'uname'     => $uname,
  127: 					'udom'      => $udom,
  128: 				    }
  129: 				  },$cdom,$cnum);
  130:     }
  131: }
  132: 
  133: sub logtouch {
  134:     my $execdir=$perlvar{'lonDaemons'};
  135:     unless (-e "$execdir/logs/lonnet.log") {	
  136: 	open(my $fh,">>$execdir/logs/lonnet.log");
  137: 	close $fh;
  138:     }
  139:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  140:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  141: }
  142: 
  143: sub logthis {
  144:     my $message=shift;
  145:     my $execdir=$perlvar{'lonDaemons'};
  146:     my $now=time;
  147:     my $local=localtime($now);
  148:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  149: 	print $fh "$local ($$): $message\n";
  150: 	close($fh);
  151:     }
  152:     return 1;
  153: }
  154: 
  155: sub logperm {
  156:     my $message=shift;
  157:     my $execdir=$perlvar{'lonDaemons'};
  158:     my $now=time;
  159:     my $local=localtime($now);
  160:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  161: 	print $fh "$now:$message:$local\n";
  162: 	close($fh);
  163:     }
  164:     return 1;
  165: }
  166: 
  167: sub create_connection {
  168:     my ($hostname,$lonid) = @_;
  169:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  170: 				     Type    => SOCK_STREAM,
  171: 				     Timeout => 10);
  172:     return 0 if (!$client);
  173:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  174:     my $result = <$client>;
  175:     chomp($result);
  176:     return 1 if ($result eq 'done');
  177:     return 0;
  178: }
  179: 
  180: sub get_server_timezone {
  181:     my ($cnum,$cdom) = @_;
  182:     my $home=&homeserver($cnum,$cdom);
  183:     if ($home ne 'no_host') {
  184:         my $cachetime = 24*3600;
  185:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  186:         if (defined($cached)) {
  187:             return $timezone;
  188:         } else {
  189:             my $timezone = &reply('servertimezone',$home);
  190:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  191:         }
  192:     }
  193: }
  194: 
  195: # -------------------------------------------------- Non-critical communication
  196: sub subreply {
  197:     my ($cmd,$server)=@_;
  198:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  199:     #
  200:     #  With loncnew process trimming, there's a timing hole between lonc server
  201:     #  process exit and the master server picking up the listen on the AF_UNIX
  202:     #  socket.  In that time interval, a lock file will exist:
  203: 
  204:     my $lockfile=$peerfile.".lock";
  205:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  206: 	sleep(1);
  207:     }
  208:     # At this point, either a loncnew parent is listening or an old lonc
  209:     # or loncnew child is listening so we can connect or everything's dead.
  210:     #
  211:     #   We'll give the connection a few tries before abandoning it.  If
  212:     #   connection is not possible, we'll con_lost back to the client.
  213:     #   
  214:     my $client;
  215:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  216: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  217: 				      Type    => SOCK_STREAM,
  218: 				      Timeout => 10);
  219: 	if ($client) {
  220: 	    last;		# Connected!
  221: 	} else {
  222: 	    &create_connection(&hostname($server),$server);
  223: 	}
  224:         sleep(1);		# Try again later if failed connection.
  225:     }
  226:     my $answer;
  227:     if ($client) {
  228: 	print $client "sethost:$server:$cmd\n";
  229: 	$answer=<$client>;
  230: 	if (!$answer) { $answer="con_lost"; }
  231: 	chomp($answer);
  232:     } else {
  233: 	$answer = 'con_lost';	# Failed connection.
  234:     }
  235:     return $answer;
  236: }
  237: 
  238: sub reply {
  239:     my ($cmd,$server)=@_;
  240:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  241:     my $answer=subreply($cmd,$server);
  242:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  243:        &logthis("<font color=\"blue\">WARNING:".
  244:                 " $cmd to $server returned $answer</font>");
  245:     }
  246:     return $answer;
  247: }
  248: 
  249: # ----------------------------------------------------------- Send USR1 to lonc
  250: 
  251: sub reconlonc {
  252:     my ($lonid) = @_;
  253:     my $hostname = &hostname($lonid);
  254:     if ($lonid) {
  255: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  256: 	if ($hostname && -e $peerfile) {
  257: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  258: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  259: 					     Type    => SOCK_STREAM,
  260: 					     Timeout => 10);
  261: 	    if ($client) {
  262: 		print $client ("reset_retries\n");
  263: 		my $answer=<$client>;
  264: 		#reset just this one.
  265: 	    }
  266: 	}
  267: 	return;
  268:     }
  269: 
  270:     &logthis("Trying to reconnect lonc");
  271:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  272:     if (open(my $fh,"<$loncfile")) {
  273: 	my $loncpid=<$fh>;
  274:         chomp($loncpid);
  275:         if (kill 0 => $loncpid) {
  276: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  277:             kill USR1 => $loncpid;
  278:             sleep 1;
  279:          } else {
  280: 	    &logthis(
  281:                "<font color=\"blue\">WARNING:".
  282:                " lonc at pid $loncpid not responding, giving up</font>");
  283:         }
  284:     } else {
  285: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  286:     }
  287: }
  288: 
  289: # ------------------------------------------------------ Critical communication
  290: 
  291: sub critical {
  292:     my ($cmd,$server)=@_;
  293:     unless (&hostname($server)) {
  294:         &logthis("<font color=\"blue\">WARNING:".
  295:                " Critical message to unknown server ($server)</font>");
  296:         return 'no_such_host';
  297:     }
  298:     my $answer=reply($cmd,$server);
  299:     if ($answer eq 'con_lost') {
  300: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  301: 	my $answer=reply($cmd,$server);
  302:         if ($answer eq 'con_lost') {
  303:             my $now=time;
  304:             my $middlename=$cmd;
  305:             $middlename=substr($middlename,0,16);
  306:             $middlename=~s/\W//g;
  307:             my $dfilename=
  308:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  309:             $dumpcount++;
  310:             {
  311: 		my $dfh;
  312: 		if (open($dfh,">$dfilename")) {
  313: 		    print $dfh "$cmd\n"; 
  314: 		    close($dfh);
  315: 		}
  316:             }
  317:             sleep 2;
  318:             my $wcmd='';
  319:             {
  320: 		my $dfh;
  321: 		if (open($dfh,"<$dfilename")) {
  322: 		    $wcmd=<$dfh>; 
  323: 		    close($dfh);
  324: 		}
  325:             }
  326:             chomp($wcmd);
  327:             if ($wcmd eq $cmd) {
  328: 		&logthis("<font color=\"blue\">WARNING: ".
  329:                          "Connection buffer $dfilename: $cmd</font>");
  330:                 &logperm("D:$server:$cmd");
  331: 	        return 'con_delayed';
  332:             } else {
  333:                 &logthis("<font color=\"red\">CRITICAL:"
  334:                         ." Critical connection failed: $server $cmd</font>");
  335:                 &logperm("F:$server:$cmd");
  336:                 return 'con_failed';
  337:             }
  338:         }
  339:     }
  340:     return $answer;
  341: }
  342: 
  343: # ------------------------------------------- check if return value is an error
  344: 
  345: sub error {
  346:     my ($result) = @_;
  347:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  348: 	if ($2 == 2) { return undef; }
  349: 	return $1;
  350:     }
  351:     return undef;
  352: }
  353: 
  354: sub convert_and_load_session_env {
  355:     my ($lonidsdir,$handle)=@_;
  356:     my @profile;
  357:     {
  358: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  359: 	if (!$opened) {
  360: 	    return 0;
  361: 	}
  362: 	flock($idf,LOCK_SH);
  363: 	@profile=<$idf>;
  364: 	close($idf);
  365:     }
  366:     my %temp_env;
  367:     foreach my $line (@profile) {
  368: 	if ($line !~ m/=/) {
  369: 	    return 0;
  370: 	}
  371: 	chomp($line);
  372: 	my ($envname,$envvalue)=split(/=/,$line,2);
  373: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  374:     }
  375:     unlink("$lonidsdir/$handle.id");
  376:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  377: 	    0640)) {
  378: 	%disk_env = %temp_env;
  379: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  380: 	untie(%disk_env);
  381:     }
  382:     return 1;
  383: }
  384: 
  385: # ------------------------------------------- Transfer profile into environment
  386: my $env_loaded;
  387: sub transfer_profile_to_env {
  388:     my ($lonidsdir,$handle,$force_transfer) = @_;
  389:     if (!$force_transfer && $env_loaded) { return; } 
  390: 
  391:     if (!defined($lonidsdir)) {
  392: 	$lonidsdir = $perlvar{'lonIDsDir'};
  393:     }
  394:     if (!defined($handle)) {
  395:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  396:     }
  397: 
  398:     my $convert;
  399:     {
  400:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  401: 	if (!$opened) {
  402: 	    return;
  403: 	}
  404: 	flock($idf,LOCK_SH);
  405: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  406: 		&GDBM_READER(),0640)) {
  407: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  408: 	    untie(%disk_env);
  409: 	} else {
  410: 	    $convert = 1;
  411: 	}
  412:     }
  413:     if ($convert) {
  414: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  415: 	    &logthis("Failed to load session, or convert session.");
  416: 	}
  417:     }
  418: 
  419:     my %remove;
  420:     while ( my $envname = each(%env) ) {
  421:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  422:             if ($time < time-300) {
  423:                 $remove{$key}++;
  424:             }
  425:         }
  426:     }
  427: 
  428:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  429:     $env_loaded=1;
  430:     foreach my $expired_key (keys(%remove)) {
  431:         &delenv($expired_key);
  432:     }
  433: }
  434: 
  435: # ---------------------------------------------------- Check for valid session 
  436: sub check_for_valid_session {
  437:     my ($r) = @_;
  438:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  439:     my $lonid=$cookies{'lonID'};
  440:     return undef if (!$lonid);
  441: 
  442:     my $handle=&LONCAPA::clean_handle($lonid->value);
  443:     my $lonidsdir=$r->dir_config('lonIDsDir');
  444:     return undef if (!-e "$lonidsdir/$handle.id");
  445: 
  446:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  447:     return undef if (!$opened);
  448: 
  449:     flock($idf,LOCK_SH);
  450:     my %disk_env;
  451:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  452: 	    &GDBM_READER(),0640)) {
  453: 	return undef;	
  454:     }
  455: 
  456:     if (!defined($disk_env{'user.name'})
  457: 	|| !defined($disk_env{'user.domain'})) {
  458: 	return undef;
  459:     }
  460:     return $handle;
  461: }
  462: 
  463: sub timed_flock {
  464:     my ($file,$lock_type) = @_;
  465:     my $failed=0;
  466:     eval {
  467: 	local $SIG{__DIE__}='DEFAULT';
  468: 	local $SIG{ALRM}=sub {
  469: 	    $failed=1;
  470: 	    die("failed lock");
  471: 	};
  472: 	alarm(13);
  473: 	flock($file,$lock_type);
  474: 	alarm(0);
  475:     };
  476:     if ($failed) {
  477: 	return undef;
  478:     } else {
  479: 	return 1;
  480:     }
  481: }
  482: 
  483: # ---------------------------------------------------------- Append Environment
  484: 
  485: sub appenv {
  486:     my ($newenv,$roles) = @_;
  487:     if (ref($newenv) eq 'HASH') {
  488:         foreach my $key (keys(%{$newenv})) {
  489:             my $refused = 0;
  490: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  491:                 $refused = 1;
  492:                 if (ref($roles) eq 'ARRAY') {
  493:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  494:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  495:                         $refused = 0;
  496:                     }
  497:                 }
  498:             }
  499:             if ($refused) {
  500:                 &logthis("<font color=\"blue\">WARNING: ".
  501:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  502:                          .'</font>');
  503: 	        delete($newenv->{$key});
  504:             } else {
  505:                 $env{$key}=$newenv->{$key};
  506:             }
  507:         }
  508:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  509:         if ($opened
  510: 	    && &timed_flock($env_file,LOCK_EX)
  511: 	    &&
  512: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  513: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  514: 	    while (my ($key,$value) = each(%{$newenv})) {
  515: 	        $disk_env{$key} = $value;
  516: 	    }
  517: 	    untie(%disk_env);
  518:         }
  519:     }
  520:     return 'ok';
  521: }
  522: # ----------------------------------------------------- Delete from Environment
  523: 
  524: sub delenv {
  525:     my ($delthis,$regexp) = @_;
  526:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  527:         &logthis("<font color=\"blue\">WARNING: ".
  528:                 "Attempt to delete from environment ".$delthis);
  529:         return 'error';
  530:     }
  531:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  532:     if ($opened
  533: 	&& &timed_flock($env_file,LOCK_EX)
  534: 	&&
  535: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  536: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  537: 	foreach my $key (keys(%disk_env)) {
  538:             if ($regexp) {
  539:                 if ($key=~/^$delthis/) {
  540:                     delete($env{$key});
  541:                     delete($disk_env{$key});
  542:                 }
  543:             } else {
  544:                 if ($key=~/^\Q$delthis\E/) {
  545:                     delete($env{$key});
  546:                     delete($disk_env{$key});
  547:                 }
  548:             }
  549: 	}
  550: 	untie(%disk_env);
  551:     }
  552:     return 'ok';
  553: }
  554: 
  555: sub get_env_multiple {
  556:     my ($name) = @_;
  557:     my @values;
  558:     if (defined($env{$name})) {
  559:         # exists is it an array
  560:         if (ref($env{$name})) {
  561:             @values=@{ $env{$name} };
  562:         } else {
  563:             $values[0]=$env{$name};
  564:         }
  565:     }
  566:     return(@values);
  567: }
  568: 
  569: # ------------------------------------------------------------------- Locking
  570: 
  571: sub set_lock {
  572:     my ($text)=@_;
  573:     $locknum++;
  574:     my $id=$$.'-'.$locknum;
  575:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  576:              'session.lock.'.$id => $text});
  577:     return $id;
  578: }
  579: 
  580: sub get_locks {
  581:     my $num=0;
  582:     my %texts=();
  583:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  584:        if ($lock=~/\w/) {
  585:           $num++;
  586:           $texts{$lock}=$env{'session.lock.'.$lock};
  587:        }
  588:    }
  589:    return ($num,%texts);
  590: }
  591: 
  592: sub remove_lock {
  593:     my ($id)=@_;
  594:     my $newlocks='';
  595:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  596:        if (($lock=~/\w/) && ($lock ne $id)) {
  597:           $newlocks.=','.$lock;
  598:        }
  599:     }
  600:     &appenv({'session.locks' => $newlocks});
  601:     &delenv('session.lock.'.$id);
  602: }
  603: 
  604: sub remove_all_locks {
  605:     my $activelocks=$env{'session.locks'};
  606:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  607:        if ($lock=~/\w/) {
  608:           &remove_lock($lock);
  609:        }
  610:     }
  611: }
  612: 
  613: 
  614: # ------------------------------------------ Find out current server userload
  615: sub userload {
  616:     my $numusers=0;
  617:     {
  618: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  619: 	my $filename;
  620: 	my $curtime=time;
  621: 	while ($filename=readdir(LONIDS)) {
  622: 	    next if ($filename eq '.' || $filename eq '..');
  623: 	    next if ($filename =~ /publicuser_\d+\.id/);
  624: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  625: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  626: 	}
  627: 	closedir(LONIDS);
  628:     }
  629:     my $userloadpercent=0;
  630:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  631:     if ($maxuserload) {
  632: 	$userloadpercent=100*$numusers/$maxuserload;
  633:     }
  634:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  635:     return $userloadpercent;
  636: }
  637: 
  638: # ------------------------------------------ Fight off request when overloaded
  639: 
  640: sub overloaderror {
  641:     my ($r,$checkserver)=@_;
  642:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  643:     my $loadavg;
  644:     if ($checkserver eq $perlvar{'lonHostID'}) {
  645:        open(my $loadfile,'/proc/loadavg');
  646:        $loadavg=<$loadfile>;
  647:        $loadavg =~ s/\s.*//g;
  648:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  649:        close($loadfile);
  650:     } else {
  651:        $loadavg=&reply('load',$checkserver);
  652:     }
  653:     my $overload=$loadavg-100;
  654:     if ($overload>0) {
  655: 	$r->err_headers_out->{'Retry-After'}=$overload;
  656:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  657:         return 413;
  658:     }    
  659:     return '';
  660: }
  661: 
  662: # ------------------------------ Find server with least workload from spare.tab
  663: 
  664: sub spareserver {
  665:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  666:     my $spare_server;
  667:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  668:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  669:                                                      :  $userloadpercent;
  670:     
  671:     foreach my $try_server (@{ $spareid{'primary'} }) {
  672: 	($spare_server, $lowest_load) =
  673: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  674:     }
  675: 
  676:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  677: 
  678:     if (!$found_server) {
  679: 	foreach my $try_server (@{ $spareid{'default'} }) {
  680: 	    ($spare_server, $lowest_load) =
  681: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  682: 	}
  683:     }
  684: 
  685:     if (!$want_server_name) {
  686:         my $protocol = 'http';
  687:         if ($protocol{$spare_server} eq 'https') {
  688:             $protocol = $protocol{$spare_server};
  689:         }
  690: 	$spare_server = $protocol.'://'.&hostname($spare_server);
  691:     }
  692:     return $spare_server;
  693: }
  694: 
  695: sub compare_server_load {
  696:     my ($try_server, $spare_server, $lowest_load) = @_;
  697: 
  698:     my $loadans     = &reply('load',    $try_server);
  699:     my $userloadans = &reply('userload',$try_server);
  700: 
  701:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  702: 	next; #didn't get a number from the server
  703:     }
  704: 
  705:     my $load;
  706:     if ($loadans =~ /\d/) {
  707: 	if ($userloadans =~ /\d/) {
  708: 	    #both are numbers, pick the bigger one
  709: 	    $load = ($loadans > $userloadans) ? $loadans 
  710: 		                              : $userloadans;
  711: 	} else {
  712: 	    $load = $loadans;
  713: 	}
  714:     } else {
  715: 	$load = $userloadans;
  716:     }
  717: 
  718:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  719: 	$spare_server = $try_server;
  720: 	$lowest_load  = $load;
  721:     }
  722:     return ($spare_server,$lowest_load);
  723: }
  724: 
  725: # --------------------------- ask offload servers if user already has a session
  726: sub find_existing_session {
  727:     my ($udom,$uname) = @_;
  728:     foreach my $try_server (@{ $spareid{'primary'} },
  729: 			    @{ $spareid{'default'} }) {
  730: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
  731:     }
  732:     return;
  733: }
  734: 
  735: # -------------------------------- ask if server already has a session for user
  736: sub has_user_session {
  737:     my ($lonid,$udom,$uname) = @_;
  738:     my $result = &reply(join(':','userhassession',
  739: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  740:     return 1 if ($result eq 'ok');
  741: 
  742:     return 0;
  743: }
  744: 
  745: # --------------------------------------------- Try to change a user's password
  746: 
  747: sub changepass {
  748:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  749:     $currentpass = &escape($currentpass);
  750:     $newpass     = &escape($newpass);
  751:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  752: 		       $server);
  753:     if (! $answer) {
  754: 	&logthis("No reply on password change request to $server ".
  755: 		 "by $uname in domain $udom.");
  756:     } elsif ($answer =~ "^ok") {
  757:         &logthis("$uname in $udom successfully changed their password ".
  758: 		 "on $server.");
  759:     } elsif ($answer =~ "^pwchange_failure") {
  760: 	&logthis("$uname in $udom was unable to change their password ".
  761: 		 "on $server.  The action was blocked by either lcpasswd ".
  762: 		 "or pwchange");
  763:     } elsif ($answer =~ "^non_authorized") {
  764:         &logthis("$uname in $udom did not get their password correct when ".
  765: 		 "attempting to change it on $server.");
  766:     } elsif ($answer =~ "^auth_mode_error") {
  767:         &logthis("$uname in $udom attempted to change their password despite ".
  768: 		 "not being locally or internally authenticated on $server.");
  769:     } elsif ($answer =~ "^unknown_user") {
  770:         &logthis("$uname in $udom attempted to change their password ".
  771: 		 "on $server but were unable to because $server is not ".
  772: 		 "their home server.");
  773:     } elsif ($answer =~ "^refused") {
  774: 	&logthis("$server refused to change $uname in $udom password because ".
  775: 		 "it was sent an unencrypted request to change the password.");
  776:     }
  777:     return $answer;
  778: }
  779: 
  780: # ----------------------- Try to determine user's current authentication scheme
  781: 
  782: sub queryauthenticate {
  783:     my ($uname,$udom)=@_;
  784:     my $uhome=&homeserver($uname,$udom);
  785:     if (!$uhome) {
  786: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  787: 	return 'no_host';
  788:     }
  789:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  790:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  791: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  792:     }
  793:     return $answer;
  794: }
  795: 
  796: # --------- Try to authenticate user from domain's lib servers (first this one)
  797: 
  798: sub authenticate {
  799:     my ($uname,$upass,$udom,$checkdefauth)=@_;
  800:     $upass=&escape($upass);
  801:     $uname= &LONCAPA::clean_username($uname);
  802:     my $uhome=&homeserver($uname,$udom,1);
  803:     my $newhome;
  804:     if ((!$uhome) || ($uhome eq 'no_host')) {
  805: # Maybe the machine was offline and only re-appeared again recently?
  806:         &reconlonc();
  807: # One more
  808: 	$uhome=&homeserver($uname,$udom,1);
  809:         if (($uhome eq 'no_host') && $checkdefauth) {
  810:             if (defined(&domain($udom,'primary'))) {
  811:                 $newhome=&domain($udom,'primary');
  812:             }
  813:             if ($newhome ne '') {
  814:                 $uhome = $newhome;
  815:             }
  816:         }
  817: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  818: 	    &logthis("User $uname at $udom is unknown in authenticate");
  819: 	    return 'no_host';
  820:         }
  821:     }
  822:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
  823:     if ($answer eq 'authorized') {
  824:         if ($newhome) {
  825:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
  826:             return 'no_account_on_host'; 
  827:         } else {
  828:             &logthis("User $uname at $udom authorized by $uhome");
  829:             return $uhome;
  830:         }
  831:     }
  832:     if ($answer eq 'non_authorized') {
  833: 	&logthis("User $uname at $udom rejected by $uhome");
  834: 	return 'no_host'; 
  835:     }
  836:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  837:     return 'no_host';
  838: }
  839: 
  840: # ---------------------- Find the homebase for a user from domain's lib servers
  841: 
  842: my %homecache;
  843: sub homeserver {
  844:     my ($uname,$udom,$ignoreBadCache)=@_;
  845:     my $index="$uname:$udom";
  846: 
  847:     if (exists($homecache{$index})) { return $homecache{$index}; }
  848: 
  849:     my %servers = &get_servers($udom,'library');
  850:     foreach my $tryserver (keys(%servers)) {
  851:         next if ($ignoreBadCache ne 'true' && 
  852: 		 exists($badServerCache{$tryserver}));
  853: 
  854: 	my $answer=reply("home:$udom:$uname",$tryserver);
  855: 	if ($answer eq 'found') {
  856: 	    delete($badServerCache{$tryserver}); 
  857: 	    return $homecache{$index}=$tryserver;
  858: 	} elsif ($answer eq 'no_host') {
  859: 	    $badServerCache{$tryserver}=1;
  860: 	}
  861:     }    
  862:     return 'no_host';
  863: }
  864: 
  865: # ------------------------------------- Find the usernames behind a list of IDs
  866: 
  867: sub idget {
  868:     my ($udom,@ids)=@_;
  869:     my %returnhash=();
  870:     
  871:     my %servers = &get_servers($udom,'library');
  872:     foreach my $tryserver (keys(%servers)) {
  873: 	my $idlist=join('&',@ids);
  874: 	$idlist=~tr/A-Z/a-z/; 
  875: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  876: 	my @answer=();
  877: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  878: 	    @answer=split(/\&/,$reply);
  879: 	}                    ;
  880: 	my $i;
  881: 	for ($i=0;$i<=$#ids;$i++) {
  882: 	    if ($answer[$i]) {
  883: 		$returnhash{$ids[$i]}=$answer[$i];
  884: 	    } 
  885: 	}
  886:     } 
  887:     return %returnhash;
  888: }
  889: 
  890: # ------------------------------------- Find the IDs behind a list of usernames
  891: 
  892: sub idrget {
  893:     my ($udom,@unames)=@_;
  894:     my %returnhash=();
  895:     foreach my $uname (@unames) {
  896:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  897:     }
  898:     return %returnhash;
  899: }
  900: 
  901: # ------------------------------- Store away a list of names and associated IDs
  902: 
  903: sub idput {
  904:     my ($udom,%ids)=@_;
  905:     my %servers=();
  906:     foreach my $uname (keys(%ids)) {
  907: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  908:         my $uhom=&homeserver($uname,$udom);
  909:         if ($uhom ne 'no_host') {
  910:             my $id=&escape($ids{$uname});
  911:             $id=~tr/A-Z/a-z/;
  912:             my $esc_unam=&escape($uname);
  913: 	    if ($servers{$uhom}) {
  914: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  915:             } else {
  916:                 $servers{$uhom}=$id.'='.$esc_unam;
  917:             }
  918:         }
  919:     }
  920:     foreach my $server (keys(%servers)) {
  921:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  922:     }
  923: }
  924: 
  925: # ------------------------------------------- get items from domain db files   
  926: 
  927: sub get_dom {
  928:     my ($namespace,$storearr,$udom,$uhome)=@_;
  929:     my $items='';
  930:     foreach my $item (@$storearr) {
  931:         $items.=&escape($item).'&';
  932:     }
  933:     $items=~s/\&$//;
  934:     if (!$udom) {
  935:         $udom=$env{'user.domain'};
  936:         if (defined(&domain($udom,'primary'))) {
  937:             $uhome=&domain($udom,'primary');
  938:         } else {
  939:             undef($uhome);
  940:         }
  941:     } else {
  942:         if (!$uhome) {
  943:             if (defined(&domain($udom,'primary'))) {
  944:                 $uhome=&domain($udom,'primary');
  945:             }
  946:         }
  947:     }
  948:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  949:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  950:         my %returnhash;
  951:         if ($rep eq '' || $rep =~ /^error: 2 /) {
  952:             return %returnhash;
  953:         }
  954:         my @pairs=split(/\&/,$rep);
  955:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  956:             return @pairs;
  957:         }
  958:         my $i=0;
  959:         foreach my $item (@$storearr) {
  960:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  961:             $i++;
  962:         }
  963:         return %returnhash;
  964:     } else {
  965:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
  966:     }
  967: }
  968: 
  969: # -------------------------------------------- put items in domain db files 
  970: 
  971: sub put_dom {
  972:     my ($namespace,$storehash,$udom,$uhome)=@_;
  973:     if (!$udom) {
  974:         $udom=$env{'user.domain'};
  975:         if (defined(&domain($udom,'primary'))) {
  976:             $uhome=&domain($udom,'primary');
  977:         } else {
  978:             undef($uhome);
  979:         }
  980:     } else {
  981:         if (!$uhome) {
  982:             if (defined(&domain($udom,'primary'))) {
  983:                 $uhome=&domain($udom,'primary');
  984:             }
  985:         }
  986:     } 
  987:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  988:         my $items='';
  989:         foreach my $item (keys(%$storehash)) {
  990:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  991:         }
  992:         $items=~s/\&$//;
  993:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  994:     } else {
  995:         &logthis("put_dom failed - no homeserver and/or domain");
  996:     }
  997: }
  998: 
  999: sub retrieve_inst_usertypes {
 1000:     my ($udom) = @_;
 1001:     my (%returnhash,@order);
 1002:     if (defined(&domain($udom,'primary'))) {
 1003:         my $uhome=&domain($udom,'primary');
 1004:         my $rep=&reply("inst_usertypes:$udom",$uhome);
 1005:         if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1006:             &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1007:             return (\%returnhash,\@order);
 1008:         }
 1009:         my ($hashitems,$orderitems) = split(/:/,$rep); 
 1010:         my @pairs=split(/\&/,$hashitems);
 1011:         foreach my $item (@pairs) {
 1012:             my ($key,$value)=split(/=/,$item,2);
 1013:             $key = &unescape($key);
 1014:             next if ($key =~ /^error: 2 /);
 1015:             $returnhash{$key}=&thaw_unescape($value);
 1016:         }
 1017:         my @esc_order = split(/\&/,$orderitems);
 1018:         foreach my $item (@esc_order) {
 1019:             push(@order,&unescape($item));
 1020:         }
 1021:     } else {
 1022:         &logthis("get_dom failed - no primary domain server for $udom");
 1023:     }
 1024:     return (\%returnhash,\@order);
 1025: }
 1026: 
 1027: sub is_domainimage {
 1028:     my ($url) = @_;
 1029:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1030:         if (&domain($1) ne '') {
 1031:             return '1';
 1032:         }
 1033:     }
 1034:     return;
 1035: }
 1036: 
 1037: sub inst_directory_query {
 1038:     my ($srch) = @_;
 1039:     my $udom = $srch->{'srchdomain'};
 1040:     my %results;
 1041:     my $homeserver = &domain($udom,'primary');
 1042:     my $outcome;
 1043:     if ($homeserver ne '') {
 1044: 	my $queryid=&reply("querysend:instdirsearch:".
 1045: 			   &escape($srch->{'srchby'}).':'.
 1046: 			   &escape($srch->{'srchterm'}).':'.
 1047: 			   &escape($srch->{'srchtype'}),$homeserver);
 1048: 	my $host=&hostname($homeserver);
 1049: 	if ($queryid !~/^\Q$host\E\_/) {
 1050: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1051: 	    return;
 1052: 	}
 1053: 	my $response = &get_query_reply($queryid);
 1054: 	my $maxtries = 5;
 1055: 	my $tries = 1;
 1056: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1057: 	    $response = &get_query_reply($queryid);
 1058: 	    $tries ++;
 1059: 	}
 1060: 
 1061:         if (!&error($response) && $response ne 'refused') {
 1062:             if ($response eq 'unavailable') {
 1063:                 $outcome = $response;
 1064:             } else {
 1065:                 $outcome = 'ok';
 1066:                 my @matches = split(/\n/,$response);
 1067:                 foreach my $match (@matches) {
 1068:                     my ($key,$value) = split(/=/,$match);
 1069:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1070:                 }
 1071:             }
 1072:         }
 1073:     }
 1074:     return ($outcome,%results);
 1075: }
 1076: 
 1077: sub usersearch {
 1078:     my ($srch) = @_;
 1079:     my $dom = $srch->{'srchdomain'};
 1080:     my %results;
 1081:     my %libserv = &all_library();
 1082:     my $query = 'usersearch';
 1083:     foreach my $tryserver (keys(%libserv)) {
 1084:         if (&host_domain($tryserver) eq $dom) {
 1085:             my $host=&hostname($tryserver);
 1086:             my $queryid=
 1087:                 &reply("querysend:".&escape($query).':'.
 1088:                        &escape($srch->{'srchby'}).':'.
 1089:                        &escape($srch->{'srchtype'}).':'.
 1090:                        &escape($srch->{'srchterm'}),$tryserver);
 1091:             if ($queryid !~/^\Q$host\E\_/) {
 1092:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1093:                 next;
 1094:             }
 1095:             my $reply = &get_query_reply($queryid);
 1096:             my $maxtries = 1;
 1097:             my $tries = 1;
 1098:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1099:                 $reply = &get_query_reply($queryid);
 1100:                 $tries ++;
 1101:             }
 1102:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1103:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1104:             } else {
 1105:                 my @matches;
 1106:                 if ($reply =~ /\n/) {
 1107:                     @matches = split(/\n/,$reply);
 1108:                 } else {
 1109:                     @matches = split(/\&/,$reply);
 1110:                 }
 1111:                 foreach my $match (@matches) {
 1112:                     my ($uname,$udom,%userhash);
 1113:                     foreach my $entry (split(/:/,$match)) {
 1114:                         my ($key,$value) =
 1115:                             map {&unescape($_);} split(/=/,$entry);
 1116:                         $userhash{$key} = $value;
 1117:                         if ($key eq 'username') {
 1118:                             $uname = $value;
 1119:                         } elsif ($key eq 'domain') {
 1120:                             $udom = $value;
 1121:                         }
 1122:                     }
 1123:                     $results{$uname.':'.$udom} = \%userhash;
 1124:                 }
 1125:             }
 1126:         }
 1127:     }
 1128:     return %results;
 1129: }
 1130: 
 1131: sub get_instuser {
 1132:     my ($udom,$uname,$id) = @_;
 1133:     my $homeserver = &domain($udom,'primary');
 1134:     my ($outcome,%results);
 1135:     if ($homeserver ne '') {
 1136:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1137:                            &escape($id).':'.&escape($udom),$homeserver);
 1138:         my $host=&hostname($homeserver);
 1139:         if ($queryid !~/^\Q$host\E\_/) {
 1140:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1141:             return;
 1142:         }
 1143:         my $response = &get_query_reply($queryid);
 1144:         my $maxtries = 5;
 1145:         my $tries = 1;
 1146:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1147:             $response = &get_query_reply($queryid);
 1148:             $tries ++;
 1149:         }
 1150:         if (!&error($response) && $response ne 'refused') {
 1151:             if ($response eq 'unavailable') {
 1152:                 $outcome = $response;
 1153:             } else {
 1154:                 $outcome = 'ok';
 1155:                 my @matches = split(/\n/,$response);
 1156:                 foreach my $match (@matches) {
 1157:                     my ($key,$value) = split(/=/,$match);
 1158:                     $results{&unescape($key)} = &thaw_unescape($value);
 1159:                 }
 1160:             }
 1161:         }
 1162:     }
 1163:     my %userinfo;
 1164:     if (ref($results{$uname}) eq 'HASH') {
 1165:         %userinfo = %{$results{$uname}};
 1166:     } 
 1167:     return ($outcome,%userinfo);
 1168: }
 1169: 
 1170: sub inst_rulecheck {
 1171:     my ($udom,$uname,$id,$item,$rules) = @_;
 1172:     my %returnhash;
 1173:     if ($udom ne '') {
 1174:         if (ref($rules) eq 'ARRAY') {
 1175:             @{$rules} = map {&escape($_);} (@{$rules});
 1176:             my $rulestr = join(':',@{$rules});
 1177:             my $homeserver=&domain($udom,'primary');
 1178:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1179:                 my $response;
 1180:                 if ($item eq 'username') {                
 1181:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1182:                                               ':'.&escape($uname).':'.$rulestr,
 1183:                                               $homeserver));
 1184:                 } elsif ($item eq 'id') {
 1185:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1186:                                               ':'.&escape($id).':'.$rulestr,
 1187:                                               $homeserver));
 1188:                 } elsif ($item eq 'selfcreate') {
 1189:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1190:                                                &escape($udom).':'.&escape($uname).
 1191:                                               ':'.$rulestr,$homeserver));
 1192:                 }
 1193:                 if ($response ne 'refused') {
 1194:                     my @pairs=split(/\&/,$response);
 1195:                     foreach my $item (@pairs) {
 1196:                         my ($key,$value)=split(/=/,$item,2);
 1197:                         $key = &unescape($key);
 1198:                         next if ($key =~ /^error: 2 /);
 1199:                         $returnhash{$key}=&thaw_unescape($value);
 1200:                     }
 1201:                 }
 1202:             }
 1203:         }
 1204:     }
 1205:     return %returnhash;
 1206: }
 1207: 
 1208: sub inst_userrules {
 1209:     my ($udom,$check) = @_;
 1210:     my (%ruleshash,@ruleorder);
 1211:     if ($udom ne '') {
 1212:         my $homeserver=&domain($udom,'primary');
 1213:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1214:             my $response;
 1215:             if ($check eq 'id') {
 1216:                 $response=&reply('instidrules:'.&escape($udom),
 1217:                                  $homeserver);
 1218:             } elsif ($check eq 'email') {
 1219:                 $response=&reply('instemailrules:'.&escape($udom),
 1220:                                  $homeserver);
 1221:             } else {
 1222:                 $response=&reply('instuserrules:'.&escape($udom),
 1223:                                  $homeserver);
 1224:             }
 1225:             if (($response ne 'refused') && ($response ne 'error') && 
 1226:                 ($response ne 'unknown_cmd') && 
 1227:                 ($response ne 'no_such_host')) {
 1228:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1229:                 my @pairs=split(/\&/,$hashitems);
 1230:                 foreach my $item (@pairs) {
 1231:                     my ($key,$value)=split(/=/,$item,2);
 1232:                     $key = &unescape($key);
 1233:                     next if ($key =~ /^error: 2 /);
 1234:                     $ruleshash{$key}=&thaw_unescape($value);
 1235:                 }
 1236:                 my @esc_order = split(/\&/,$orderitems);
 1237:                 foreach my $item (@esc_order) {
 1238:                     push(@ruleorder,&unescape($item));
 1239:                 }
 1240:             }
 1241:         }
 1242:     }
 1243:     return (\%ruleshash,\@ruleorder);
 1244: }
 1245: 
 1246: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1247: 
 1248: sub get_domain_defaults {
 1249:     my ($domain) = @_;
 1250:     my $cachetime = 60*60*24;
 1251:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1252:     if (defined($cached)) {
 1253:         if (ref($result) eq 'HASH') {
 1254:             return %{$result};
 1255:         }
 1256:     }
 1257:     my %domdefaults;
 1258:     my %domconfig =
 1259:          &Apache::lonnet::get_dom('configuration',['defaults','quotas'],$domain);
 1260:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1261:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1262:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1263:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1264:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1265:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1266:     } else {
 1267:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1268:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1269:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1270:     }
 1271:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1272:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1273:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1274:         } else {
 1275:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1276:         } 
 1277:         my @usertools = ('aboutme','blog','portfolio');
 1278:         foreach my $item (@usertools) {
 1279:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1280:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1281:             }
 1282:         }
 1283:     }
 1284:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1285:                                   $cachetime);
 1286:     return %domdefaults;
 1287: }
 1288: 
 1289: # --------------------------------------------------- Assign a key to a student
 1290: 
 1291: sub assign_access_key {
 1292: #
 1293: # a valid key looks like uname:udom#comments
 1294: # comments are being appended
 1295: #
 1296:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1297:     $kdom=
 1298:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1299:     $knum=
 1300:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1301:     $cdom=
 1302:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1303:     $cnum=
 1304:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1305:     $udom=$env{'user.name'} unless (defined($udom));
 1306:     $uname=$env{'user.domain'} unless (defined($uname));
 1307:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1308:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1309:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1310:                                                   # assigned to this person
 1311:                                                   # - this should not happen,
 1312:                                                   # unless something went wrong
 1313:                                                   # the first time around
 1314: # ready to assign
 1315:         $logentry=$1.'; '.$logentry;
 1316:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1317:                                                  $kdom,$knum) eq 'ok') {
 1318: # key now belongs to user
 1319: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1320:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1321:                 &appenv({'environment.'.$envkey => $ckey});
 1322:                 return 'ok';
 1323:             } else {
 1324:                 return 
 1325:   'error: Count not permanently assign key, will need to be re-entered later.';
 1326: 	    }
 1327:         } else {
 1328:             return 'error: Could not assign key, try again later.';
 1329:         }
 1330:     } elsif (!$existing{$ckey}) {
 1331: # the key does not exist
 1332: 	return 'error: The key does not exist';
 1333:     } else {
 1334: # the key is somebody else's
 1335: 	return 'error: The key is already in use';
 1336:     }
 1337: }
 1338: 
 1339: # ------------------------------------------ put an additional comment on a key
 1340: 
 1341: sub comment_access_key {
 1342: #
 1343: # a valid key looks like uname:udom#comments
 1344: # comments are being appended
 1345: #
 1346:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1347:     $cdom=
 1348:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1349:     $cnum=
 1350:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1351:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1352:     if ($existing{$ckey}) {
 1353:         $existing{$ckey}.='; '.$logentry;
 1354: # ready to assign
 1355:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1356:                                                  $cdom,$cnum) eq 'ok') {
 1357: 	    return 'ok';
 1358:         } else {
 1359: 	    return 'error: Count not store comment.';
 1360:         }
 1361:     } else {
 1362: # the key does not exist
 1363: 	return 'error: The key does not exist';
 1364:     }
 1365: }
 1366: 
 1367: # ------------------------------------------------------ Generate a set of keys
 1368: 
 1369: sub generate_access_keys {
 1370:     my ($number,$cdom,$cnum,$logentry)=@_;
 1371:     $cdom=
 1372:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1373:     $cnum=
 1374:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1375:     unless (&allowed('mky',$cdom)) { return 0; }
 1376:     unless (($cdom) && ($cnum)) { return 0; }
 1377:     if ($number>10000) { return 0; }
 1378:     sleep(2); # make sure don't get same seed twice
 1379:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1380:     my $total=0;
 1381:     for (my $i=1;$i<=$number;$i++) {
 1382:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1383:                   sprintf("%lx",int(100000*rand)).'-'.
 1384:                   sprintf("%lx",int(100000*rand));
 1385:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1386:        $newkey=~s/0/h/g; # and also 0 and O
 1387:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1388:        if ($existing{$newkey}) {
 1389:            $i--;
 1390:        } else {
 1391: 	  if (&put('accesskeys',
 1392:               { $newkey => '# generated '.localtime().
 1393:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1394:                            '; '.$logentry },
 1395: 		   $cdom,$cnum) eq 'ok') {
 1396:               $total++;
 1397: 	  }
 1398:        }
 1399:     }
 1400:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1401:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1402:     return $total;
 1403: }
 1404: 
 1405: # ------------------------------------------------------- Validate an accesskey
 1406: 
 1407: sub validate_access_key {
 1408:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1409:     $cdom=
 1410:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1411:     $cnum=
 1412:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1413:     $udom=$env{'user.domain'} unless (defined($udom));
 1414:     $uname=$env{'user.name'} unless (defined($uname));
 1415:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1416:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1417: }
 1418: 
 1419: # ------------------------------------- Find the section of student in a course
 1420: sub devalidate_getsection_cache {
 1421:     my ($udom,$unam,$courseid)=@_;
 1422:     my $hashid="$udom:$unam:$courseid";
 1423:     &devalidate_cache_new('getsection',$hashid);
 1424: }
 1425: 
 1426: sub courseid_to_courseurl {
 1427:     my ($courseid) = @_;
 1428:     #already url style courseid
 1429:     return $courseid if ($courseid =~ m{^/});
 1430: 
 1431:     if (exists($env{'course.'.$courseid.'.num'})) {
 1432: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1433: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1434: 	return "/$cdom/$cnum";
 1435:     }
 1436: 
 1437:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1438:     if (exists($courseinfo{'num'})) {
 1439: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1440:     }
 1441: 
 1442:     return undef;
 1443: }
 1444: 
 1445: sub getsection {
 1446:     my ($udom,$unam,$courseid)=@_;
 1447:     my $cachetime=1800;
 1448: 
 1449:     my $hashid="$udom:$unam:$courseid";
 1450:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1451:     if (defined($cached)) { return $result; }
 1452: 
 1453:     my %Pending; 
 1454:     my %Expired;
 1455:     #
 1456:     # Each role can either have not started yet (pending), be active, 
 1457:     #    or have expired.
 1458:     #
 1459:     # If there is an active role, we are done.
 1460:     #
 1461:     # If there is more than one role which has not started yet, 
 1462:     #     choose the one which will start sooner
 1463:     # If there is one role which has not started yet, return it.
 1464:     #
 1465:     # If there is more than one expired role, choose the one which ended last.
 1466:     # If there is a role which has expired, return it.
 1467:     #
 1468:     $courseid = &courseid_to_courseurl($courseid);
 1469:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1470:     foreach my $key (keys(%roleshash)) {
 1471:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1472:         my $section=$1;
 1473:         if ($key eq $courseid.'_st') { $section=''; }
 1474:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1475:         my $now=time;
 1476:         if (defined($end) && $end && ($now > $end)) {
 1477:             $Expired{$end}=$section;
 1478:             next;
 1479:         }
 1480:         if (defined($start) && $start && ($now < $start)) {
 1481:             $Pending{$start}=$section;
 1482:             next;
 1483:         }
 1484:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1485:     }
 1486:     #
 1487:     # Presumedly there will be few matching roles from the above
 1488:     # loop and the sorting time will be negligible.
 1489:     if (scalar(keys(%Pending))) {
 1490:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1491:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1492:     } 
 1493:     if (scalar(keys(%Expired))) {
 1494:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1495:         my $time = pop(@sorted);
 1496:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1497:     }
 1498:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1499: }
 1500: 
 1501: sub save_cache {
 1502:     &purge_remembered();
 1503:     #&Apache::loncommon::validate_page();
 1504:     undef(%env);
 1505:     undef($env_loaded);
 1506: }
 1507: 
 1508: my $to_remember=-1;
 1509: my %remembered;
 1510: my %accessed;
 1511: my $kicks=0;
 1512: my $hits=0;
 1513: sub make_key {
 1514:     my ($name,$id) = @_;
 1515:     if (length($id) > 65 
 1516: 	&& length(&escape($id)) > 200) {
 1517: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1518:     }
 1519:     return &escape($name.':'.$id);
 1520: }
 1521: 
 1522: sub devalidate_cache_new {
 1523:     my ($name,$id,$debug) = @_;
 1524:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1525:     $id=&make_key($name,$id);
 1526:     $memcache->delete($id);
 1527:     delete($remembered{$id});
 1528:     delete($accessed{$id});
 1529: }
 1530: 
 1531: sub is_cached_new {
 1532:     my ($name,$id,$debug) = @_;
 1533:     $id=&make_key($name,$id);
 1534:     if (exists($remembered{$id})) {
 1535: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1536: 	$accessed{$id}=[&gettimeofday()];
 1537: 	$hits++;
 1538: 	return ($remembered{$id},1);
 1539:     }
 1540:     my $value = $memcache->get($id);
 1541:     if (!(defined($value))) {
 1542: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1543: 	return (undef,undef);
 1544:     }
 1545:     if ($value eq '__undef__') {
 1546: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1547: 	$value=undef;
 1548:     }
 1549:     &make_room($id,$value,$debug);
 1550:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1551:     return ($value,1);
 1552: }
 1553: 
 1554: sub do_cache_new {
 1555:     my ($name,$id,$value,$time,$debug) = @_;
 1556:     $id=&make_key($name,$id);
 1557:     my $setvalue=$value;
 1558:     if (!defined($setvalue)) {
 1559: 	$setvalue='__undef__';
 1560:     }
 1561:     if (!defined($time) ) {
 1562: 	$time=600;
 1563:     }
 1564:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1565:     my $result = $memcache->set($id,$setvalue,$time);
 1566:     if (! $result) {
 1567: 	&logthis("caching of id -> $id  failed");
 1568: 	$memcache->disconnect_all();
 1569:     }
 1570:     # need to make a copy of $value
 1571:     &make_room($id,$value,$debug);
 1572:     return $value;
 1573: }
 1574: 
 1575: sub make_room {
 1576:     my ($id,$value,$debug)=@_;
 1577: 
 1578:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1579:                                     : $value;
 1580:     if ($to_remember<0) { return; }
 1581:     $accessed{$id}=[&gettimeofday()];
 1582:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1583:     my $to_kick;
 1584:     my $max_time=0;
 1585:     foreach my $other (keys(%accessed)) {
 1586: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1587: 	    $to_kick=$other;
 1588: 	    $max_time=&tv_interval($accessed{$other});
 1589: 	}
 1590:     }
 1591:     delete($remembered{$to_kick});
 1592:     delete($accessed{$to_kick});
 1593:     $kicks++;
 1594:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1595:     return;
 1596: }
 1597: 
 1598: sub purge_remembered {
 1599:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1600:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1601:     undef(%remembered);
 1602:     undef(%accessed);
 1603: }
 1604: # ------------------------------------- Read an entry from a user's environment
 1605: 
 1606: sub userenvironment {
 1607:     my ($udom,$unam,@what)=@_;
 1608:     my $items;
 1609:     foreach my $item (@what) {
 1610:         $items.=&escape($item).'&';
 1611:     }
 1612:     $items=~s/\&$//;
 1613:     my %returnhash=();
 1614:     my @answer=split(/\&/,
 1615:                 &reply('get:'.$udom.':'.$unam.':environment:'.$items,
 1616:                       &homeserver($unam,$udom)));
 1617:     my $i;
 1618:     for ($i=0;$i<=$#what;$i++) {
 1619: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1620:     }
 1621:     return %returnhash;
 1622: }
 1623: 
 1624: # ---------------------------------------------------------- Get a studentphoto
 1625: sub studentphoto {
 1626:     my ($udom,$unam,$ext) = @_;
 1627:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1628:     if (defined($env{'request.course.id'})) {
 1629:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1630:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1631:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1632:             } else {
 1633:                 my ($result,$perm_reqd)=
 1634: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1635:                 if ($result eq 'ok') {
 1636:                     if (!($perm_reqd eq 'yes')) {
 1637:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1638:                     }
 1639:                 }
 1640:             }
 1641:         }
 1642:     } else {
 1643:         my ($result,$perm_reqd) = 
 1644: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1645:         if ($result eq 'ok') {
 1646:             if (!($perm_reqd eq 'yes')) {
 1647:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1648:             }
 1649:         }
 1650:     }
 1651:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1652: }
 1653: 
 1654: sub retrievestudentphoto {
 1655:     my ($udom,$unam,$ext,$type) = @_;
 1656:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1657:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1658:     if ($ret eq 'ok') {
 1659:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1660:         if ($type eq 'thumbnail') {
 1661:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1662:         }
 1663:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1664:         return $tokenurl;
 1665:     } else {
 1666:         if ($type eq 'thumbnail') {
 1667:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1668:         } else { 
 1669:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1670:         }
 1671:     }
 1672: }
 1673: 
 1674: # -------------------------------------------------------------------- New chat
 1675: 
 1676: sub chatsend {
 1677:     my ($newentry,$anon,$group)=@_;
 1678:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1679:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1680:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1681:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1682: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1683: 		   &escape($newentry)).':'.$group,$chome);
 1684: }
 1685: 
 1686: # ------------------------------------------ Find current version of a resource
 1687: 
 1688: sub getversion {
 1689:     my $fname=&clutter(shift);
 1690:     unless ($fname=~/^\/res\//) { return -1; }
 1691:     return &currentversion(&filelocation('',$fname));
 1692: }
 1693: 
 1694: sub currentversion {
 1695:     my $fname=shift;
 1696:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1697:     if (defined($cached)) { return $result; }
 1698:     my $author=$fname;
 1699:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1700:     my ($udom,$uname)=split(/\//,$author);
 1701:     my $home=homeserver($uname,$udom);
 1702:     if ($home eq 'no_host') { 
 1703:         return -1; 
 1704:     }
 1705:     my $answer=reply("currentversion:$fname",$home);
 1706:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1707: 	return -1;
 1708:     }
 1709:     return &do_cache_new('resversion',$fname,$answer,600);
 1710: }
 1711: 
 1712: # ----------------------------- Subscribe to a resource, return URL if possible
 1713: 
 1714: sub subscribe {
 1715:     my $fname=shift;
 1716:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1717:     $fname=~s/[\n\r]//g;
 1718:     my $author=$fname;
 1719:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1720:     my ($udom,$uname)=split(/\//,$author);
 1721:     my $home=homeserver($uname,$udom);
 1722:     if ($home eq 'no_host') {
 1723:         return 'not_found';
 1724:     }
 1725:     my $answer=reply("sub:$fname",$home);
 1726:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1727: 	$answer.=' by '.$home;
 1728:     }
 1729:     return $answer;
 1730: }
 1731:     
 1732: # -------------------------------------------------------------- Replicate file
 1733: 
 1734: sub repcopy {
 1735:     my $filename=shift;
 1736:     $filename=~s/\/+/\//g;
 1737:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1738:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1739:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1740: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1741: 	return &repcopy_userfile($filename);
 1742:     }
 1743:     $filename=~s/[\n\r]//g;
 1744:     my $transname="$filename.in.transfer";
 1745: # FIXME: this should flock
 1746:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1747:     my $remoteurl=subscribe($filename);
 1748:     if ($remoteurl =~ /^con_lost by/) {
 1749: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1750:            return 'unavailable';
 1751:     } elsif ($remoteurl eq 'not_found') {
 1752: 	   #&logthis("Subscribe returned not_found: $filename");
 1753: 	   return 'not_found';
 1754:     } elsif ($remoteurl =~ /^rejected by/) {
 1755: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1756:            return 'forbidden';
 1757:     } elsif ($remoteurl eq 'directory') {
 1758:            return 'ok';
 1759:     } else {
 1760:         my $author=$filename;
 1761:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1762:         my ($udom,$uname)=split(/\//,$author);
 1763:         my $home=homeserver($uname,$udom);
 1764:         unless ($home eq $perlvar{'lonHostID'}) {
 1765:            my @parts=split(/\//,$filename);
 1766:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1767:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1768:                &logthis("Malconfiguration for replication: $filename");
 1769: 	       return 'bad_request';
 1770:            }
 1771:            my $count;
 1772:            for ($count=5;$count<$#parts;$count++) {
 1773:                $path.="/$parts[$count]";
 1774:                if ((-e $path)!=1) {
 1775: 		   mkdir($path,0777);
 1776:                }
 1777:            }
 1778:            my $ua=new LWP::UserAgent;
 1779:            my $request=new HTTP::Request('GET',"$remoteurl");
 1780:            my $response=$ua->request($request,$transname);
 1781:            if ($response->is_error()) {
 1782: 	       unlink($transname);
 1783:                my $message=$response->status_line;
 1784:                &logthis("<font color=\"blue\">WARNING:"
 1785:                        ." LWP get: $message: $filename</font>");
 1786:                return 'unavailable';
 1787:            } else {
 1788: 	       if ($remoteurl!~/\.meta$/) {
 1789:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1790:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1791:                   if ($mresponse->is_error()) {
 1792: 		      unlink($filename.'.meta');
 1793:                       &logthis(
 1794:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1795:                   }
 1796: 	       }
 1797:                rename($transname,$filename);
 1798:                return 'ok';
 1799:            }
 1800:        }
 1801:     }
 1802: }
 1803: 
 1804: # ------------------------------------------------ Get server side include body
 1805: sub ssi_body {
 1806:     my ($filelink,%form)=@_;
 1807:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1808:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1809:     }
 1810:     my $output='';
 1811:     my $response;
 1812:     if ($filelink=~/^https?\:/) {
 1813:        ($output,$response)=&externalssi($filelink);
 1814:     } else {
 1815:        ($output,$response)=&ssi($filelink,%form);
 1816:     }
 1817:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1818:     $output=~s/^.*?\<body[^\>]*\>//si;
 1819:     $output=~s/\<\/body\s*\>.*?$//si;
 1820:     if (wantarray) {
 1821:         return ($output, $response);
 1822:     } else {
 1823:         return $output;
 1824:     }
 1825: }
 1826: 
 1827: # --------------------------------------------------------- Server Side Include
 1828: 
 1829: sub absolute_url {
 1830:     my ($host_name) = @_;
 1831:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1832:     if ($host_name eq '') {
 1833: 	$host_name = $ENV{'SERVER_NAME'};
 1834:     }
 1835:     return $protocol.$host_name;
 1836: }
 1837: 
 1838: #
 1839: #   Server side include.
 1840: # Parameters:
 1841: #  fn     Possibly encrypted resource name/id.
 1842: #  form   Hash that describes how the rendering should be done
 1843: #         and other things.
 1844: # Returns:
 1845: #   Scalar context: The content of the response.
 1846: #   Array context:  2 element list of the content and the full response object.
 1847: #     
 1848: sub ssi {
 1849: 
 1850:     my ($fn,%form)=@_;
 1851:     my $ua=new LWP::UserAgent;
 1852:     my $request;
 1853: 
 1854:     $form{'no_update_last_known'}=1;
 1855:     &Apache::lonenc::check_encrypt(\$fn);
 1856:     if (%form) {
 1857:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1858:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1859:     } else {
 1860:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1861:     }
 1862: 
 1863:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1864:     my $response=$ua->request($request);
 1865: 
 1866:     if (wantarray) {
 1867: 	return ($response->content, $response);
 1868:     } else {
 1869: 	return $response->content;
 1870:     }
 1871: }
 1872: 
 1873: sub externalssi {
 1874:     my ($url)=@_;
 1875:     my $ua=new LWP::UserAgent;
 1876:     my $request=new HTTP::Request('GET',$url);
 1877:     my $response=$ua->request($request);
 1878:     if (wantarray) {
 1879:         return ($response->content, $response);
 1880:     } else {
 1881:         return $response->content;
 1882:     }
 1883: }
 1884: 
 1885: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1886: 
 1887: sub allowuploaded {
 1888:     my ($srcurl,$url)=@_;
 1889:     $url=&clutter(&declutter($url));
 1890:     my $dir=$url;
 1891:     $dir=~s/\/[^\/]+$//;
 1892:     my %httpref=();
 1893:     my $httpurl=&hreflocation('',$url);
 1894:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1895:     &Apache::lonnet::appenv(\%httpref);
 1896: }
 1897: 
 1898: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1899: # input: action, courseID, current domain, intended
 1900: #        path to file, source of file, instruction to parse file for objects,
 1901: #        ref to hash for embedded objects,
 1902: #        ref to hash for codebase of java objects.
 1903: #
 1904: # output: url to file (if action was uploaddoc), 
 1905: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1906: #
 1907: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1908: # course.
 1909: #
 1910: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1911: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1912: #          course's home server.
 1913: #
 1914: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1915: #          be copied from $source (current location) to 
 1916: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1917: #         and will then be copied to
 1918: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1919: #         course's home server.
 1920: #
 1921: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1922: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1923: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1924: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1925: #         in course's home server.
 1926: #
 1927: 
 1928: sub process_coursefile {
 1929:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1930:     my $fetchresult;
 1931:     my $home=&homeserver($docuname,$docudom);
 1932:     if ($action eq 'propagate') {
 1933:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1934: 			     $home);
 1935:     } else {
 1936:         my $fpath = '';
 1937:         my $fname = $file;
 1938:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1939:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1940:         my $filepath = &build_filepath($fpath);
 1941:         if ($action eq 'copy') {
 1942:             if ($source eq '') {
 1943:                 $fetchresult = 'no source file';
 1944:                 return $fetchresult;
 1945:             } else {
 1946:                 my $destination = $filepath.'/'.$fname;
 1947:                 rename($source,$destination);
 1948:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1949:                                  $home);
 1950:             }
 1951:         } elsif ($action eq 'uploaddoc') {
 1952:             open(my $fh,'>'.$filepath.'/'.$fname);
 1953:             print $fh $env{'form.'.$source};
 1954:             close($fh);
 1955:             if ($parser eq 'parse') {
 1956:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 1957:                 unless ($parse_result eq 'ok') {
 1958:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1959:                 }
 1960:             }
 1961:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1962:                                  $home);
 1963:             if ($fetchresult eq 'ok') {
 1964:                 return '/uploaded/'.$fpath.'/'.$fname;
 1965:             } else {
 1966:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1967:                         ' to host '.$home.': '.$fetchresult);
 1968:                 return '/adm/notfound.html';
 1969:             }
 1970:         }
 1971:     }
 1972:     unless ( $fetchresult eq 'ok') {
 1973:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1974:              ' to host '.$home.': '.$fetchresult);
 1975:     }
 1976:     return $fetchresult;
 1977: }
 1978: 
 1979: sub build_filepath {
 1980:     my ($fpath) = @_;
 1981:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1982:     unless ($fpath eq '') {
 1983:         my @parts=split('/',$fpath);
 1984:         foreach my $part (@parts) {
 1985:             $filepath.= '/'.$part;
 1986:             if ((-e $filepath)!=1) {
 1987:                 mkdir($filepath,0777);
 1988:             }
 1989:         }
 1990:     }
 1991:     return $filepath;
 1992: }
 1993: 
 1994: sub store_edited_file {
 1995:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1996:     my $file = $primary_url;
 1997:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1998:     my $fpath = '';
 1999:     my $fname = $file;
 2000:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2001:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2002:     my $filepath = &build_filepath($fpath);
 2003:     open(my $fh,'>'.$filepath.'/'.$fname);
 2004:     print $fh $content;
 2005:     close($fh);
 2006:     my $home=&homeserver($docuname,$docudom);
 2007:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2008: 			  $home);
 2009:     if ($$fetchresult eq 'ok') {
 2010:         return '/uploaded/'.$fpath.'/'.$fname;
 2011:     } else {
 2012:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2013: 		 ' to host '.$home.': '.$$fetchresult);
 2014:         return '/adm/notfound.html';
 2015:     }
 2016: }
 2017: 
 2018: sub clean_filename {
 2019:     my ($fname,$args)=@_;
 2020: # Replace Windows backslashes by forward slashes
 2021:     $fname=~s/\\/\//g;
 2022:     if (!$args->{'keep_path'}) {
 2023:         # Get rid of everything but the actual filename
 2024: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2025:     }
 2026: # Replace spaces by underscores
 2027:     $fname=~s/\s+/\_/g;
 2028: # Replace all other weird characters by nothing
 2029:     $fname=~s{[^/\w\.\-]}{}g;
 2030: # Replace all .\d. sequences with _\d. so they no longer look like version
 2031: # numbers
 2032:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2033:     return $fname;
 2034: }
 2035: 
 2036: # --------------- Take an uploaded file and put it into the userfiles directory
 2037: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2038: #                    the desired filenam is in $env{"form.$formname.filename"}
 2039: #        $coursedoc - if true up to the current course
 2040: #                     if false
 2041: #        $subdir - directory in userfile to store the file into
 2042: #        $parser - instruction to parse file for objects ($parser = parse)    
 2043: #        $allfiles - reference to hash for embedded objects
 2044: #        $codebase - reference to hash for codebase of java objects
 2045: #        $desuname - username for permanent storage of uploaded file
 2046: #        $dsetudom - domain for permanaent storage of uploaded file
 2047: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2048: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2049: # 
 2050: # output: url of file in userspace, or error: <message> 
 2051: #             or /adm/notfound.html if failure to upload occurse
 2052: 
 2053: 
 2054: sub userfileupload {
 2055:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 2056:         $destudom,$thumbwidth,$thumbheight)=@_;
 2057:     if (!defined($subdir)) { $subdir='unknown'; }
 2058:     my $fname=$env{'form.'.$formname.'.filename'};
 2059:     $fname=&clean_filename($fname);
 2060: # See if there is anything left
 2061:     unless ($fname) { return 'error: no uploaded file'; }
 2062:     chop($env{'form.'.$formname});
 2063:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 2064:         my $now = time;
 2065:         my $filepath = 'tmp/helprequests/'.$now;
 2066:         my @parts=split(/\//,$filepath);
 2067:         my $fullpath = $perlvar{'lonDaemons'};
 2068:         for (my $i=0;$i<@parts;$i++) {
 2069:             $fullpath .= '/'.$parts[$i];
 2070:             if ((-e $fullpath)!=1) {
 2071:                 mkdir($fullpath,0777);
 2072:             }
 2073:         }
 2074:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2075:         print $fh $env{'form.'.$formname};
 2076:         close($fh);
 2077:         return $fullpath.'/'.$fname;
 2078:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 2079:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2080:                        '_'.$env{'user.domain'}.'/pending';
 2081:         my @parts=split(/\//,$filepath);
 2082:         my $fullpath = $perlvar{'lonDaemons'};
 2083:         for (my $i=0;$i<@parts;$i++) {
 2084:             $fullpath .= '/'.$parts[$i];
 2085:             if ((-e $fullpath)!=1) {
 2086:                 mkdir($fullpath,0777);
 2087:             }
 2088:         }
 2089:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2090:         print $fh $env{'form.'.$formname};
 2091:         close($fh);
 2092:         return $fullpath.'/'.$fname;
 2093:     }
 2094:     
 2095: # Create the directory if not present
 2096:     $fname="$subdir/$fname";
 2097:     if ($coursedoc) {
 2098: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2099: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2100:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2101:             return &finishuserfileupload($docuname,$docudom,
 2102: 					 $formname,$fname,$parser,$allfiles,
 2103: 					 $codebase,$thumbwidth,$thumbheight);
 2104:         } else {
 2105:             $fname=$env{'form.folder'}.'/'.$fname;
 2106:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2107: 				       $fname,$formname,$parser,
 2108: 				       $allfiles,$codebase);
 2109:         }
 2110:     } elsif (defined($destuname)) {
 2111:         my $docuname=$destuname;
 2112:         my $docudom=$destudom;
 2113: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2114: 				     $parser,$allfiles,$codebase,
 2115:                                      $thumbwidth,$thumbheight);
 2116:         
 2117:     } else {
 2118:         my $docuname=$env{'user.name'};
 2119:         my $docudom=$env{'user.domain'};
 2120:         if (exists($env{'form.group'})) {
 2121:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2122:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2123:         }
 2124: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2125: 				     $parser,$allfiles,$codebase,
 2126:                                      $thumbwidth,$thumbheight);
 2127:     }
 2128: }
 2129: 
 2130: sub finishuserfileupload {
 2131:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2132:         $thumbwidth,$thumbheight) = @_;
 2133:     my $path=$docudom.'/'.$docuname.'/';
 2134:     my $filepath=$perlvar{'lonDocRoot'};
 2135:     my ($fnamepath,$file,$fetchthumb);
 2136:     $file=$fname;
 2137:     if ($fname=~m|/|) {
 2138:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2139: 	$path.=$fnamepath.'/';
 2140:     }
 2141:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2142:     my $count;
 2143:     for ($count=4;$count<=$#parts;$count++) {
 2144:         $filepath.="/$parts[$count]";
 2145:         if ((-e $filepath)!=1) {
 2146: 	    mkdir($filepath,0777);
 2147:         }
 2148:     }
 2149: # Save the file
 2150:     {
 2151: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2152: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2153: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2154: 	    return '/adm/notfound.html';
 2155: 	}
 2156: 	if (!print FH ($env{'form.'.$formname})) {
 2157: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2158: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2159: 	    return '/adm/notfound.html';
 2160: 	}
 2161: 	close(FH);
 2162:     }
 2163:     if ($parser eq 'parse') {
 2164:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
 2165: 						   $codebase);
 2166:         unless ($parse_result eq 'ok') {
 2167:             &logthis('Failed to parse '.$filepath.$file.
 2168: 		     ' for embedded media: '.$parse_result); 
 2169:         }
 2170:     }
 2171:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2172:         my $input = $filepath.'/'.$file;
 2173:         my $output = $filepath.'/'.'tn-'.$file;
 2174:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2175:         system("convert -sample $thumbsize $input $output");
 2176:         if (-e $filepath.'/'.'tn-'.$file) {
 2177:             $fetchthumb  = 1; 
 2178:         }
 2179:     }
 2180:  
 2181: # Notify homeserver to grep it
 2182: #
 2183:     my $docuhome=&homeserver($docuname,$docudom);
 2184:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2185:     if ($fetchresult eq 'ok') {
 2186:         if ($fetchthumb) {
 2187:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2188:             if ($thumbresult ne 'ok') {
 2189:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2190:                          $docuhome.': '.$thumbresult);
 2191:             }
 2192:         }
 2193: #
 2194: # Return the URL to it
 2195:         return '/uploaded/'.$path.$file;
 2196:     } else {
 2197:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2198: 		 ': '.$fetchresult);
 2199:         return '/adm/notfound.html';
 2200:     }
 2201: }
 2202: 
 2203: sub extract_embedded_items {
 2204:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 2205:     my @state = ();
 2206:     my %javafiles = (
 2207:                       codebase => '',
 2208:                       code => '',
 2209:                       archive => ''
 2210:                     );
 2211:     my %mediafiles = (
 2212:                       src => '',
 2213:                       movie => '',
 2214:                      );
 2215:     my $p;
 2216:     if ($content) {
 2217:         $p = HTML::LCParser->new($content);
 2218:     } else {
 2219:         $p = HTML::LCParser->new($fullpath);
 2220:     }
 2221:     while (my $t=$p->get_token()) {
 2222: 	if ($t->[0] eq 'S') {
 2223: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2224: 	    push(@state, $tagname);
 2225:             if (lc($tagname) eq 'allow') {
 2226:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2227:             }
 2228: 	    if (lc($tagname) eq 'img') {
 2229: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2230: 	    }
 2231: 	    if (lc($tagname) eq 'a') {
 2232: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2233: 	    }
 2234:             if (lc($tagname) eq 'script') {
 2235:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2236:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2237:                 } else {
 2238:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2239:                 }
 2240:             }
 2241:             if (lc($tagname) eq 'link') {
 2242:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2243:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2244:                 }
 2245:             }
 2246: 	    if (lc($tagname) eq 'object' ||
 2247: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2248: 		foreach my $item (keys(%javafiles)) {
 2249: 		    $javafiles{$item} = '';
 2250: 		}
 2251: 	    }
 2252: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2253: 		my $name = lc($attr->{'name'});
 2254: 		foreach my $item (keys(%javafiles)) {
 2255: 		    if ($name eq $item) {
 2256: 			$javafiles{$item} = $attr->{'value'};
 2257: 			last;
 2258: 		    }
 2259: 		}
 2260: 		foreach my $item (keys(%mediafiles)) {
 2261: 		    if ($name eq $item) {
 2262: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2263: 			last;
 2264: 		    }
 2265: 		}
 2266: 	    }
 2267: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2268: 		foreach my $item (keys(%javafiles)) {
 2269: 		    if ($attr->{$item}) {
 2270: 			$javafiles{$item} = $attr->{$item};
 2271: 			last;
 2272: 		    }
 2273: 		}
 2274: 		foreach my $item (keys(%mediafiles)) {
 2275: 		    if ($attr->{$item}) {
 2276: 			&add_filetype($allfiles,$attr->{$item},$item);
 2277: 			last;
 2278: 		    }
 2279: 		}
 2280: 	    }
 2281: 	} elsif ($t->[0] eq 'E') {
 2282: 	    my ($tagname) = ($t->[1]);
 2283: 	    if ($javafiles{'codebase'} ne '') {
 2284: 		$javafiles{'codebase'} .= '/';
 2285: 	    }  
 2286: 	    if (lc($tagname) eq 'applet' ||
 2287: 		lc($tagname) eq 'object' ||
 2288: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2289: 		) {
 2290: 		foreach my $item (keys(%javafiles)) {
 2291: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2292: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2293: 			&add_filetype($allfiles,$file,$item);
 2294: 		    }
 2295: 		}
 2296: 	    } 
 2297: 	    pop @state;
 2298: 	}
 2299:     }
 2300:     return 'ok';
 2301: }
 2302: 
 2303: sub add_filetype {
 2304:     my ($allfiles,$file,$type)=@_;
 2305:     if (exists($allfiles->{$file})) {
 2306: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2307: 	    push(@{$allfiles->{$file}}, &escape($type));
 2308: 	}
 2309:     } else {
 2310: 	@{$allfiles->{$file}} = (&escape($type));
 2311:     }
 2312: }
 2313: 
 2314: sub removeuploadedurl {
 2315:     my ($url)=@_;
 2316:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 2317:     return &removeuserfile($uname,$udom,$fname);
 2318: }
 2319: 
 2320: sub removeuserfile {
 2321:     my ($docuname,$docudom,$fname)=@_;
 2322:     my $home=&homeserver($docuname,$docudom);
 2323:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2324:     if ($result eq 'ok') {
 2325:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2326:             my $metafile = $fname.'.meta';
 2327:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2328: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2329:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2330:             my $sqlresult = 
 2331:                 &update_portfolio_table($docuname,$docudom,$file,
 2332:                                         'portfolio_metadata',$group,
 2333:                                         'delete');
 2334:         }
 2335:     }
 2336:     return $result;
 2337: }
 2338: 
 2339: sub mkdiruserfile {
 2340:     my ($docuname,$docudom,$dir)=@_;
 2341:     my $home=&homeserver($docuname,$docudom);
 2342:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2343: }
 2344: 
 2345: sub renameuserfile {
 2346:     my ($docuname,$docudom,$old,$new)=@_;
 2347:     my $home=&homeserver($docuname,$docudom);
 2348:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2349:                         &escape("$old").':'.&escape("$new"),$home);
 2350:     if ($result eq 'ok') {
 2351:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2352:             my $oldmeta = $old.'.meta';
 2353:             my $newmeta = $new.'.meta';
 2354:             my $metaresult = 
 2355:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2356: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2357:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2358:             my $sqlresult = 
 2359:                 &update_portfolio_table($docuname,$docudom,$file,
 2360:                                         'portfolio_metadata',$group,
 2361:                                         'delete');
 2362:         }
 2363:     }
 2364:     return $result;
 2365: }
 2366: 
 2367: # ------------------------------------------------------------------------- Log
 2368: 
 2369: sub log {
 2370:     my ($dom,$nam,$hom,$what)=@_;
 2371:     return critical("log:$dom:$nam:$what",$hom);
 2372: }
 2373: 
 2374: # ------------------------------------------------------------------ Course Log
 2375: #
 2376: # This routine flushes several buffers of non-mission-critical nature
 2377: #
 2378: 
 2379: sub flushcourselogs {
 2380:     &logthis('Flushing log buffers');
 2381: #
 2382: # course logs
 2383: # This is a log of all transactions in a course, which can be used
 2384: # for data mining purposes
 2385: #
 2386: # It also collects the courseid database, which lists last transaction
 2387: # times and course titles for all courseids
 2388: #
 2389:     my %courseidbuffer=();
 2390:     foreach my $crsid (keys(%courselogs)) {
 2391:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2392: 		          &escape($courselogs{$crsid}),
 2393: 		          $coursehombuf{$crsid}) eq 'ok') {
 2394: 	    delete $courselogs{$crsid};
 2395:         } else {
 2396:             &logthis('Failed to flush log buffer for '.$crsid);
 2397:             if (length($courselogs{$crsid})>40000) {
 2398:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2399:                         " exceeded maximum size, deleting.</font>");
 2400:                delete $courselogs{$crsid};
 2401:             }
 2402:         }
 2403:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2404:             'description' => $coursedescrbuf{$crsid},
 2405:             'inst_code'    => $courseinstcodebuf{$crsid},
 2406:             'type'        => $coursetypebuf{$crsid},
 2407:             'owner'       => $courseownerbuf{$crsid},
 2408:         };
 2409:     }
 2410: #
 2411: # Write course id database (reverse lookup) to homeserver of courses 
 2412: # Is used in pickcourse
 2413: #
 2414:     foreach my $crs_home (keys(%courseidbuffer)) {
 2415:         my $response = &courseidput(&host_domain($crs_home),
 2416:                                     $courseidbuffer{$crs_home},
 2417:                                     $crs_home,'timeonly');
 2418:     }
 2419: #
 2420: # File accesses
 2421: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2422: #
 2423:     foreach my $entry (keys(%accesshash)) {
 2424:         if ($entry =~ /___count$/) {
 2425:             my ($dom,$name);
 2426:             ($dom,$name,undef)=
 2427: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2428:             if (! defined($dom) || $dom eq '' || 
 2429:                 ! defined($name) || $name eq '') {
 2430:                 my $cid = $env{'request.course.id'};
 2431:                 $dom  = $env{'request.'.$cid.'.domain'};
 2432:                 $name = $env{'request.'.$cid.'.num'};
 2433:             }
 2434:             my $value = $accesshash{$entry};
 2435:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2436:             my %temphash=($url => $value);
 2437:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2438:             if ($result eq 'ok') {
 2439:                 delete $accesshash{$entry};
 2440:             } elsif ($result eq 'unknown_cmd') {
 2441:                 # Target server has old code running on it.
 2442:                 my %temphash=($entry => $value);
 2443:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2444:                     delete $accesshash{$entry};
 2445:                 }
 2446:             }
 2447:         } else {
 2448:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2449:             my %temphash=($entry => $accesshash{$entry});
 2450:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2451:                 delete $accesshash{$entry};
 2452:             }
 2453:         }
 2454:     }
 2455: #
 2456: # Roles
 2457: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2458: #
 2459:     foreach my $entry (keys(%userrolehash)) {
 2460:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2461: 	    split(/\:/,$entry);
 2462:         if (&Apache::lonnet::put('nohist_userroles',
 2463:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2464:                 $rudom,$runame) eq 'ok') {
 2465: 	    delete $userrolehash{$entry};
 2466:         }
 2467:     }
 2468: #
 2469: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2470: #
 2471:     my %domrolebuffer = ();
 2472:     foreach my $entry (keys %domainrolehash) {
 2473:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2474:         if ($domrolebuffer{$rudom}) {
 2475:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2476:                       '='.&escape($domainrolehash{$entry});
 2477:         } else {
 2478:             $domrolebuffer{$rudom}.=&escape($entry).
 2479:                       '='.&escape($domainrolehash{$entry});
 2480:         }
 2481:         delete $domainrolehash{$entry};
 2482:     }
 2483:     foreach my $dom (keys(%domrolebuffer)) {
 2484: 	my %servers = &get_servers($dom,'library');
 2485: 	foreach my $tryserver (keys(%servers)) {
 2486: 	    unless (&reply('domroleput:'.$dom.':'.
 2487: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2488: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2489: 	    }
 2490:         }
 2491:     }
 2492:     $dumpcount++;
 2493: }
 2494: 
 2495: sub courselog {
 2496:     my $what=shift;
 2497:     $what=time.':'.$what;
 2498:     unless ($env{'request.course.id'}) { return ''; }
 2499:     $coursedombuf{$env{'request.course.id'}}=
 2500:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2501:     $coursenumbuf{$env{'request.course.id'}}=
 2502:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2503:     $coursehombuf{$env{'request.course.id'}}=
 2504:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2505:     $coursedescrbuf{$env{'request.course.id'}}=
 2506:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2507:     $courseinstcodebuf{$env{'request.course.id'}}=
 2508:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2509:     $courseownerbuf{$env{'request.course.id'}}=
 2510:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2511:     $coursetypebuf{$env{'request.course.id'}}=
 2512:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2513:     if (defined $courselogs{$env{'request.course.id'}}) {
 2514: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2515:     } else {
 2516: 	$courselogs{$env{'request.course.id'}}.=$what;
 2517:     }
 2518:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2519: 	&flushcourselogs();
 2520:     }
 2521: }
 2522: 
 2523: sub courseacclog {
 2524:     my $fnsymb=shift;
 2525:     unless ($env{'request.course.id'}) { return ''; }
 2526:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2527:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2528:         $what.=':POST';
 2529:         # FIXME: Probably ought to escape things....
 2530: 	foreach my $key (keys(%env)) {
 2531:             if ($key=~/^form\.(.*)/) {
 2532:                 my $formitem = $1;
 2533:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 2534:                     $what.=':'.$formitem.'='.$env{$key};
 2535:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 2536:                     $what.=':'.$formitem.'='.$env{$key};
 2537:                 }
 2538:             }
 2539:         }
 2540:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2541:         # FIXME: We should not be depending on a form parameter that someone
 2542:         # editing lonsearchcat.pm might change in the future.
 2543:         if ($env{'form.phase'} eq 'course_search') {
 2544:             $what.= ':POST';
 2545:             # FIXME: Probably ought to escape things....
 2546:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2547:                                  'crsdiscuss') {
 2548:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2549:             }
 2550:         }
 2551:     }
 2552:     &courselog($what);
 2553: }
 2554: 
 2555: sub countacc {
 2556:     my $url=&declutter(shift);
 2557:     return if (! defined($url) || $url eq '');
 2558:     unless ($env{'request.course.id'}) { return ''; }
 2559:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2560:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2561:     $accesshash{$key}++;
 2562: }
 2563: 
 2564: sub linklog {
 2565:     my ($from,$to)=@_;
 2566:     $from=&declutter($from);
 2567:     $to=&declutter($to);
 2568:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2569:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2570: }
 2571:   
 2572: sub userrolelog {
 2573:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2574:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2575:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2576:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2577:         ($trole=~/^ta/)) {
 2578:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2579:        $userrolehash
 2580:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2581:                     =$tend.':'.$tstart;
 2582:     }
 2583:     if (($env{'request.role'} =~ /dc\./) &&
 2584: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2585: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2586: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
 2587:        $userrolehash
 2588:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2589:                     =$tend.':'.$tstart;
 2590:     }
 2591:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2592:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2593:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2594:         ($trole=~/^sc/)) {
 2595:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2596:        $domainrolehash
 2597:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2598:                     = $tend.':'.$tstart;
 2599:     }
 2600: }
 2601: 
 2602: sub courserolelog {
 2603:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 2604:     if (($trole eq 'cc') || ($trole eq 'in') ||
 2605:         ($trole eq 'ep') || ($trole eq 'ad') ||
 2606:         ($trole eq 'ta') || ($trole eq 'st') ||
 2607:         ($trole=~/^cr/) || ($trole eq 'gr')) {
 2608:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 2609:             my $cdom = $1;
 2610:             my $cnum = $2;
 2611:             my $sec = $3;
 2612:             my $namespace = 'rolelog';
 2613:             my %storehash = (
 2614:                                role    => $trole,
 2615:                                start   => $tstart,
 2616:                                end     => $tend,
 2617:                                selfenroll => $selfenroll,
 2618:                                context    => $context,
 2619:                             );
 2620:             if ($trole eq 'gr') {
 2621:                 $namespace = 'groupslog';
 2622:                 $storehash{'group'} = $sec;
 2623:             } else {
 2624:                 $storehash{'section'} = $sec;
 2625:             }
 2626:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 2627:             if (($trole ne 'st') || ($sec ne '')) {
 2628:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 2629:             }
 2630:         }
 2631:     }
 2632:     return;
 2633: }
 2634: 
 2635: sub get_course_adv_roles {
 2636:     my ($cid,$codes) = @_;
 2637:     $cid=$env{'request.course.id'} unless (defined($cid));
 2638:     my %coursehash=&coursedescription($cid);
 2639:     my %nothide=();
 2640:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2641:         if ($user !~ /:/) {
 2642: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2643:         } else {
 2644:             $nothide{$user}=1;
 2645:         }
 2646:     }
 2647:     my %returnhash=();
 2648:     my %dumphash=
 2649:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2650:     my $now=time;
 2651:     my %privileged;
 2652:     foreach my $entry (keys %dumphash) {
 2653: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2654:         if (($tstart) && ($tstart<0)) { next; }
 2655:         if (($tend) && ($tend<$now)) { next; }
 2656:         if (($tstart) && ($now<$tstart)) { next; }
 2657:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2658: 	if ($username eq '' || $domain eq '') { next; }
 2659:         unless (ref($privileged{$domain}) eq 'HASH') {
 2660:             my %dompersonnel =
 2661:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 2662:             $privileged{$domain} = {};
 2663:             foreach my $server (keys(%dompersonnel)) {
 2664:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 2665:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 2666:                         my ($trole,$uname,$udom) = split(/:/,$user);
 2667:                         $privileged{$udom}{$uname} = 1;
 2668:                     }
 2669:                 }
 2670:             }
 2671:         }
 2672:         if ((exists($privileged{$domain}{$username})) &&
 2673:             (!$nothide{$username.':'.$domain})) { next; }
 2674: 	if ($role eq 'cr') { next; }
 2675:         if ($codes) {
 2676:             if ($section) { $role .= ':'.$section; }
 2677:             if ($returnhash{$role}) {
 2678:                 $returnhash{$role}.=','.$username.':'.$domain;
 2679:             } else {
 2680:                 $returnhash{$role}=$username.':'.$domain;
 2681:             }
 2682:         } else {
 2683:             my $key=&plaintext($role);
 2684:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 2685:             if ($returnhash{$key}) {
 2686: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2687:             } else {
 2688:                 $returnhash{$key}=$username.':'.$domain;
 2689:             }
 2690:         }
 2691:     }
 2692:     return %returnhash;
 2693: }
 2694: 
 2695: sub get_my_roles {
 2696:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2697:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2698:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2699:     my (%dumphash,%nothide);
 2700:     if ($context eq 'userroles') { 
 2701:         %dumphash = &dump('roles',$udom,$uname);
 2702:     } else {
 2703:         %dumphash=
 2704:             &dump('nohist_userroles',$udom,$uname);
 2705:         if ($hidepriv) {
 2706:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2707:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2708:                 if ($user !~ /:/) {
 2709:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2710:                 } else {
 2711:                     $nothide{$user} = 1;
 2712:                 }
 2713:             }
 2714:         }
 2715:     }
 2716:     my %returnhash=();
 2717:     my $now=time;
 2718:     my %privileged;
 2719:     foreach my $entry (keys(%dumphash)) {
 2720:         my ($role,$tend,$tstart);
 2721:         if ($context eq 'userroles') {
 2722: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2723:         } else {
 2724:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2725:         }
 2726:         if (($tstart) && ($tstart<0)) { next; }
 2727:         my $status = 'active';
 2728:         if (($tend) && ($tend<=$now)) {
 2729:             $status = 'previous';
 2730:         } 
 2731:         if (($tstart) && ($now<$tstart)) {
 2732:             $status = 'future';
 2733:         }
 2734:         if (ref($types) eq 'ARRAY') {
 2735:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2736:                 next;
 2737:             } 
 2738:         } else {
 2739:             if ($status ne 'active') {
 2740:                 next;
 2741:             }
 2742:         }
 2743:         my ($rolecode,$username,$domain,$section,$area);
 2744:         if ($context eq 'userroles') {
 2745:             ($area,$rolecode) = split(/_/,$entry);
 2746:             (undef,$domain,$username,$section) = split(/\//,$area);
 2747:         } else {
 2748:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2749:         }
 2750:         if (ref($roledoms) eq 'ARRAY') {
 2751:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2752:                 next;
 2753:             }
 2754:         }
 2755:         if (ref($roles) eq 'ARRAY') {
 2756:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2757:                 if ($role =~ /^cr\//) {
 2758:                     if (!grep(/^cr$/,@{$roles})) {
 2759:                         next;
 2760:                     }
 2761:                 } else {
 2762:                     next;
 2763:                 }
 2764:             }
 2765:         }
 2766:         if ($hidepriv) {
 2767:             if ($context eq 'userroles') {
 2768:                 if ((&privileged($username,$domain)) &&
 2769:                     (!$nothide{$username.':'.$domain})) {
 2770:                     next;
 2771:                 }
 2772:             } else {
 2773:                 unless (ref($privileged{$domain}) eq 'HASH') {
 2774:                     my %dompersonnel =
 2775:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 2776:                     $privileged{$domain} = {};
 2777:                     if (keys(%dompersonnel)) {
 2778:                         foreach my $server (keys(%dompersonnel)) {
 2779:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 2780:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 2781:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 2782:                                     $privileged{$udom}{$uname} = $trole;
 2783:                                 }
 2784:                             }
 2785:                         }
 2786:                     }
 2787:                 }
 2788:                 if (exists($privileged{$domain}{$username})) {
 2789:                     if (!$nothide{$username.':'.$domain}) {
 2790:                         next;
 2791:                     }
 2792:                 }
 2793:             }
 2794:         }
 2795:         if ($withsec) {
 2796:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2797:                 $tstart.':'.$tend;
 2798:         } else {
 2799:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2800:         }
 2801:     }
 2802:     return %returnhash;
 2803: }
 2804: 
 2805: # ----------------------------------------------------- Frontpage Announcements
 2806: #
 2807: #
 2808: 
 2809: sub postannounce {
 2810:     my ($server,$text)=@_;
 2811:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2812:     unless ($text=~/\w/) { $text=''; }
 2813:     return &reply('setannounce:'.&escape($text),$server);
 2814: }
 2815: 
 2816: sub getannounce {
 2817: 
 2818:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2819: 	my $announcement='';
 2820: 	while (my $line = <$fh>) { $announcement .= $line; }
 2821: 	close($fh);
 2822: 	if ($announcement=~/\w/) { 
 2823: 	    return 
 2824:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2825:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2826: 	} else {
 2827: 	    return '';
 2828: 	}
 2829:     } else {
 2830: 	return '';
 2831:     }
 2832: }
 2833: 
 2834: # ---------------------------------------------------------- Course ID routines
 2835: # Deal with domain's nohist_courseid.db files
 2836: #
 2837: 
 2838: sub courseidput {
 2839:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2840:     my $outcome;
 2841:     if ($caller eq 'timeonly') {
 2842:         my $cids = '';
 2843:         foreach my $item (keys(%$storehash)) {
 2844:             $cids.=&escape($item).'&';
 2845:         }
 2846:         $cids=~s/\&$//;
 2847:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 2848:                           $coursehome);       
 2849:     } else {
 2850:         my $items = '';
 2851:         foreach my $item (keys(%$storehash)) {
 2852:             $items.= &escape($item).'='.
 2853:                      &freeze_escape($$storehash{$item}).'&';
 2854:         }
 2855:         $items=~s/\&$//;
 2856:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 2857:                           $coursehome);
 2858:     }
 2859:     if ($outcome eq 'unknown_cmd') {
 2860:         my $what;
 2861:         foreach my $cid (keys(%$storehash)) {
 2862:             $what .= &escape($cid).'=';
 2863:             foreach my $item ('description','inst_code','owner','type') {
 2864:                 $what .= &escape($storehash->{$cid}{$item}).':';
 2865:             }
 2866:             $what =~ s/\:$/&/;
 2867:         }
 2868:         $what =~ s/\&$//;  
 2869:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2870:     } else {
 2871:         return $outcome;
 2872:     }
 2873: }
 2874: 
 2875: sub courseiddump {
 2876:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 2877:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 2878:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
 2879:     my $as_hash = 1;
 2880:     my %returnhash;
 2881:     if (!$domfilter) { $domfilter=''; }
 2882:     my %libserv = &all_library();
 2883:     foreach my $tryserver (keys(%libserv)) {
 2884:         if ( (  $hostidflag == 1 
 2885: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2886: 	     || (!defined($hostidflag)) ) {
 2887: 
 2888: 	    if (($domfilter eq '') ||
 2889: 		(&host_domain($tryserver) eq $domfilter)) {
 2890:                 my $rep = 
 2891:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 2892:                          $sincefilter.':'.&escape($descfilter).':'.
 2893:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 2894:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 2895:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 2896:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 2897:                          $showhidden.':'.$caller,$tryserver);
 2898:                 my @pairs=split(/\&/,$rep);
 2899:                 foreach my $item (@pairs) {
 2900:                     my ($key,$value)=split(/\=/,$item,2);
 2901:                     $key = &unescape($key);
 2902:                     next if ($key =~ /^error: 2 /);
 2903:                     my $result = &thaw_unescape($value);
 2904:                     if (ref($result) eq 'HASH') {
 2905:                         $returnhash{$key}=$result;
 2906:                     } else {
 2907:                         my @responses = split(/:/,$value);
 2908:                         my @items = ('description','inst_code','owner','type');
 2909:                         for (my $i=0; $i<@responses; $i++) {
 2910:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 2911:                         }
 2912:                     } 
 2913:                 }
 2914:             }
 2915:         }
 2916:     }
 2917:     return %returnhash;
 2918: }
 2919: 
 2920: # ---------------------------------------------------------- DC e-mail
 2921: 
 2922: sub dcmailput {
 2923:     my ($domain,$msgid,$message,$server)=@_;
 2924:     my $status = &Apache::lonnet::critical(
 2925:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2926:        &escape($message),$server);
 2927:     return $status;
 2928: }
 2929: 
 2930: sub dcmaildump {
 2931:     my ($dom,$startdate,$enddate,$senders) = @_;
 2932:     my %returnhash=();
 2933: 
 2934:     if (defined(&domain($dom,'primary'))) {
 2935:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2936:                                                          &escape($enddate).':';
 2937: 	my @esc_senders=map { &escape($_)} @$senders;
 2938: 	$cmd.=&escape(join('&',@esc_senders));
 2939: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2940:             my ($key,$value) = split(/\=/,$line,2);
 2941:             if (($key) && ($value)) {
 2942:                 $returnhash{&unescape($key)} = &unescape($value);
 2943:             }
 2944:         }
 2945:     }
 2946:     return %returnhash;
 2947: }
 2948: # ---------------------------------------------------------- Domain roles
 2949: 
 2950: sub get_domain_roles {
 2951:     my ($dom,$roles,$startdate,$enddate)=@_;
 2952:     if (undef($startdate) || $startdate eq '') {
 2953:         $startdate = '.';
 2954:     }
 2955:     if (undef($enddate) || $enddate eq '') {
 2956:         $enddate = '.';
 2957:     }
 2958:     my $rolelist;
 2959:     if (ref($roles) eq 'ARRAY') {
 2960:         $rolelist = join(':',@{$roles});
 2961:     }
 2962:     my %personnel = ();
 2963: 
 2964:     my %servers = &get_servers($dom,'library');
 2965:     foreach my $tryserver (keys(%servers)) {
 2966: 	%{$personnel{$tryserver}}=();
 2967: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2968: 					    &escape($startdate).':'.
 2969: 					    &escape($enddate).':'.
 2970: 					    &escape($rolelist), $tryserver))) {
 2971: 	    my ($key,$value) = split(/\=/,$line,2);
 2972: 	    if (($key) && ($value)) {
 2973: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2974: 	    }
 2975: 	}
 2976:     }
 2977:     return %personnel;
 2978: }
 2979: 
 2980: # ----------------------------------------------------------- Check out an item
 2981: 
 2982: sub get_first_access {
 2983:     my ($type,$argsymb)=@_;
 2984:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2985:     if ($argsymb) { $symb=$argsymb; }
 2986:     my ($map,$id,$res)=&decode_symb($symb);
 2987:     if ($type eq 'course') {
 2988: 	$res='course';
 2989:     } elsif ($type eq 'map') {
 2990: 	$res=&symbread($map);
 2991:     } else {
 2992: 	$res=$symb;
 2993:     }
 2994:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2995:     return $times{"$courseid\0$res"};
 2996: }
 2997: 
 2998: sub set_first_access {
 2999:     my ($type)=@_;
 3000:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3001:     my ($map,$id,$res)=&decode_symb($symb);
 3002:     if ($type eq 'course') {
 3003: 	$res='course';
 3004:     } elsif ($type eq 'map') {
 3005: 	$res=&symbread($map);
 3006:     } else {
 3007: 	$res=$symb;
 3008:     }
 3009:     my $firstaccess=&get_first_access($type,$symb);
 3010:     if (!$firstaccess) {
 3011: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 3012:     }
 3013:     return 'already_set';
 3014: }
 3015: 
 3016: sub checkout {
 3017:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 3018:     my $now=time;
 3019:     my $lonhost=$perlvar{'lonHostID'};
 3020:     my $infostr=&escape(
 3021:                  'CHECKOUTTOKEN&'.
 3022:                  $tuname.'&'.
 3023:                  $tudom.'&'.
 3024:                  $tcrsid.'&'.
 3025:                  $symb.'&'.
 3026: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 3027:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 3028:     if ($token=~/^error\:/) { 
 3029:         &logthis("<font color=\"blue\">WARNING: ".
 3030:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 3031:                  "</font>");
 3032:         return ''; 
 3033:     }
 3034: 
 3035:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 3036:     $token=~tr/a-z/A-Z/;
 3037: 
 3038:     my %infohash=('resource.0.outtoken' => $token,
 3039:                   'resource.0.checkouttime' => $now,
 3040:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 3041: 
 3042:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3043:        return '';
 3044:     } else {
 3045:         &logthis("<font color=\"blue\">WARNING: ".
 3046:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 3047:                  "</font>");
 3048:     }    
 3049: 
 3050:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3051:                          &escape('Checkout '.$infostr.' - '.
 3052:                                                  $token)) ne 'ok') {
 3053: 	return '';
 3054:     } else {
 3055:         &logthis("<font color=\"blue\">WARNING: ".
 3056:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 3057:                  "</font>");
 3058:     }
 3059:     return $token;
 3060: }
 3061: 
 3062: # ------------------------------------------------------------ Check in an item
 3063: 
 3064: sub checkin {
 3065:     my $token=shift;
 3066:     my $now=time;
 3067:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 3068:     $lonhost=~tr/A-Z/a-z/;
 3069:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 3070:     $dtoken=~s/\W/\_/g;
 3071:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 3072:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 3073: 
 3074:     unless (($tuname) && ($tudom)) {
 3075:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 3076:         return '';
 3077:     }
 3078:     
 3079:     unless (&allowed('mgr',$tcrsid)) {
 3080:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 3081:                  $env{'user.name'}.' - '.$env{'user.domain'});
 3082:         return '';
 3083:     }
 3084: 
 3085:     my %infohash=('resource.0.intoken' => $token,
 3086:                   'resource.0.checkintime' => $now,
 3087:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 3088: 
 3089:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3090:        return '';
 3091:     }    
 3092: 
 3093:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3094:                          &escape('Checkin - '.$token)) ne 'ok') {
 3095: 	return '';
 3096:     }
 3097: 
 3098:     return ($symb,$tuname,$tudom,$tcrsid);    
 3099: }
 3100: 
 3101: # --------------------------------------------- Set Expire Date for Spreadsheet
 3102: 
 3103: sub expirespread {
 3104:     my ($uname,$udom,$stype,$usymb)=@_;
 3105:     my $cid=$env{'request.course.id'}; 
 3106:     if ($cid) {
 3107:        my $now=time;
 3108:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3109:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3110:                             $env{'course.'.$cid.'.num'}.
 3111: 	        	    ':nohist_expirationdates:'.
 3112:                             &escape($key).'='.$now,
 3113:                             $env{'course.'.$cid.'.home'})
 3114:     }
 3115:     return 'ok';
 3116: }
 3117: 
 3118: # ----------------------------------------------------- Devalidate Spreadsheets
 3119: 
 3120: sub devalidate {
 3121:     my ($symb,$uname,$udom)=@_;
 3122:     my $cid=$env{'request.course.id'}; 
 3123:     if ($cid) {
 3124:         # delete the stored spreadsheets for
 3125:         # - the student level sheet of this user in course's homespace
 3126:         # - the assessment level sheet for this resource 
 3127:         #   for this user in user's homespace
 3128: 	# - current conditional state info
 3129: 	my $key=$uname.':'.$udom.':';
 3130:         my $status=
 3131: 	    &del('nohist_calculatedsheets',
 3132: 		 [$key.'studentcalc:'],
 3133: 		 $env{'course.'.$cid.'.domain'},
 3134: 		 $env{'course.'.$cid.'.num'})
 3135: 		.' '.
 3136: 	    &del('nohist_calculatedsheets_'.$cid,
 3137: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3138:         unless ($status eq 'ok ok') {
 3139:            &logthis('Could not devalidate spreadsheet '.
 3140:                     $uname.' at '.$udom.' for '.
 3141: 		    $symb.': '.$status);
 3142:         }
 3143: 	&delenv('user.state.'.$cid);
 3144:     }
 3145: }
 3146: 
 3147: sub get_scalar {
 3148:     my ($string,$end) = @_;
 3149:     my $value;
 3150:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3151: 	$value = $1;
 3152:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3153: 	$value = $1;
 3154:     }
 3155:     return &unescape($value);
 3156: }
 3157: 
 3158: sub array2str {
 3159:   my (@array) = @_;
 3160:   my $result=&arrayref2str(\@array);
 3161:   $result=~s/^__ARRAY_REF__//;
 3162:   $result=~s/__END_ARRAY_REF__$//;
 3163:   return $result;
 3164: }
 3165: 
 3166: sub arrayref2str {
 3167:   my ($arrayref) = @_;
 3168:   my $result='__ARRAY_REF__';
 3169:   foreach my $elem (@$arrayref) {
 3170:     if(ref($elem) eq 'ARRAY') {
 3171:       $result.=&arrayref2str($elem).'&';
 3172:     } elsif(ref($elem) eq 'HASH') {
 3173:       $result.=&hashref2str($elem).'&';
 3174:     } elsif(ref($elem)) {
 3175:       #print("Got a ref of ".(ref($elem))." skipping.");
 3176:     } else {
 3177:       $result.=&escape($elem).'&';
 3178:     }
 3179:   }
 3180:   $result=~s/\&$//;
 3181:   $result .= '__END_ARRAY_REF__';
 3182:   return $result;
 3183: }
 3184: 
 3185: sub hash2str {
 3186:   my (%hash) = @_;
 3187:   my $result=&hashref2str(\%hash);
 3188:   $result=~s/^__HASH_REF__//;
 3189:   $result=~s/__END_HASH_REF__$//;
 3190:   return $result;
 3191: }
 3192: 
 3193: sub hashref2str {
 3194:   my ($hashref)=@_;
 3195:   my $result='__HASH_REF__';
 3196:   foreach my $key (sort(keys(%$hashref))) {
 3197:     if (ref($key) eq 'ARRAY') {
 3198:       $result.=&arrayref2str($key).'=';
 3199:     } elsif (ref($key) eq 'HASH') {
 3200:       $result.=&hashref2str($key).'=';
 3201:     } elsif (ref($key)) {
 3202:       $result.='=';
 3203:       #print("Got a ref of ".(ref($key))." skipping.");
 3204:     } else {
 3205: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3206:     }
 3207: 
 3208:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3209:       $result.=&arrayref2str($hashref->{$key}).'&';
 3210:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3211:       $result.=&hashref2str($hashref->{$key}).'&';
 3212:     } elsif(ref($hashref->{$key})) {
 3213:        $result.='&';
 3214:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3215:     } else {
 3216:       $result.=&escape($hashref->{$key}).'&';
 3217:     }
 3218:   }
 3219:   $result=~s/\&$//;
 3220:   $result .= '__END_HASH_REF__';
 3221:   return $result;
 3222: }
 3223: 
 3224: sub str2hash {
 3225:     my ($string)=@_;
 3226:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3227:     return %$hash;
 3228: }
 3229: 
 3230: sub str2hashref {
 3231:   my ($string) = @_;
 3232: 
 3233:   my %hash;
 3234: 
 3235:   if($string !~ /^__HASH_REF__/) {
 3236:       if (! ($string eq '' || !defined($string))) {
 3237: 	  $hash{'error'}='Not hash reference';
 3238:       }
 3239:       return (\%hash, $string);
 3240:   }
 3241: 
 3242:   $string =~ s/^__HASH_REF__//;
 3243: 
 3244:   while($string !~ /^__END_HASH_REF__/) {
 3245:       #key
 3246:       my $key='';
 3247:       if($string =~ /^__HASH_REF__/) {
 3248:           ($key, $string)=&str2hashref($string);
 3249:           if(defined($key->{'error'})) {
 3250:               $hash{'error'}='Bad data';
 3251:               return (\%hash, $string);
 3252:           }
 3253:       } elsif($string =~ /^__ARRAY_REF__/) {
 3254:           ($key, $string)=&str2arrayref($string);
 3255:           if($key->[0] eq 'Array reference error') {
 3256:               $hash{'error'}='Bad data';
 3257:               return (\%hash, $string);
 3258:           }
 3259:       } else {
 3260:           $string =~ s/^(.*?)=//;
 3261: 	  $key=&unescape($1);
 3262:       }
 3263:       $string =~ s/^=//;
 3264: 
 3265:       #value
 3266:       my $value='';
 3267:       if($string =~ /^__HASH_REF__/) {
 3268:           ($value, $string)=&str2hashref($string);
 3269:           if(defined($value->{'error'})) {
 3270:               $hash{'error'}='Bad data';
 3271:               return (\%hash, $string);
 3272:           }
 3273:       } elsif($string =~ /^__ARRAY_REF__/) {
 3274:           ($value, $string)=&str2arrayref($string);
 3275:           if($value->[0] eq 'Array reference error') {
 3276:               $hash{'error'}='Bad data';
 3277:               return (\%hash, $string);
 3278:           }
 3279:       } else {
 3280: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3281:       }
 3282:       $string =~ s/^&//;
 3283: 
 3284:       $hash{$key}=$value;
 3285:   }
 3286: 
 3287:   $string =~ s/^__END_HASH_REF__//;
 3288: 
 3289:   return (\%hash, $string);
 3290: }
 3291: 
 3292: sub str2array {
 3293:     my ($string)=@_;
 3294:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3295:     return @$array;
 3296: }
 3297: 
 3298: sub str2arrayref {
 3299:   my ($string) = @_;
 3300:   my @array;
 3301: 
 3302:   if($string !~ /^__ARRAY_REF__/) {
 3303:       if (! ($string eq '' || !defined($string))) {
 3304: 	  $array[0]='Array reference error';
 3305:       }
 3306:       return (\@array, $string);
 3307:   }
 3308: 
 3309:   $string =~ s/^__ARRAY_REF__//;
 3310: 
 3311:   while($string !~ /^__END_ARRAY_REF__/) {
 3312:       my $value='';
 3313:       if($string =~ /^__HASH_REF__/) {
 3314:           ($value, $string)=&str2hashref($string);
 3315:           if(defined($value->{'error'})) {
 3316:               $array[0] ='Array reference error';
 3317:               return (\@array, $string);
 3318:           }
 3319:       } elsif($string =~ /^__ARRAY_REF__/) {
 3320:           ($value, $string)=&str2arrayref($string);
 3321:           if($value->[0] eq 'Array reference error') {
 3322:               $array[0] ='Array reference error';
 3323:               return (\@array, $string);
 3324:           }
 3325:       } else {
 3326: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3327:       }
 3328:       $string =~ s/^&//;
 3329: 
 3330:       push(@array, $value);
 3331:   }
 3332: 
 3333:   $string =~ s/^__END_ARRAY_REF__//;
 3334: 
 3335:   return (\@array, $string);
 3336: }
 3337: 
 3338: # -------------------------------------------------------------------Temp Store
 3339: 
 3340: sub tmpreset {
 3341:   my ($symb,$namespace,$domain,$stuname) = @_;
 3342:   if (!$symb) {
 3343:     $symb=&symbread();
 3344:     if (!$symb) { $symb= $env{'request.url'}; }
 3345:   }
 3346:   $symb=escape($symb);
 3347: 
 3348:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3349:   $namespace=~s/\//\_/g;
 3350:   $namespace=~s/\W//g;
 3351: 
 3352:   if (!$domain) { $domain=$env{'user.domain'}; }
 3353:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3354:   if ($domain eq 'public' && $stuname eq 'public') {
 3355:       $stuname=$ENV{'REMOTE_ADDR'};
 3356:   }
 3357:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3358:   my %hash;
 3359:   if (tie(%hash,'GDBM_File',
 3360: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3361: 	  &GDBM_WRCREAT(),0640)) {
 3362:     foreach my $key (keys %hash) {
 3363:       if ($key=~ /:$symb/) {
 3364: 	delete($hash{$key});
 3365:       }
 3366:     }
 3367:   }
 3368: }
 3369: 
 3370: sub tmpstore {
 3371:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3372: 
 3373:   if (!$symb) {
 3374:     $symb=&symbread();
 3375:     if (!$symb) { $symb= $env{'request.url'}; }
 3376:   }
 3377:   $symb=escape($symb);
 3378: 
 3379:   if (!$namespace) {
 3380:     # I don't think we would ever want to store this for a course.
 3381:     # it seems this will only be used if we don't have a course.
 3382:     #$namespace=$env{'request.course.id'};
 3383:     #if (!$namespace) {
 3384:       $namespace=$env{'request.state'};
 3385:     #}
 3386:   }
 3387:   $namespace=~s/\//\_/g;
 3388:   $namespace=~s/\W//g;
 3389:   if (!$domain) { $domain=$env{'user.domain'}; }
 3390:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3391:   if ($domain eq 'public' && $stuname eq 'public') {
 3392:       $stuname=$ENV{'REMOTE_ADDR'};
 3393:   }
 3394:   my $now=time;
 3395:   my %hash;
 3396:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3397:   if (tie(%hash,'GDBM_File',
 3398: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3399: 	  &GDBM_WRCREAT(),0640)) {
 3400:     $hash{"version:$symb"}++;
 3401:     my $version=$hash{"version:$symb"};
 3402:     my $allkeys=''; 
 3403:     foreach my $key (keys(%$storehash)) {
 3404:       $allkeys.=$key.':';
 3405:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3406:     }
 3407:     $hash{"$version:$symb:timestamp"}=$now;
 3408:     $allkeys.='timestamp';
 3409:     $hash{"$version:keys:$symb"}=$allkeys;
 3410:     if (untie(%hash)) {
 3411:       return 'ok';
 3412:     } else {
 3413:       return "error:$!";
 3414:     }
 3415:   } else {
 3416:     return "error:$!";
 3417:   }
 3418: }
 3419: 
 3420: # -----------------------------------------------------------------Temp Restore
 3421: 
 3422: sub tmprestore {
 3423:   my ($symb,$namespace,$domain,$stuname) = @_;
 3424: 
 3425:   if (!$symb) {
 3426:     $symb=&symbread();
 3427:     if (!$symb) { $symb= $env{'request.url'}; }
 3428:   }
 3429:   $symb=escape($symb);
 3430: 
 3431:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3432: 
 3433:   if (!$domain) { $domain=$env{'user.domain'}; }
 3434:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3435:   if ($domain eq 'public' && $stuname eq 'public') {
 3436:       $stuname=$ENV{'REMOTE_ADDR'};
 3437:   }
 3438:   my %returnhash;
 3439:   $namespace=~s/\//\_/g;
 3440:   $namespace=~s/\W//g;
 3441:   my %hash;
 3442:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3443:   if (tie(%hash,'GDBM_File',
 3444: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3445: 	  &GDBM_READER(),0640)) {
 3446:     my $version=$hash{"version:$symb"};
 3447:     $returnhash{'version'}=$version;
 3448:     my $scope;
 3449:     for ($scope=1;$scope<=$version;$scope++) {
 3450:       my $vkeys=$hash{"$scope:keys:$symb"};
 3451:       my @keys=split(/:/,$vkeys);
 3452:       my $key;
 3453:       $returnhash{"$scope:keys"}=$vkeys;
 3454:       foreach $key (@keys) {
 3455: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3456: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3457:       }
 3458:     }
 3459:     if (!(untie(%hash))) {
 3460:       return "error:$!";
 3461:     }
 3462:   } else {
 3463:     return "error:$!";
 3464:   }
 3465:   return %returnhash;
 3466: }
 3467: 
 3468: # ----------------------------------------------------------------------- Store
 3469: 
 3470: sub store {
 3471:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3472:     my $home='';
 3473: 
 3474:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3475: 
 3476:     $symb=&symbclean($symb);
 3477:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3478: 
 3479:     if (!$domain) { $domain=$env{'user.domain'}; }
 3480:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3481: 
 3482:     &devalidate($symb,$stuname,$domain);
 3483: 
 3484:     $symb=escape($symb);
 3485:     if (!$namespace) { 
 3486:        unless ($namespace=$env{'request.course.id'}) { 
 3487:           return ''; 
 3488:        } 
 3489:     }
 3490:     if (!$home) { $home=$env{'user.home'}; }
 3491: 
 3492:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3493:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3494: 
 3495:     my $namevalue='';
 3496:     foreach my $key (keys(%$storehash)) {
 3497:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3498:     }
 3499:     $namevalue=~s/\&$//;
 3500:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3501:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3502: }
 3503: 
 3504: # -------------------------------------------------------------- Critical Store
 3505: 
 3506: sub cstore {
 3507:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3508:     my $home='';
 3509: 
 3510:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3511: 
 3512:     $symb=&symbclean($symb);
 3513:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3514: 
 3515:     if (!$domain) { $domain=$env{'user.domain'}; }
 3516:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3517: 
 3518:     &devalidate($symb,$stuname,$domain);
 3519: 
 3520:     $symb=escape($symb);
 3521:     if (!$namespace) { 
 3522:        unless ($namespace=$env{'request.course.id'}) { 
 3523:           return ''; 
 3524:        } 
 3525:     }
 3526:     if (!$home) { $home=$env{'user.home'}; }
 3527: 
 3528:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3529:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3530: 
 3531:     my $namevalue='';
 3532:     foreach my $key (keys(%$storehash)) {
 3533:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3534:     }
 3535:     $namevalue=~s/\&$//;
 3536:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3537:     return critical
 3538:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3539: }
 3540: 
 3541: # --------------------------------------------------------------------- Restore
 3542: 
 3543: sub restore {
 3544:     my ($symb,$namespace,$domain,$stuname) = @_;
 3545:     my $home='';
 3546: 
 3547:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3548: 
 3549:     if (!$symb) {
 3550:       unless ($symb=escape(&symbread())) { return ''; }
 3551:     } else {
 3552:       $symb=&escape(&symbclean($symb));
 3553:     }
 3554:     if (!$namespace) { 
 3555:        unless ($namespace=$env{'request.course.id'}) { 
 3556:           return ''; 
 3557:        } 
 3558:     }
 3559:     if (!$domain) { $domain=$env{'user.domain'}; }
 3560:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3561:     if (!$home) { $home=$env{'user.home'}; }
 3562:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3563: 
 3564:     my %returnhash=();
 3565:     foreach my $line (split(/\&/,$answer)) {
 3566: 	my ($name,$value)=split(/\=/,$line);
 3567:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3568:     }
 3569:     my $version;
 3570:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3571:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3572:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3573:        }
 3574:     }
 3575:     return %returnhash;
 3576: }
 3577: 
 3578: # ---------------------------------------------------------- Course Description
 3579: 
 3580: sub coursedescription {
 3581:     my ($courseid,$args)=@_;
 3582:     $courseid=~s/^\///;
 3583:     $courseid=~s/\_/\//g;
 3584:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3585:     my $chome=&homeserver($cnum,$cdomain);
 3586:     my $normalid=$cdomain.'_'.$cnum;
 3587:     # need to always cache even if we get errors otherwise we keep 
 3588:     # trying and trying and trying to get the course description.
 3589:     my %envhash=();
 3590:     my %returnhash=();
 3591:     
 3592:     my $expiretime=600;
 3593:     if ($env{'request.course.id'} eq $normalid) {
 3594: 	$expiretime=120;
 3595:     }
 3596: 
 3597:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3598:     if (!$args->{'freshen_cache'}
 3599: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3600: 	foreach my $key (keys(%env)) {
 3601: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3602: 	    my ($setting) = $1;
 3603: 	    $returnhash{$setting} = $env{$key};
 3604: 	}
 3605: 	return %returnhash;
 3606:     }
 3607: 
 3608:     # get the data agin
 3609:     if (!$args->{'one_time'}) {
 3610: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3611:     }
 3612: 
 3613:     if ($chome ne 'no_host') {
 3614:        %returnhash=&dump('environment',$cdomain,$cnum);
 3615:        if (!exists($returnhash{'con_lost'})) {
 3616:            $returnhash{'home'}= $chome;
 3617: 	   $returnhash{'domain'} = $cdomain;
 3618: 	   $returnhash{'num'} = $cnum;
 3619:            if (!defined($returnhash{'type'})) {
 3620:                $returnhash{'type'} = 'Course';
 3621:            }
 3622:            while (my ($name,$value) = each %returnhash) {
 3623:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3624:            }
 3625:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3626:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3627: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3628:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3629:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3630:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3631:        }
 3632:     }
 3633:     if (!$args->{'one_time'}) {
 3634: 	&appenv(\%envhash);
 3635:     }
 3636:     return %returnhash;
 3637: }
 3638: 
 3639: # -------------------------------------------------See if a user is privileged
 3640: 
 3641: sub privileged {
 3642:     my ($username,$domain)=@_;
 3643:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3644: 			&homeserver($username,$domain));
 3645:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3646:     my $now=time;
 3647:     if ($rolesdump ne '') {
 3648:         foreach my $entry (split(/&/,$rolesdump)) {
 3649: 	    if ($entry!~/^rolesdef_/) {
 3650: 		my ($area,$role)=split(/=/,$entry);
 3651: 		$area=~s/\_\w\w$//;
 3652: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3653: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3654: 		    my $active=1;
 3655: 		    if ($tend) {
 3656: 			if ($tend<$now) { $active=0; }
 3657: 		    }
 3658: 		    if ($tstart) {
 3659: 			if ($tstart>$now) { $active=0; }
 3660: 		    }
 3661: 		    if ($active) { return 1; }
 3662: 		}
 3663: 	    }
 3664: 	}
 3665:     }
 3666:     return 0;
 3667: }
 3668: 
 3669: # -------------------------------------------------------- Get user privileges
 3670: 
 3671: sub rolesinit {
 3672:     my ($domain,$username,$authhost)=@_;
 3673:     my %userroles;
 3674:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3675:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
 3676:     my %allroles=();
 3677:     my %allgroups=();   
 3678:     my $now=time;
 3679:     %userroles = ('user.login.time' => $now);
 3680:     my $group_privs;
 3681: 
 3682:     if ($rolesdump ne '') {
 3683:         foreach my $entry (split(/&/,$rolesdump)) {
 3684: 	  if ($entry!~/^rolesdef_/) {
 3685:             my ($area,$role)=split(/=/,$entry);
 3686: 	    $area=~s/\_\w\w$//;
 3687:             my ($trole,$tend,$tstart,$group_privs);
 3688: 	    if ($role=~/^cr/) { 
 3689: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3690: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3691: 		    ($tend,$tstart)=split('_',$trest);
 3692: 		} else {
 3693: 		    $trole=$role;
 3694: 		}
 3695:             } elsif ($role =~ m|^gr/|) {
 3696:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3697:                 ($trole,$group_privs) = split(/\//,$trole);
 3698:                 $group_privs = &unescape($group_privs);
 3699: 	    } else {
 3700: 		($trole,$tend,$tstart)=split(/_/,$role);
 3701: 	    }
 3702: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3703: 					 $username);
 3704: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3705:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3706:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3707:             if (($area ne '') && ($trole ne '')) {
 3708: 		my $spec=$trole.'.'.$area;
 3709: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3710: 		if ($trole =~ /^cr\//) {
 3711:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3712:                 } elsif ($trole eq 'gr') {
 3713:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3714: 		} else {
 3715:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3716: 		}
 3717:             }
 3718:           }
 3719:         }
 3720:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3721:         $userroles{'user.adv'}    = $adv;
 3722: 	$userroles{'user.author'} = $author;
 3723:         $env{'user.adv'}=$adv;
 3724:     }
 3725:     return \%userroles;  
 3726: }
 3727: 
 3728: sub set_arearole {
 3729:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3730: # log the associated role with the area
 3731:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3732:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3733: }
 3734: 
 3735: sub custom_roleprivs {
 3736:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3737:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3738:     my $homsvr=homeserver($rauthor,$rdomain);
 3739:     if (&hostname($homsvr) ne '') {
 3740:         my ($rdummy,$roledef)=
 3741:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3742:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3743:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3744:             if (defined($syspriv)) {
 3745:                 $$allroles{'cm./'}.=':'.$syspriv;
 3746:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3747:             }
 3748:             if ($tdomain ne '') {
 3749:                 if (defined($dompriv)) {
 3750:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3751:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3752:                 }
 3753:                 if (($trest ne '') && (defined($coursepriv))) {
 3754:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3755:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3756:                 }
 3757:             }
 3758:         }
 3759:     }
 3760: }
 3761: 
 3762: sub group_roleprivs {
 3763:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3764:     my $access = 1;
 3765:     my $now = time;
 3766:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3767:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3768:     if ($access) {
 3769:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3770:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3771:     }
 3772: }
 3773: 
 3774: sub standard_roleprivs {
 3775:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3776:     if (defined($pr{$trole.':s'})) {
 3777:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3778:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3779:     }
 3780:     if ($tdomain ne '') {
 3781:         if (defined($pr{$trole.':d'})) {
 3782:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3783:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3784:         }
 3785:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3786:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3787:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3788:         }
 3789:     }
 3790: }
 3791: 
 3792: sub set_userprivs {
 3793:     my ($userroles,$allroles,$allgroups) = @_; 
 3794:     my $author=0;
 3795:     my $adv=0;
 3796:     my %grouproles = ();
 3797:     if (keys(%{$allgroups}) > 0) {
 3798:         foreach my $role (keys %{$allroles}) {
 3799:             my ($trole,$area,$sec,$extendedarea);
 3800:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3801:                 $trole = $1;
 3802:                 $area = $2;
 3803:                 $sec = $3;
 3804:                 $extendedarea = $area.$sec;
 3805:                 if (exists($$allgroups{$area})) {
 3806:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3807:                         my $spec = $trole.'.'.$extendedarea;
 3808:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3809:                                                 $$allgroups{$area}{$group};
 3810:                     }
 3811:                 }
 3812:             }
 3813:         }
 3814:     }
 3815:     foreach my $group (keys(%grouproles)) {
 3816:         $$allroles{$group} = $grouproles{$group};
 3817:     }
 3818:     foreach my $role (keys(%{$allroles})) {
 3819:         my %thesepriv;
 3820:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3821:         foreach my $item (split(/:/,$$allroles{$role})) {
 3822:             if ($item ne '') {
 3823:                 my ($privilege,$restrictions)=split(/&/,$item);
 3824:                 if ($restrictions eq '') {
 3825:                     $thesepriv{$privilege}='F';
 3826:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3827:                     $thesepriv{$privilege}.=$restrictions;
 3828:                 }
 3829:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3830:             }
 3831:         }
 3832:         my $thesestr='';
 3833:         foreach my $priv (keys(%thesepriv)) {
 3834: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3835: 	}
 3836:         $userroles->{'user.priv.'.$role} = $thesestr;
 3837:     }
 3838:     return ($author,$adv);
 3839: }
 3840: 
 3841: # --------------------------------------------------------------- get interface
 3842: 
 3843: sub get {
 3844:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3845:    my $items='';
 3846:    foreach my $item (@$storearr) {
 3847:        $items.=&escape($item).'&';
 3848:    }
 3849:    $items=~s/\&$//;
 3850:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3851:    if (!$uname) { $uname=$env{'user.name'}; }
 3852:    my $uhome=&homeserver($uname,$udomain);
 3853: 
 3854:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3855:    my @pairs=split(/\&/,$rep);
 3856:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3857:      return @pairs;
 3858:    }
 3859:    my %returnhash=();
 3860:    my $i=0;
 3861:    foreach my $item (@$storearr) {
 3862:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3863:       $i++;
 3864:    }
 3865:    return %returnhash;
 3866: }
 3867: 
 3868: # --------------------------------------------------------------- del interface
 3869: 
 3870: sub del {
 3871:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3872:    my $items='';
 3873:    foreach my $item (@$storearr) {
 3874:        $items.=&escape($item).'&';
 3875:    }
 3876:    $items=~s/\&$//;
 3877:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3878:    if (!$uname) { $uname=$env{'user.name'}; }
 3879:    my $uhome=&homeserver($uname,$udomain);
 3880: 
 3881:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3882: }
 3883: 
 3884: # -------------------------------------------------------------- dump interface
 3885: 
 3886: sub dump {
 3887:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3888:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3889:     if (!$uname) { $uname=$env{'user.name'}; }
 3890:     my $uhome=&homeserver($uname,$udomain);
 3891:     if ($regexp) {
 3892: 	$regexp=&escape($regexp);
 3893:     } else {
 3894: 	$regexp='.';
 3895:     }
 3896:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3897:     my @pairs=split(/\&/,$rep);
 3898:     my %returnhash=();
 3899:     foreach my $item (@pairs) {
 3900: 	my ($key,$value)=split(/=/,$item,2);
 3901: 	$key = &unescape($key);
 3902: 	next if ($key =~ /^error: 2 /);
 3903: 	$returnhash{$key}=&thaw_unescape($value);
 3904:     }
 3905:     return %returnhash;
 3906: }
 3907: 
 3908: # --------------------------------------------------------- dumpstore interface
 3909: 
 3910: sub dumpstore {
 3911:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3912:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3913:    if (!$uname) { $uname=$env{'user.name'}; }
 3914:    my $uhome=&homeserver($uname,$udomain);
 3915:    if ($regexp) {
 3916:        $regexp=&escape($regexp);
 3917:    } else {
 3918:        $regexp='.';
 3919:    }
 3920:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3921:    my @pairs=split(/\&/,$rep);
 3922:    my %returnhash=();
 3923:    foreach my $item (@pairs) {
 3924:        my ($key,$value)=split(/=/,$item,2);
 3925:        next if ($key =~ /^error: 2 /);
 3926:        $returnhash{$key}=&thaw_unescape($value);
 3927:    }
 3928:    return %returnhash;
 3929: }
 3930: 
 3931: # -------------------------------------------------------------- keys interface
 3932: 
 3933: sub getkeys {
 3934:    my ($namespace,$udomain,$uname)=@_;
 3935:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3936:    if (!$uname) { $uname=$env{'user.name'}; }
 3937:    my $uhome=&homeserver($uname,$udomain);
 3938:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3939:    my @keyarray=();
 3940:    foreach my $key (split(/\&/,$rep)) {
 3941:       next if ($key =~ /^error: 2 /);
 3942:       push(@keyarray,&unescape($key));
 3943:    }
 3944:    return @keyarray;
 3945: }
 3946: 
 3947: # --------------------------------------------------------------- currentdump
 3948: sub currentdump {
 3949:    my ($courseid,$sdom,$sname)=@_;
 3950:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3951:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3952:    $sname    = $env{'user.name'}         if (! defined($sname));
 3953:    my $uhome = &homeserver($sname,$sdom);
 3954:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3955:    return if ($rep =~ /^(error:|no_such_host)/);
 3956:    #
 3957:    my %returnhash=();
 3958:    #
 3959:    if ($rep eq "unknown_cmd") { 
 3960:        # an old lond will not know currentdump
 3961:        # Do a dump and make it look like a currentdump
 3962:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3963:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3964:        my %hash = @tmp;
 3965:        @tmp=();
 3966:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3967:    } else {
 3968:        my @pairs=split(/\&/,$rep);
 3969:        foreach my $pair (@pairs) {
 3970:            my ($key,$value)=split(/=/,$pair,2);
 3971:            my ($symb,$param) = split(/:/,$key);
 3972:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3973:                                                         &thaw_unescape($value);
 3974:        }
 3975:    }
 3976:    return %returnhash;
 3977: }
 3978: 
 3979: sub convert_dump_to_currentdump{
 3980:     my %hash = %{shift()};
 3981:     my %returnhash;
 3982:     # Code ripped from lond, essentially.  The only difference
 3983:     # here is the unescaping done by lonnet::dump().  Conceivably
 3984:     # we might run in to problems with parameter names =~ /^v\./
 3985:     while (my ($key,$value) = each(%hash)) {
 3986:         my ($v,$symb,$param) = split(/:/,$key);
 3987: 	$symb  = &unescape($symb);
 3988: 	$param = &unescape($param);
 3989:         next if ($v eq 'version' || $symb eq 'keys');
 3990:         next if (exists($returnhash{$symb}) &&
 3991:                  exists($returnhash{$symb}->{$param}) &&
 3992:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3993:         $returnhash{$symb}->{$param}=$value;
 3994:         $returnhash{$symb}->{'v.'.$param}=$v;
 3995:     }
 3996:     #
 3997:     # Remove all of the keys in the hashes which keep track of
 3998:     # the version of the parameter.
 3999:     while (my ($symb,$param_hash) = each(%returnhash)) {
 4000:         # use a foreach because we are going to delete from the hash.
 4001:         foreach my $key (keys(%$param_hash)) {
 4002:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 4003:         }
 4004:     }
 4005:     return \%returnhash;
 4006: }
 4007: 
 4008: # ------------------------------------------------------ critical inc interface
 4009: 
 4010: sub cinc {
 4011:     return &inc(@_,'critical');
 4012: }
 4013: 
 4014: # --------------------------------------------------------------- inc interface
 4015: 
 4016: sub inc {
 4017:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 4018:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4019:     if (!$uname) { $uname=$env{'user.name'}; }
 4020:     my $uhome=&homeserver($uname,$udomain);
 4021:     my $items='';
 4022:     if (! ref($store)) {
 4023:         # got a single value, so use that instead
 4024:         $items = &escape($store).'=&';
 4025:     } elsif (ref($store) eq 'SCALAR') {
 4026:         $items = &escape($$store).'=&';        
 4027:     } elsif (ref($store) eq 'ARRAY') {
 4028:         $items = join('=&',map {&escape($_);} @{$store});
 4029:     } elsif (ref($store) eq 'HASH') {
 4030:         while (my($key,$value) = each(%{$store})) {
 4031:             $items.= &escape($key).'='.&escape($value).'&';
 4032:         }
 4033:     }
 4034:     $items=~s/\&$//;
 4035:     if ($critical) {
 4036: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 4037:     } else {
 4038: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 4039:     }
 4040: }
 4041: 
 4042: # --------------------------------------------------------------- put interface
 4043: 
 4044: sub put {
 4045:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4046:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4047:    if (!$uname) { $uname=$env{'user.name'}; }
 4048:    my $uhome=&homeserver($uname,$udomain);
 4049:    my $items='';
 4050:    foreach my $item (keys(%$storehash)) {
 4051:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4052:    }
 4053:    $items=~s/\&$//;
 4054:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4055: }
 4056: 
 4057: # ------------------------------------------------------------ newput interface
 4058: 
 4059: sub newput {
 4060:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4061:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4062:    if (!$uname) { $uname=$env{'user.name'}; }
 4063:    my $uhome=&homeserver($uname,$udomain);
 4064:    my $items='';
 4065:    foreach my $key (keys(%$storehash)) {
 4066:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4067:    }
 4068:    $items=~s/\&$//;
 4069:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 4070: }
 4071: 
 4072: # ---------------------------------------------------------  putstore interface
 4073: 
 4074: sub putstore {
 4075:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4076:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4077:    if (!$uname) { $uname=$env{'user.name'}; }
 4078:    my $uhome=&homeserver($uname,$udomain);
 4079:    my $items='';
 4080:    foreach my $key (keys(%$storehash)) {
 4081:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 4082:    }
 4083:    $items=~s/\&$//;
 4084:    my $esc_symb=&escape($symb);
 4085:    my $esc_v=&escape($version);
 4086:    my $reply =
 4087:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 4088: 	      $uhome);
 4089:    if ($reply eq 'unknown_cmd') {
 4090:        # gfall back to way things use to be done
 4091:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 4092: 			    $uname);
 4093:    }
 4094:    return $reply;
 4095: }
 4096: 
 4097: sub old_putstore {
 4098:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4099:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4100:     if (!$uname) { $uname=$env{'user.name'}; }
 4101:     my $uhome=&homeserver($uname,$udomain);
 4102:     my %newstorehash;
 4103:     foreach my $item (keys(%$storehash)) {
 4104: 	my $key = $version.':'.&escape($symb).':'.$item;
 4105: 	$newstorehash{$key} = $storehash->{$item};
 4106:     }
 4107:     my $items='';
 4108:     my %allitems = ();
 4109:     foreach my $item (keys(%newstorehash)) {
 4110: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 4111: 	    my $key = $1.':keys:'.$2;
 4112: 	    $allitems{$key} .= $3.':';
 4113: 	}
 4114: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 4115:     }
 4116:     foreach my $item (keys(%allitems)) {
 4117: 	$allitems{$item} =~ s/\:$//;
 4118: 	$items.= $item.'='.$allitems{$item}.'&';
 4119:     }
 4120:     $items=~s/\&$//;
 4121:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4122: }
 4123: 
 4124: # ------------------------------------------------------ critical put interface
 4125: 
 4126: sub cput {
 4127:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4128:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4129:    if (!$uname) { $uname=$env{'user.name'}; }
 4130:    my $uhome=&homeserver($uname,$udomain);
 4131:    my $items='';
 4132:    foreach my $item (keys(%$storehash)) {
 4133:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4134:    }
 4135:    $items=~s/\&$//;
 4136:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 4137: }
 4138: 
 4139: # -------------------------------------------------------------- eget interface
 4140: 
 4141: sub eget {
 4142:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4143:    my $items='';
 4144:    foreach my $item (@$storearr) {
 4145:        $items.=&escape($item).'&';
 4146:    }
 4147:    $items=~s/\&$//;
 4148:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4149:    if (!$uname) { $uname=$env{'user.name'}; }
 4150:    my $uhome=&homeserver($uname,$udomain);
 4151:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 4152:    my @pairs=split(/\&/,$rep);
 4153:    my %returnhash=();
 4154:    my $i=0;
 4155:    foreach my $item (@$storearr) {
 4156:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4157:       $i++;
 4158:    }
 4159:    return %returnhash;
 4160: }
 4161: 
 4162: # ------------------------------------------------------------ tmpput interface
 4163: sub tmpput {
 4164:     my ($storehash,$server,$context)=@_;
 4165:     my $items='';
 4166:     foreach my $item (keys(%$storehash)) {
 4167: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4168:     }
 4169:     $items=~s/\&$//;
 4170:     if (defined($context)) {
 4171:         $items .= ':'.&escape($context);
 4172:     }
 4173:     return &reply("tmpput:$items",$server);
 4174: }
 4175: 
 4176: # ------------------------------------------------------------ tmpget interface
 4177: sub tmpget {
 4178:     my ($token,$server)=@_;
 4179:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4180:     my $rep=&reply("tmpget:$token",$server);
 4181:     my %returnhash;
 4182:     foreach my $item (split(/\&/,$rep)) {
 4183: 	my ($key,$value)=split(/=/,$item);
 4184:         next if ($key =~ /^error: 2 /);
 4185: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 4186:     }
 4187:     return %returnhash;
 4188: }
 4189: 
 4190: # ------------------------------------------------------------ tmpget interface
 4191: sub tmpdel {
 4192:     my ($token,$server)=@_;
 4193:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4194:     return &reply("tmpdel:$token",$server);
 4195: }
 4196: 
 4197: # -------------------------------------------------- portfolio access checking
 4198: 
 4199: sub portfolio_access {
 4200:     my ($requrl) = @_;
 4201:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4202:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4203:     if ($result) {
 4204:         my %setters;
 4205:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4206:             my ($startblock,$endblock) =
 4207:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4208:             if ($startblock && $endblock) {
 4209:                 return 'B';
 4210:             }
 4211:         } else {
 4212:             my ($startblock,$endblock) =
 4213:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4214:             if ($startblock && $endblock) {
 4215:                 return 'B';
 4216:             }
 4217:         }
 4218:     }
 4219:     if ($result eq 'ok') {
 4220:        return 'F';
 4221:     } elsif ($result =~ /^[^:]+:guest_/) {
 4222:        return 'A';
 4223:     }
 4224:     return '';
 4225: }
 4226: 
 4227: sub get_portfolio_access {
 4228:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4229: 
 4230:     if (!ref($access_hash)) {
 4231: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4232: 	my %access_controls = &get_access_controls($current_perms,$group,
 4233: 						   $file_name);
 4234: 	$access_hash = $access_controls{$file_name};
 4235:     }
 4236: 
 4237:     my ($public,$guest,@domains,@users,@courses,@groups);
 4238:     my $now = time;
 4239:     if (ref($access_hash) eq 'HASH') {
 4240:         foreach my $key (keys(%{$access_hash})) {
 4241:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4242:             if ($start > $now) {
 4243:                 next;
 4244:             }
 4245:             if ($end && $end<$now) {
 4246:                 next;
 4247:             }
 4248:             if ($scope eq 'public') {
 4249:                 $public = $key;
 4250:                 last;
 4251:             } elsif ($scope eq 'guest') {
 4252:                 $guest = $key;
 4253:             } elsif ($scope eq 'domains') {
 4254:                 push(@domains,$key);
 4255:             } elsif ($scope eq 'users') {
 4256:                 push(@users,$key);
 4257:             } elsif ($scope eq 'course') {
 4258:                 push(@courses,$key);
 4259:             } elsif ($scope eq 'group') {
 4260:                 push(@groups,$key);
 4261:             }
 4262:         }
 4263:         if ($public) {
 4264:             return 'ok';
 4265:         }
 4266:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4267:             if ($guest) {
 4268:                 return $guest;
 4269:             }
 4270:         } else {
 4271:             if (@domains > 0) {
 4272:                 foreach my $domkey (@domains) {
 4273:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4274:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4275:                             return 'ok';
 4276:                         }
 4277:                     }
 4278:                 }
 4279:             }
 4280:             if (@users > 0) {
 4281:                 foreach my $userkey (@users) {
 4282:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4283:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4284:                             if (ref($item) eq 'HASH') {
 4285:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4286:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4287:                                     return 'ok';
 4288:                                 }
 4289:                             }
 4290:                         }
 4291:                     } 
 4292:                 }
 4293:             }
 4294:             my %roleshash;
 4295:             my @courses_and_groups = @courses;
 4296:             push(@courses_and_groups,@groups); 
 4297:             if (@courses_and_groups > 0) {
 4298:                 my (%allgroups,%allroles); 
 4299:                 my ($start,$end,$role,$sec,$group);
 4300:                 foreach my $envkey (%env) {
 4301:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4302:                         my $cid = $2.'_'.$3; 
 4303:                         if ($1 eq 'gr') {
 4304:                             $group = $4;
 4305:                             $allgroups{$cid}{$group} = $env{$envkey};
 4306:                         } else {
 4307:                             if ($4 eq '') {
 4308:                                 $sec = 'none';
 4309:                             } else {
 4310:                                 $sec = $4;
 4311:                             }
 4312:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4313:                         }
 4314:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4315:                         my $cid = $2.'_'.$3;
 4316:                         if ($4 eq '') {
 4317:                             $sec = 'none';
 4318:                         } else {
 4319:                             $sec = $4;
 4320:                         }
 4321:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4322:                     }
 4323:                 }
 4324:                 if (keys(%allroles) == 0) {
 4325:                     return;
 4326:                 }
 4327:                 foreach my $key (@courses_and_groups) {
 4328:                     my %content = %{$$access_hash{$key}};
 4329:                     my $cnum = $content{'number'};
 4330:                     my $cdom = $content{'domain'};
 4331:                     my $cid = $cdom.'_'.$cnum;
 4332:                     if (!exists($allroles{$cid})) {
 4333:                         next;
 4334:                     }    
 4335:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4336:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4337:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4338:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4339:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4340:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4341:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4342:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4343:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4344:                                         if (grep/^all$/,@sections) {
 4345:                                             return 'ok';
 4346:                                         } else {
 4347:                                             if (grep/^$sec$/,@sections) {
 4348:                                                 return 'ok';
 4349:                                             }
 4350:                                         }
 4351:                                     }
 4352:                                 }
 4353:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4354:                                     if (grep/^none$/,@groups) {
 4355:                                         return 'ok';
 4356:                                     }
 4357:                                 } else {
 4358:                                     if (grep/^all$/,@groups) {
 4359:                                         return 'ok';
 4360:                                     } 
 4361:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4362:                                         if (grep/^$group$/,@groups) {
 4363:                                             return 'ok';
 4364:                                         }
 4365:                                     }
 4366:                                 } 
 4367:                             }
 4368:                         }
 4369:                     }
 4370:                 }
 4371:             }
 4372:             if ($guest) {
 4373:                 return $guest;
 4374:             }
 4375:         }
 4376:     }
 4377:     return;
 4378: }
 4379: 
 4380: sub course_group_datechecker {
 4381:     my ($dates,$now,$status) = @_;
 4382:     my ($start,$end) = split(/\./,$dates);
 4383:     if (!$start && !$end) {
 4384:         return 'ok';
 4385:     }
 4386:     if (grep/^active$/,@{$status}) {
 4387:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4388:             return 'ok';
 4389:         }
 4390:     }
 4391:     if (grep/^previous$/,@{$status}) {
 4392:         if ($end > $now ) {
 4393:             return 'ok';
 4394:         }
 4395:     }
 4396:     if (grep/^future$/,@{$status}) {
 4397:         if ($start > $now) {
 4398:             return 'ok';
 4399:         }
 4400:     }
 4401:     return; 
 4402: }
 4403: 
 4404: sub parse_portfolio_url {
 4405:     my ($url) = @_;
 4406: 
 4407:     my ($type,$udom,$unum,$group,$file_name);
 4408:     
 4409:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4410: 	$type = 1;
 4411:         $udom = $1;
 4412:         $unum = $2;
 4413:         $file_name = $3;
 4414:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4415: 	$type = 2;
 4416:         $udom = $1;
 4417:         $unum = $2;
 4418:         $group = $3;
 4419:         $file_name = $3.'/'.$4;
 4420:     }
 4421:     if (wantarray) {
 4422: 	return ($type,$udom,$unum,$file_name,$group);
 4423:     }
 4424:     return $type;
 4425: }
 4426: 
 4427: sub is_portfolio_url {
 4428:     my ($url) = @_;
 4429:     return scalar(&parse_portfolio_url($url));
 4430: }
 4431: 
 4432: sub is_portfolio_file {
 4433:     my ($file) = @_;
 4434:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4435:         return 1;
 4436:     }
 4437:     return;
 4438: }
 4439: 
 4440: sub usertools_access {
 4441:     my ($uname,$udom,$tool,$action) = @_;
 4442:     my $access;
 4443:     my %tools = (
 4444:                   aboutme   => 1,
 4445:                   blog      => 1,
 4446:                   portfolio => 1,
 4447:                 );
 4448:     return if (!defined($tools{$tool}));
 4449: 
 4450:     if ((!defined($udom)) || (!defined($uname))) {
 4451:         $udom = $env{'user.domain'};
 4452:         $uname = $env{'user.name'};
 4453:     }
 4454: 
 4455:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4456:         if ($action ne 'reload') {
 4457:             return $env{'environment.availabletools.'.$tool};
 4458:         }
 4459:     }
 4460: 
 4461:     my ($toolstatus,$inststatus);
 4462: 
 4463:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4464:         $toolstatus = $env{'environment.tools.'.$tool};
 4465:         $inststatus = $env{'environment.inststatus'};
 4466:     } else {
 4467:         my %userenv = &userenvironment($udom,$uname,'tools.'.$tool);
 4468:         $toolstatus = $userenv{'tools.'.$tool};
 4469:         $inststatus = $userenv{'inststatus'};
 4470:     }
 4471: 
 4472:     if ($toolstatus ne '') {
 4473:         if ($toolstatus) {
 4474:             $access = 1;
 4475:         } else {
 4476:             $access = 0;
 4477:         }
 4478:         return $access;
 4479:     }
 4480: 
 4481:     my $is_adv = &is_advanced_user($udom,$uname);
 4482:     my %domdef = &get_domain_defaults($udom);
 4483:     if (ref($domdef{$tool}) eq 'HASH') {
 4484:         if ($is_adv) {
 4485:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 4486:                 if ($domdef{$tool}{'_LC_adv'}) { 
 4487:                     $access = 1;
 4488:                 } else {
 4489:                     $access = 0;
 4490:                 }
 4491:                 return $access;
 4492:             }
 4493:         }
 4494:         if ($inststatus ne '') {
 4495:             my ($hasaccess,$hasnoaccess);
 4496:             foreach my $affiliation (split(/:/,$inststatus)) {
 4497:                 if ($domdef{$tool}{$affiliation} ne '') { 
 4498:                     if ($domdef{$tool}{$affiliation}) {
 4499:                         $hasaccess = 1;
 4500:                     } else {
 4501:                         $hasnoaccess = 1;
 4502:                     }
 4503:                 }
 4504:             }
 4505:             if ($hasaccess || $hasnoaccess) {
 4506:                 if ($hasaccess) {
 4507:                     $access = 1;
 4508:                 } elsif ($hasnoaccess) {
 4509:                     $access = 0; 
 4510:                 }
 4511:                 return $access;
 4512:             }
 4513:         } else {
 4514:             if ($domdef{$tool}{'default'} ne '') {
 4515:                 if ($domdef{$tool}{'default'}) {
 4516:                     $access = 1;
 4517:                 } elsif ($domdef{$tool}{'default'} == 0) {
 4518:                     $access = 0;
 4519:                 }
 4520:                 return $access;
 4521:             }
 4522:         }
 4523:     } else {
 4524:         $access = 1;
 4525:         return $access;
 4526:     }
 4527: }
 4528: 
 4529: sub is_advanced_user {
 4530:     my ($udom,$uname) = @_;
 4531:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 4532:     my %allroles;
 4533:     my $is_adv;
 4534:     foreach my $role (keys(%roleshash)) {
 4535:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 4536:         my $area = '/'.$tdomain.'/'.$trest;
 4537:         if ($sec ne '') {
 4538:             $area .= '/'.$sec;
 4539:         }
 4540:         if (($area ne '') && ($trole ne '')) {
 4541:             my $spec=$trole.'.'.$area;
 4542:             if ($trole =~ /^cr\//) {
 4543:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4544:             } elsif ($trole ne 'gr') {
 4545:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4546:             }
 4547:         }
 4548:     }
 4549:     foreach my $role (keys(%allroles)) {
 4550:         last if ($is_adv);
 4551:         foreach my $item (split(/:/,$allroles{$role})) {
 4552:             if ($item ne '') {
 4553:                 my ($privilege,$restrictions)=split(/&/,$item);
 4554:                 if ($privilege eq 'adv') {
 4555:                     $is_adv = 1;
 4556:                     last;
 4557:                 }
 4558:             }
 4559:         }
 4560:     }
 4561:     return $is_adv;
 4562: }
 4563: 
 4564: # ---------------------------------------------- Custom access rule evaluation
 4565: 
 4566: sub customaccess {
 4567:     my ($priv,$uri)=@_;
 4568:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4569:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4570:     $udom = &LONCAPA::clean_domain($udom);
 4571:     $ucrs = &LONCAPA::clean_username($ucrs);
 4572:     my $access=0;
 4573:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4574: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4575: 	if ($type eq 'user') {
 4576: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4577: 		my ($tdom,$tuname)=split(m{/},$scope);
 4578: 		if ($tdom) {
 4579: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4580: 		}
 4581: 		if ($tuname) {
 4582: 		    if ($tuname ne $env{'user.name'}) { next; }
 4583: 		}
 4584: 		$access=($effect eq 'allow');
 4585: 		last;
 4586: 	    }
 4587: 	} else {
 4588: 	    if ($role) {
 4589: 		if ($role ne $urole) { next; }
 4590: 	    }
 4591: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4592: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4593: 		if ($tdom) {
 4594: 		    if ($tdom ne $udom) { next; }
 4595: 		}
 4596: 		if ($tcrs) {
 4597: 		    if ($tcrs ne $ucrs) { next; }
 4598: 		}
 4599: 		if ($tsec) {
 4600: 		    if ($tsec ne $usec) { next; }
 4601: 		}
 4602: 		$access=($effect eq 'allow');
 4603: 		last;
 4604: 	    }
 4605: 	    if ($realm eq '' && $role eq '') {
 4606: 		$access=($effect eq 'allow');
 4607: 	    }
 4608: 	}
 4609:     }
 4610:     return $access;
 4611: }
 4612: 
 4613: # ------------------------------------------------- Check for a user privilege
 4614: 
 4615: sub allowed {
 4616:     my ($priv,$uri,$symb,$role)=@_;
 4617:     my $ver_orguri=$uri;
 4618:     $uri=&deversion($uri);
 4619:     my $orguri=$uri;
 4620:     $uri=&declutter($uri);
 4621: 
 4622:     if ($priv eq 'evb') {
 4623: # Evade communication block restrictions for specified role in a course
 4624:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4625:             return $1;
 4626:         } else {
 4627:             return;
 4628:         }
 4629:     }
 4630: 
 4631:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4632: # Free bre access to adm and meta resources
 4633:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4634: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4635: 	&& ($priv eq 'bre')) {
 4636: 	return 'F';
 4637:     }
 4638: 
 4639: # Free bre access to user's own portfolio contents
 4640:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4641:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4642: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4643:         my %setters;
 4644:         my ($startblock,$endblock) = 
 4645:             &Apache::loncommon::blockcheck(\%setters,'port');
 4646:         if ($startblock && $endblock) {
 4647:             return 'B';
 4648:         } else {
 4649:             return 'F';
 4650:         }
 4651:     }
 4652: 
 4653: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4654:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4655:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4656:         if (exists($env{'request.course.id'})) {
 4657:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4658:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4659:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4660:                 my $courseprivid=$env{'request.course.id'};
 4661:                 $courseprivid=~s/\_/\//;
 4662:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4663:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4664:                     return $1; 
 4665:                 } else {
 4666:                     if ($env{'request.course.sec'}) {
 4667:                         $courseprivid.='/'.$env{'request.course.sec'};
 4668:                     }
 4669:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4670:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4671:                         return $2;
 4672:                     }
 4673:                 }
 4674:             }
 4675:         }
 4676:     }
 4677: 
 4678: # Free bre to public access
 4679: 
 4680:     if ($priv eq 'bre') {
 4681:         my $copyright=&metadata($uri,'copyright');
 4682: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4683:            return 'F'; 
 4684:         }
 4685:         if ($copyright eq 'priv') {
 4686:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4687: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4688: 		return '';
 4689:             }
 4690:         }
 4691:         if ($copyright eq 'domain') {
 4692:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4693: 	    unless (($env{'user.domain'} eq $1) ||
 4694:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4695: 		return '';
 4696:             }
 4697:         }
 4698:         if ($env{'request.role'}=~ /li\.\//) {
 4699:             # Library role, so allow browsing of resources in this domain.
 4700:             return 'F';
 4701:         }
 4702:         if ($copyright eq 'custom') {
 4703: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4704:         }
 4705:     }
 4706:     # Domain coordinator is trying to create a course
 4707:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4708:         # uri is the requested domain in this case.
 4709:         # comparison to 'request.role.domain' shows if the user has selected
 4710:         # a role of dc for the domain in question.
 4711:         return 'F' if ($uri eq $env{'request.role.domain'});
 4712:     }
 4713: 
 4714:     my $thisallowed='';
 4715:     my $statecond=0;
 4716:     my $courseprivid='';
 4717: 
 4718: # Course
 4719: 
 4720:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4721:        $thisallowed.=$1;
 4722:     }
 4723: 
 4724: # Domain
 4725: 
 4726:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4727:        =~/\Q$priv\E\&([^\:]*)/) {
 4728:        $thisallowed.=$1;
 4729:     }
 4730: 
 4731: # Course: uri itself is a course
 4732:     my $courseuri=$uri;
 4733:     $courseuri=~s/\_(\d)/\/$1/;
 4734:     $courseuri=~s/^([^\/])/\/$1/;
 4735: 
 4736:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 4737:        =~/\Q$priv\E\&([^\:]*)/) {
 4738:        $thisallowed.=$1;
 4739:     }
 4740: 
 4741: # URI is an uploaded document for this course, default permissions don't matter
 4742: # not allowing 'edit' access (editupload) to uploaded course docs
 4743:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 4744: 	$thisallowed='';
 4745:         my ($match)=&is_on_map($uri);
 4746:         if ($match) {
 4747:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 4748:                   =~/\Q$priv\E\&([^\:]*)/) {
 4749:                 $thisallowed.=$1;
 4750:             }
 4751:         } else {
 4752:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 4753:             if ($refuri) {
 4754:                 if ($refuri =~ m|^/adm/|) {
 4755:                     $thisallowed='F';
 4756:                 } else {
 4757:                     $refuri=&declutter($refuri);
 4758:                     my ($match) = &is_on_map($refuri);
 4759:                     if ($match) {
 4760:                         $thisallowed='F';
 4761:                     }
 4762:                 }
 4763:             }
 4764:         }
 4765:     }
 4766: 
 4767:     if ($priv eq 'bre'
 4768: 	&& $thisallowed ne 'F' 
 4769: 	&& $thisallowed ne '2'
 4770: 	&& &is_portfolio_url($uri)) {
 4771: 	$thisallowed = &portfolio_access($uri);
 4772:     }
 4773:     
 4774: # Full access at system, domain or course-wide level? Exit.
 4775:     if ($thisallowed=~/F/) {
 4776: 	return 'F';
 4777:     }
 4778: 
 4779: # If this is generating or modifying users, exit with special codes
 4780: 
 4781:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4782: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4783: 	    my ($audom,$auname)=split('/',$uri);
 4784: # no author name given, so this just checks on the general right to make a co-author in this domain
 4785: 	    unless ($auname) { return $thisallowed; }
 4786: # an author name is given, so we are about to actually make a co-author for a certain account
 4787: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4788: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 4789: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 4790: 	}
 4791: 	return $thisallowed;
 4792:     }
 4793: #
 4794: # Gathered so far: system, domain and course wide privileges
 4795: #
 4796: # Course: See if uri or referer is an individual resource that is part of 
 4797: # the course
 4798: 
 4799:     if ($env{'request.course.id'}) {
 4800: 
 4801:        $courseprivid=$env{'request.course.id'};
 4802:        if ($env{'request.course.sec'}) {
 4803:           $courseprivid.='/'.$env{'request.course.sec'};
 4804:        }
 4805:        $courseprivid=~s/\_/\//;
 4806:        my $checkreferer=1;
 4807:        my ($match,$cond)=&is_on_map($uri);
 4808:        if ($match) {
 4809:            $statecond=$cond;
 4810:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4811:                =~/\Q$priv\E\&([^\:]*)/) {
 4812:                $thisallowed.=$1;
 4813:                $checkreferer=0;
 4814:            }
 4815:        }
 4816:        
 4817:        if ($checkreferer) {
 4818: 	  my $refuri=$env{'httpref.'.$orguri};
 4819:             unless ($refuri) {
 4820:                 foreach my $key (keys(%env)) {
 4821: 		    if ($key=~/^httpref\..*\*/) {
 4822: 			my $pattern=$key;
 4823:                         $pattern=~s/^httpref\.\/res\///;
 4824:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4825:                         $pattern=~s/\//\\\//g;
 4826:                         if ($orguri=~/$pattern/) {
 4827: 			    $refuri=$env{$key};
 4828:                         }
 4829:                     }
 4830:                 }
 4831:             }
 4832: 
 4833:          if ($refuri) { 
 4834: 	  $refuri=&declutter($refuri);
 4835:           my ($match,$cond)=&is_on_map($refuri);
 4836:             if ($match) {
 4837:               my $refstatecond=$cond;
 4838:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4839:                   =~/\Q$priv\E\&([^\:]*)/) {
 4840:                   $thisallowed.=$1;
 4841:                   $uri=$refuri;
 4842:                   $statecond=$refstatecond;
 4843:               }
 4844:           }
 4845:         }
 4846:        }
 4847:    }
 4848: 
 4849: #
 4850: # Gathered now: all privileges that could apply, and condition number
 4851: # 
 4852: #
 4853: # Full or no access?
 4854: #
 4855: 
 4856:     if ($thisallowed=~/F/) {
 4857: 	return 'F';
 4858:     }
 4859: 
 4860:     unless ($thisallowed) {
 4861:         return '';
 4862:     }
 4863: 
 4864: # Restrictions exist, deal with them
 4865: #
 4866: #   C:according to course preferences
 4867: #   R:according to resource settings
 4868: #   L:unless locked
 4869: #   X:according to user session state
 4870: #
 4871: 
 4872: # Possibly locked functionality, check all courses
 4873: # Locks might take effect only after 10 minutes cache expiration for other
 4874: # courses, and 2 minutes for current course
 4875: 
 4876:     my $envkey;
 4877:     if ($thisallowed=~/L/) {
 4878:         foreach $envkey (keys %env) {
 4879:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 4880:                my $courseid=$2;
 4881:                my $roleid=$1.'.'.$2;
 4882:                $courseid=~s/^\///;
 4883:                my $expiretime=600;
 4884:                if ($env{'request.role'} eq $roleid) {
 4885: 		  $expiretime=120;
 4886:                }
 4887: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 4888:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 4889:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 4890: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 4891:                }
 4892:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4893:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4894: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4895:                        &log($env{'user.domain'},$env{'user.name'},
 4896:                             $env{'user.home'},
 4897:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4898:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4899:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4900: 		       return '';
 4901:                    }
 4902:                }
 4903:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4904:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4905: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4906:                        &log($env{'user.domain'},$env{'user.name'},
 4907:                             $env{'user.home'},
 4908:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4909:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4910:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4911: 		       return '';
 4912:                    }
 4913:                }
 4914: 	   }
 4915:        }
 4916:     }
 4917:    
 4918: #
 4919: # Rest of the restrictions depend on selected course
 4920: #
 4921: 
 4922:     unless ($env{'request.course.id'}) {
 4923: 	if ($thisallowed eq 'A') {
 4924: 	    return 'A';
 4925:         } elsif ($thisallowed eq 'B') {
 4926:             return 'B';
 4927: 	} else {
 4928: 	    return '1';
 4929: 	}
 4930:     }
 4931: 
 4932: #
 4933: # Now user is definitely in a course
 4934: #
 4935: 
 4936: 
 4937: # Course preferences
 4938: 
 4939:    if ($thisallowed=~/C/) {
 4940:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4941:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4942:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4943: 	   =~/\Q$rolecode\E/) {
 4944: 	   if ($priv ne 'pch') { 
 4945: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4946: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4947: 			$env{'request.course.id'});
 4948: 	   }
 4949:            return '';
 4950:        }
 4951: 
 4952:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4953: 	   =~/\Q$unamedom\E/) {
 4954: 	   if ($priv ne 'pch') { 
 4955: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4956: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4957: 			$env{'request.course.id'});
 4958: 	   }
 4959:            return '';
 4960:        }
 4961:    }
 4962: 
 4963: # Resource preferences
 4964: 
 4965:    if ($thisallowed=~/R/) {
 4966:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4967:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4968: 	   if ($priv ne 'pch') { 
 4969: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4970: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4971: 	   }
 4972: 	   return '';
 4973:        }
 4974:    }
 4975: 
 4976: # Restricted by state or randomout?
 4977: 
 4978:    if ($thisallowed=~/X/) {
 4979:       if ($env{'acc.randomout'}) {
 4980: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4981:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4982:             return ''; 
 4983:          }
 4984:       }
 4985:       if (&condval($statecond)) {
 4986: 	 return '2';
 4987:       } else {
 4988:          return '';
 4989:       }
 4990:    }
 4991: 
 4992:     if ($thisallowed eq 'A') {
 4993: 	return 'A';
 4994:     } elsif ($thisallowed eq 'B') {
 4995:         return 'B';
 4996:     }
 4997:    return 'F';
 4998: }
 4999: 
 5000: sub split_uri_for_cond {
 5001:     my $uri=&deversion(&declutter(shift));
 5002:     my @uriparts=split(/\//,$uri);
 5003:     my $filename=pop(@uriparts);
 5004:     my $pathname=join('/',@uriparts);
 5005:     return ($pathname,$filename);
 5006: }
 5007: # --------------------------------------------------- Is a resource on the map?
 5008: 
 5009: sub is_on_map {
 5010:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 5011:     #Trying to find the conditional for the file
 5012:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 5013: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 5014:     if ($match) {
 5015: 	return (1,$1);
 5016:     } else {
 5017: 	return (0,0);
 5018:     }
 5019: }
 5020: 
 5021: # --------------------------------------------------------- Get symb from alias
 5022: 
 5023: sub get_symb_from_alias {
 5024:     my $symb=shift;
 5025:     my ($map,$resid,$url)=&decode_symb($symb);
 5026: # Already is a symb
 5027:     if ($url) { return $symb; }
 5028: # Must be an alias
 5029:     my $aliassymb='';
 5030:     my %bighash;
 5031:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5032:                             &GDBM_READER(),0640)) {
 5033:         my $rid=$bighash{'mapalias_'.$symb};
 5034: 	if ($rid) {
 5035: 	    my ($mapid,$resid)=split(/\./,$rid);
 5036: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 5037: 				    $resid,$bighash{'src_'.$rid});
 5038: 	}
 5039:         untie %bighash;
 5040:     }
 5041:     return $aliassymb;
 5042: }
 5043: 
 5044: # ----------------------------------------------------------------- Define Role
 5045: 
 5046: sub definerole {
 5047:   if (allowed('mcr','/')) {
 5048:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 5049:     foreach my $role (split(':',$sysrole)) {
 5050: 	my ($crole,$cqual)=split(/\&/,$role);
 5051:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 5052:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 5053: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5054:                return "refused:s:$crole&$cqual"; 
 5055:             }
 5056:         }
 5057:     }
 5058:     foreach my $role (split(':',$domrole)) {
 5059: 	my ($crole,$cqual)=split(/\&/,$role);
 5060:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 5061:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 5062: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 5063:                return "refused:d:$crole&$cqual"; 
 5064:             }
 5065:         }
 5066:     }
 5067:     foreach my $role (split(':',$courole)) {
 5068: 	my ($crole,$cqual)=split(/\&/,$role);
 5069:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 5070:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 5071: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5072:                return "refused:c:$crole&$cqual"; 
 5073:             }
 5074:         }
 5075:     }
 5076:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5077:                 "$env{'user.domain'}:$env{'user.name'}:".
 5078: 	        "rolesdef_$rolename=".
 5079:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 5080:     return reply($command,$env{'user.home'});
 5081:   } else {
 5082:     return 'refused';
 5083:   }
 5084: }
 5085: 
 5086: # ---------------- Make a metadata query against the network of library servers
 5087: 
 5088: sub metadata_query {
 5089:     my ($query,$custom,$customshow,$server_array)=@_;
 5090:     my %rhash;
 5091:     my %libserv = &all_library();
 5092:     my @server_list = (defined($server_array) ? @$server_array
 5093:                                               : keys(%libserv) );
 5094:     for my $server (@server_list) {
 5095: 	unless ($custom or $customshow) {
 5096: 	    my $reply=&reply("querysend:".&escape($query),$server);
 5097: 	    $rhash{$server}=$reply;
 5098: 	}
 5099: 	else {
 5100: 	    my $reply=&reply("querysend:".&escape($query).':'.
 5101: 			     &escape($custom).':'.&escape($customshow),
 5102: 			     $server);
 5103: 	    $rhash{$server}=$reply;
 5104: 	}
 5105:     }
 5106:     return \%rhash;
 5107: }
 5108: 
 5109: # ----------------------------------------- Send log queries and wait for reply
 5110: 
 5111: sub log_query {
 5112:     my ($uname,$udom,$query,%filters)=@_;
 5113:     my $uhome=&homeserver($uname,$udom);
 5114:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 5115:     my $uhost=&hostname($uhome);
 5116:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 5117:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 5118:                        $uhome);
 5119:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 5120:     return get_query_reply($queryid);
 5121: }
 5122: 
 5123: # -------------------------- Update MySQL table for portfolio file
 5124: 
 5125: sub update_portfolio_table {
 5126:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 5127:     if ($group ne '') {
 5128:         $file_name =~s /^\Q$group\E//;
 5129:     }
 5130:     my $homeserver = &homeserver($uname,$udom);
 5131:     my $queryid=
 5132:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 5133:                ':'.&escape($file_name).':'.$action,$homeserver);
 5134:     my $reply = &get_query_reply($queryid);
 5135:     return $reply;
 5136: }
 5137: 
 5138: # -------------------------- Update MySQL allusers table
 5139: 
 5140: sub update_allusers_table {
 5141:     my ($uname,$udom,$names) = @_;
 5142:     my $homeserver = &homeserver($uname,$udom);
 5143:     my $queryid=
 5144:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 5145:                'lastname='.&escape($names->{'lastname'}).'%%'.
 5146:                'firstname='.&escape($names->{'firstname'}).'%%'.
 5147:                'middlename='.&escape($names->{'middlename'}).'%%'.
 5148:                'generation='.&escape($names->{'generation'}).'%%'.
 5149:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 5150:                'id='.&escape($names->{'id'}),$homeserver);
 5151:     my $reply = &get_query_reply($queryid);
 5152:     return $reply;
 5153: }
 5154: 
 5155: # ------- Request retrieval of institutional classlists for course(s)
 5156: 
 5157: sub fetch_enrollment_query {
 5158:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 5159:     my $homeserver;
 5160:     my $maxtries = 1;
 5161:     if ($context eq 'automated') {
 5162:         $homeserver = $perlvar{'lonHostID'};
 5163:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 5164:     } else {
 5165:         $homeserver = &homeserver($cnum,$dom);
 5166:     }
 5167:     my $host=&hostname($homeserver);
 5168:     my $cmd = '';
 5169:     foreach my $affiliate (keys %{$affiliatesref}) {
 5170:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5171:     }
 5172:     $cmd =~ s/%%$//;
 5173:     $cmd = &escape($cmd);
 5174:     my $query = 'fetchenrollment';
 5175:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 5176:     unless ($queryid=~/^\Q$host\E\_/) { 
 5177:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 5178:         return 'error: '.$queryid;
 5179:     }
 5180:     my $reply = &get_query_reply($queryid);
 5181:     my $tries = 1;
 5182:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5183:         $reply = &get_query_reply($queryid);
 5184:         $tries ++;
 5185:     }
 5186:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5187:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5188:     } else {
 5189:         my @responses = split(/:/,$reply);
 5190:         if ($homeserver eq $perlvar{'lonHostID'}) {
 5191:             foreach my $line (@responses) {
 5192:                 my ($key,$value) = split(/=/,$line,2);
 5193:                 $$replyref{$key} = $value;
 5194:             }
 5195:         } else {
 5196:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 5197:             foreach my $line (@responses) {
 5198:                 my ($key,$value) = split(/=/,$line);
 5199:                 $$replyref{$key} = $value;
 5200:                 if ($value > 0) {
 5201:                     foreach my $item (@{$$affiliatesref{$key}}) {
 5202:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 5203:                         my $destname = $pathname.'/'.$filename;
 5204:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 5205:                         if ($xml_classlist =~ /^error/) {
 5206:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 5207:                         } else {
 5208:                             if ( open(FILE,">$destname") ) {
 5209:                                 print FILE &unescape($xml_classlist);
 5210:                                 close(FILE);
 5211:                             } else {
 5212:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 5213:                             }
 5214:                         }
 5215:                     }
 5216:                 }
 5217:             }
 5218:         }
 5219:         return 'ok';
 5220:     }
 5221:     return 'error';
 5222: }
 5223: 
 5224: sub get_query_reply {
 5225:     my $queryid=shift;
 5226:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 5227:     my $reply='';
 5228:     for (1..100) {
 5229: 	sleep 2;
 5230:         if (-e $replyfile.'.end') {
 5231: 	    if (open(my $fh,$replyfile)) {
 5232: 		$reply = join('',<$fh>);
 5233: 		close($fh);
 5234: 	   } else { return 'error: reply_file_error'; }
 5235:            return &unescape($reply);
 5236: 	}
 5237:     }
 5238:     return 'timeout:'.$queryid;
 5239: }
 5240: 
 5241: sub courselog_query {
 5242: #
 5243: # possible filters:
 5244: # url: url or symb
 5245: # username
 5246: # domain
 5247: # action: view, submit, grade
 5248: # start: timestamp
 5249: # end: timestamp
 5250: #
 5251:     my (%filters)=@_;
 5252:     unless ($env{'request.course.id'}) { return 'no_course'; }
 5253:     if ($filters{'url'}) {
 5254: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 5255:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 5256:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 5257:     }
 5258:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5259:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5260:     return &log_query($cname,$cdom,'courselog',%filters);
 5261: }
 5262: 
 5263: sub userlog_query {
 5264: #
 5265: # possible filters:
 5266: # action: log check role
 5267: # start: timestamp
 5268: # end: timestamp
 5269: #
 5270:     my ($uname,$udom,%filters)=@_;
 5271:     return &log_query($uname,$udom,'userlog',%filters);
 5272: }
 5273: 
 5274: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 5275: 
 5276: sub auto_run {
 5277:     my ($cnum,$cdom) = @_;
 5278:     my $response = 0;
 5279:     my $settings;
 5280:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 5281:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5282:         $settings = $domconfig{'autoenroll'};
 5283:         if ($settings->{'run'} eq '1') {
 5284:             $response = 1;
 5285:         }
 5286:     } else {
 5287:         my $homeserver;
 5288:         if (&is_course($cdom,$cnum)) {
 5289:             $homeserver = &homeserver($cnum,$cdom);
 5290:         } else {
 5291:             $homeserver = &domain($cdom,'primary');
 5292:         }
 5293:         if ($homeserver ne 'no_host') {
 5294:             $response = &reply('autorun:'.$cdom,$homeserver);
 5295:         }
 5296:     }
 5297:     return $response;
 5298: }
 5299: 
 5300: sub auto_get_sections {
 5301:     my ($cnum,$cdom,$inst_coursecode) = @_;
 5302:     my $homeserver = &homeserver($cnum,$cdom);
 5303:     my @secs = ();
 5304:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 5305:     unless ($response eq 'refused') {
 5306:         @secs = split(/:/,$response);
 5307:     }
 5308:     return @secs;
 5309: }
 5310: 
 5311: sub auto_new_course {
 5312:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 5313:     my $homeserver = &homeserver($cnum,$cdom);
 5314:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 5315:     return $response;
 5316: }
 5317: 
 5318: sub auto_validate_courseID {
 5319:     my ($cnum,$cdom,$inst_course_id) = @_;
 5320:     my $homeserver = &homeserver($cnum,$cdom);
 5321:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5322:     return $response;
 5323: }
 5324: 
 5325: sub auto_create_password {
 5326:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5327:     my ($homeserver,$response);
 5328:     my $create_passwd = 0;
 5329:     my $authchk = '';
 5330:     if ($udom =~ /^$match_domain$/) {
 5331:         $homeserver = &domain($udom,'primary');
 5332:     }
 5333:     if ($homeserver eq '') {
 5334:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5335:             $homeserver = &homeserver($cnum,$cdom);
 5336:         }
 5337:     }
 5338:     if ($homeserver eq '') {
 5339:         $authchk = 'nodomain';
 5340:     } else {
 5341:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5342:         if ($response eq 'refused') {
 5343:             $authchk = 'refused';
 5344:         } else {
 5345:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5346:         }
 5347:     }
 5348:     return ($authparam,$create_passwd,$authchk);
 5349: }
 5350: 
 5351: sub auto_photo_permission {
 5352:     my ($cnum,$cdom,$students) = @_;
 5353:     my $homeserver = &homeserver($cnum,$cdom);
 5354:     my ($outcome,$perm_reqd,$conditions) = 
 5355: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5356:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5357: 	return (undef,undef);
 5358:     }
 5359:     return ($outcome,$perm_reqd,$conditions);
 5360: }
 5361: 
 5362: sub auto_checkphotos {
 5363:     my ($uname,$udom,$pid) = @_;
 5364:     my $homeserver = &homeserver($uname,$udom);
 5365:     my ($result,$resulttype);
 5366:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5367: 				   &escape($uname).':'.&escape($pid),
 5368: 				   $homeserver));
 5369:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5370: 	return (undef,undef);
 5371:     }
 5372:     if ($outcome) {
 5373:         ($result,$resulttype) = split(/:/,$outcome);
 5374:     } 
 5375:     return ($result,$resulttype);
 5376: }
 5377: 
 5378: sub auto_photochoice {
 5379:     my ($cnum,$cdom) = @_;
 5380:     my $homeserver = &homeserver($cnum,$cdom);
 5381:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5382: 						       &escape($cdom),
 5383: 						       $homeserver)));
 5384:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5385: 	return (undef,undef);
 5386:     }
 5387:     return ($update,$comment);
 5388: }
 5389: 
 5390: sub auto_photoupdate {
 5391:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5392:     my $homeserver = &homeserver($cnum,$dom);
 5393:     my $host=&hostname($homeserver);
 5394:     my $cmd = '';
 5395:     my $maxtries = 1;
 5396:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5397:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5398:     }
 5399:     $cmd =~ s/%%$//;
 5400:     $cmd = &escape($cmd);
 5401:     my $query = 'institutionalphotos';
 5402:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5403:     unless ($queryid=~/^\Q$host\E\_/) {
 5404:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5405:         return 'error: '.$queryid;
 5406:     }
 5407:     my $reply = &get_query_reply($queryid);
 5408:     my $tries = 1;
 5409:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5410:         $reply = &get_query_reply($queryid);
 5411:         $tries ++;
 5412:     }
 5413:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5414:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5415:     } else {
 5416:         my @responses = split(/:/,$reply);
 5417:         my $outcome = shift(@responses); 
 5418:         foreach my $item (@responses) {
 5419:             my ($key,$value) = split(/=/,$item);
 5420:             $$photo{$key} = $value;
 5421:         }
 5422:         return $outcome;
 5423:     }
 5424:     return 'error';
 5425: }
 5426: 
 5427: sub auto_instcode_format {
 5428:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5429: 	$cat_order) = @_;
 5430:     my $courses = '';
 5431:     my @homeservers;
 5432:     if ($caller eq 'global') {
 5433: 	my %servers = &get_servers($codedom,'library');
 5434: 	foreach my $tryserver (keys(%servers)) {
 5435: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5436: 		push(@homeservers,$tryserver);
 5437: 	    }
 5438:         }
 5439:     } else {
 5440:         push(@homeservers,&homeserver($caller,$codedom));
 5441:     }
 5442:     foreach my $code (keys(%{$instcodes})) {
 5443:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5444:     }
 5445:     chop($courses);
 5446:     my $ok_response = 0;
 5447:     my $response;
 5448:     while (@homeservers > 0 && $ok_response == 0) {
 5449:         my $server = shift(@homeservers); 
 5450:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5451:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5452:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5453: 		split(/:/,$response);
 5454:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5455:             push(@{$codetitles},&str2array($codetitles_str));
 5456:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5457:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5458:             $ok_response = 1;
 5459:         }
 5460:     }
 5461:     if ($ok_response) {
 5462:         return 'ok';
 5463:     } else {
 5464:         return $response;
 5465:     }
 5466: }
 5467: 
 5468: sub auto_instcode_defaults {
 5469:     my ($domain,$returnhash,$code_order) = @_;
 5470:     my @homeservers;
 5471: 
 5472:     my %servers = &get_servers($domain,'library');
 5473:     foreach my $tryserver (keys(%servers)) {
 5474: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5475: 	    push(@homeservers,$tryserver);
 5476: 	}
 5477:     }
 5478: 
 5479:     my $response;
 5480:     foreach my $server (@homeservers) {
 5481:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5482:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5483: 	
 5484: 	foreach my $pair (split(/\&/,$response)) {
 5485: 	    my ($name,$value)=split(/\=/,$pair);
 5486: 	    if ($name eq 'code_order') {
 5487: 		@{$code_order} = split(/\&/,&unescape($value));
 5488: 	    } else {
 5489: 		$returnhash->{&unescape($name)}=&unescape($value);
 5490: 	    }
 5491: 	}
 5492: 	return 'ok';
 5493:     }
 5494: 
 5495:     return $response;
 5496: } 
 5497: 
 5498: sub auto_validate_class_sec {
 5499:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5500:     my $homeserver = &homeserver($cnum,$cdom);
 5501:     my $ownerlist;
 5502:     if (ref($owners) eq 'ARRAY') {
 5503:         $ownerlist = join(',',@{$owners});
 5504:     } else {
 5505:         $ownerlist = $owners;
 5506:     }
 5507:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 5508:                         &escape($ownerlist).':'.$cdom,$homeserver);
 5509:     return $response;
 5510: }
 5511: 
 5512: # ------------------------------------------------------- Course Group routines
 5513: 
 5514: sub get_coursegroups {
 5515:     my ($cdom,$cnum,$group,$namespace) = @_;
 5516:     return(&dump($namespace,$cdom,$cnum,$group));
 5517: }
 5518: 
 5519: sub modify_coursegroup {
 5520:     my ($cdom,$cnum,$groupsettings) = @_;
 5521:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 5522: }
 5523: 
 5524: sub toggle_coursegroup_status {
 5525:     my ($cdom,$cnum,$group,$action) = @_;
 5526:     my ($from_namespace,$to_namespace);
 5527:     if ($action eq 'delete') {
 5528:         $from_namespace = 'coursegroups';
 5529:         $to_namespace = 'deleted_groups';
 5530:     } else {
 5531:         $from_namespace = 'deleted_groups';
 5532:         $to_namespace = 'coursegroups';
 5533:     }
 5534:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 5535:     if (my $tmp = &error(%curr_group)) {
 5536:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 5537:         return ('read error',$tmp);
 5538:     } else {
 5539:         my %savedsettings = %curr_group; 
 5540:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 5541:         my $deloutcome;
 5542:         if ($result eq 'ok') {
 5543:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 5544:         } else {
 5545:             return ('write error',$result);
 5546:         }
 5547:         if ($deloutcome eq 'ok') {
 5548:             return 'ok';
 5549:         } else {
 5550:             return ('delete error',$deloutcome);
 5551:         }
 5552:     }
 5553: }
 5554: 
 5555: sub modify_group_roles {
 5556:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 5557:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 5558:     my $role = 'gr/'.&escape($userprivs);
 5559:     my ($uname,$udom) = split(/:/,$user);
 5560:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 5561:     if ($result eq 'ok') {
 5562:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 5563:     }
 5564:     return $result;
 5565: }
 5566: 
 5567: sub modify_coursegroup_membership {
 5568:     my ($cdom,$cnum,$membership) = @_;
 5569:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 5570:     return $result;
 5571: }
 5572: 
 5573: sub get_active_groups {
 5574:     my ($udom,$uname,$cdom,$cnum) = @_;
 5575:     my $now = time;
 5576:     my %groups = ();
 5577:     foreach my $key (keys(%env)) {
 5578:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 5579:             my ($start,$end) = split(/\./,$env{$key});
 5580:             if (($end!=0) && ($end<$now)) { next; }
 5581:             if (($start!=0) && ($start>$now)) { next; }
 5582:             if ($1 eq $cdom && $2 eq $cnum) {
 5583:                 $groups{$3} = $env{$key} ;
 5584:             }
 5585:         }
 5586:     }
 5587:     return %groups;
 5588: }
 5589: 
 5590: sub get_group_membership {
 5591:     my ($cdom,$cnum,$group) = @_;
 5592:     return(&dump('groupmembership',$cdom,$cnum,$group));
 5593: }
 5594: 
 5595: sub get_users_groups {
 5596:     my ($udom,$uname,$courseid) = @_;
 5597:     my @usersgroups;
 5598:     my $cachetime=1800;
 5599: 
 5600:     my $hashid="$udom:$uname:$courseid";
 5601:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 5602:     if (defined($cached)) {
 5603:         @usersgroups = split(/:/,$grouplist);
 5604:     } else {  
 5605:         $grouplist = '';
 5606:         my $courseurl = &courseid_to_courseurl($courseid);
 5607:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 5608:         my $access_end = $env{'course.'.$courseid.
 5609:                               '.default_enrollment_end_date'};
 5610:         my $now = time;
 5611:         foreach my $key (keys(%roleshash)) {
 5612:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 5613:                 my $group = $1;
 5614:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 5615:                     my $start = $2;
 5616:                     my $end = $1;
 5617:                     if ($start == -1) { next; } # deleted from group
 5618:                     if (($start!=0) && ($start>$now)) { next; }
 5619:                     if (($end!=0) && ($end<$now)) {
 5620:                         if ($access_end && $access_end < $now) {
 5621:                             if ($access_end - $end < 86400) {
 5622:                                 push(@usersgroups,$group);
 5623:                             }
 5624:                         }
 5625:                         next;
 5626:                     }
 5627:                     push(@usersgroups,$group);
 5628:                 }
 5629:             }
 5630:         }
 5631:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 5632:         $grouplist = join(':',@usersgroups);
 5633:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 5634:     }
 5635:     return @usersgroups;
 5636: }
 5637: 
 5638: sub devalidate_getgroups_cache {
 5639:     my ($udom,$uname,$cdom,$cnum)=@_;
 5640:     my $courseid = $cdom.'_'.$cnum;
 5641: 
 5642:     my $hashid="$udom:$uname:$courseid";
 5643:     &devalidate_cache_new('getgroups',$hashid);
 5644: }
 5645: 
 5646: # ------------------------------------------------------------------ Plain Text
 5647: 
 5648: sub plaintext {
 5649:     my ($short,$type,$cid) = @_;
 5650:     if ($short =~ /^cr/) {
 5651: 	return (split('/',$short))[-1];
 5652:     }
 5653:     if (!defined($cid)) {
 5654:         $cid = $env{'request.course.id'};
 5655:     }
 5656:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 5657:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 5658:                                           '.plaintext'});
 5659:     }
 5660:     my %rolenames = (
 5661:                       Course => 'std',
 5662:                       Group => 'alt1',
 5663:                     );
 5664:     if (defined($type) && 
 5665:          defined($rolenames{$type}) && 
 5666:          defined($prp{$short}{$rolenames{$type}})) {
 5667:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 5668:     } else {
 5669:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 5670:     }
 5671: }
 5672: 
 5673: # ----------------------------------------------------------------- Assign Role
 5674: 
 5675: sub assignrole {
 5676:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 5677:         $context)=@_;
 5678:     my $mrole;
 5679:     if ($role =~ /^cr\//) {
 5680:         my $cwosec=$url;
 5681:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5682: 	unless (&allowed('ccr',$cwosec)) {
 5683:            &logthis('Refused custom assignrole: '.
 5684:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5685: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 5686:            return 'refused'; 
 5687:         }
 5688:         $mrole='cr';
 5689:     } elsif ($role =~ /^gr\//) {
 5690:         my $cwogrp=$url;
 5691:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 5692:         unless (&allowed('mdg',$cwogrp)) {
 5693:             &logthis('Refused group assignrole: '.
 5694:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5695:                     $env{'user.name'}.' at '.$env{'user.domain'});
 5696:             return 'refused';
 5697:         }
 5698:         $mrole='gr';
 5699:     } else {
 5700:         my $cwosec=$url;
 5701:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5702:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 5703:             my $refused;
 5704:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 5705:                 if (!(&allowed('c'.$role,$url))) {
 5706:                     $refused = 1;
 5707:                 }
 5708:             } else {
 5709:                 $refused = 1;
 5710:             }
 5711:             if ($refused) {
 5712:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5713:                     $refused = '';
 5714:                 } else {
 5715:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 5716:                              ' '.$role.' '.$end.' '.$start.' by '.
 5717: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 5718:                     return 'refused';
 5719:                 }
 5720:             }
 5721:         }
 5722:         $mrole=$role;
 5723:     }
 5724:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5725:                 "$udom:$uname:$url".'_'."$mrole=$role";
 5726:     if ($end) { $command.='_'.$end; }
 5727:     if ($start) {
 5728: 	if ($end) { 
 5729:            $command.='_'.$start; 
 5730:         } else {
 5731:            $command.='_0_'.$start;
 5732:         }
 5733:     }
 5734:     my $origstart = $start;
 5735:     my $origend = $end;
 5736:     my $delflag;
 5737: # actually delete
 5738:     if ($deleteflag) {
 5739: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 5740: # modify command to delete the role
 5741:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 5742:                 "$udom:$uname:$url".'_'."$mrole";
 5743: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 5744: # set start and finish to negative values for userrolelog
 5745:            $start=-1;
 5746:            $end=-1;
 5747:            $delflag = 1;
 5748:         }
 5749:     }
 5750: # send command
 5751:     my $answer=&reply($command,&homeserver($uname,$udom));
 5752: # log new user role if status is ok
 5753:     if ($answer eq 'ok') {
 5754: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 5755: # for course roles, perform group memberships changes triggered by role change.
 5756:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 5757:         unless ($role =~ /^gr/) {
 5758:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 5759:                                              $origstart,$selfenroll,$context);
 5760:         }
 5761:     }
 5762:     return $answer;
 5763: }
 5764: 
 5765: # -------------------------------------------------- Modify user authentication
 5766: # Overrides without validation
 5767: 
 5768: sub modifyuserauth {
 5769:     my ($udom,$uname,$umode,$upass)=@_;
 5770:     my $uhome=&homeserver($uname,$udom);
 5771:     unless (&allowed('mau',$udom)) { return 'refused'; }
 5772:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 5773:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5774:              ' in domain '.$env{'request.role.domain'});  
 5775:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 5776: 		     &escape($upass),$uhome);
 5777:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 5778:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 5779:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5780:     &log($udom,,$uname,$uhome,
 5781:         'Authentication changed by '.$env{'user.domain'}.', '.
 5782:                                      $env{'user.name'}.', '.$umode.
 5783:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5784:     unless ($reply eq 'ok') {
 5785:         &logthis('Authentication mode error: '.$reply);
 5786: 	return 'error: '.$reply;
 5787:     }   
 5788:     return 'ok';
 5789: }
 5790: 
 5791: # --------------------------------------------------------------- Modify a user
 5792: 
 5793: sub modifyuser {
 5794:     my ($udom,    $uname, $uid,
 5795:         $umode,   $upass, $first,
 5796:         $middle,  $last,  $gene,
 5797:         $forceid, $desiredhome, $email, $inststatus)=@_;
 5798:     $udom= &LONCAPA::clean_domain($udom);
 5799:     $uname=&LONCAPA::clean_username($uname);
 5800:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 5801:              $umode.', '.$first.', '.$middle.', '.
 5802: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 5803:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 5804:                                      ' desiredhome not specified'). 
 5805:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5806:              ' in domain '.$env{'request.role.domain'});
 5807:     my $uhome=&homeserver($uname,$udom,'true');
 5808: # ----------------------------------------------------------------- Create User
 5809:     if (($uhome eq 'no_host') && 
 5810: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 5811:         my $unhome='';
 5812:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 5813:             $unhome = $desiredhome;
 5814: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 5815: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 5816:         } else { # load balancing routine for determining $unhome
 5817:             my $loadm=10000000;
 5818: 	    my %servers = &get_servers($udom,'library');
 5819: 	    foreach my $tryserver (keys(%servers)) {
 5820: 		my $answer=reply('load',$tryserver);
 5821: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 5822: 		    $loadm=$answer;
 5823: 		    $unhome=$tryserver;
 5824: 		}
 5825: 	    }
 5826:         }
 5827:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 5828: 	    return 'error: unable to find a home server for '.$uname.
 5829:                    ' in domain '.$udom;
 5830:         }
 5831:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 5832:                          &escape($upass),$unhome);
 5833: 	unless ($reply eq 'ok') {
 5834:             return 'error: '.$reply;
 5835:         }   
 5836:         $uhome=&homeserver($uname,$udom,'true');
 5837:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 5838: 	    return 'error: unable verify users home machine.';
 5839:         }
 5840:     }   # End of creation of new user
 5841: # ---------------------------------------------------------------------- Add ID
 5842:     if ($uid) {
 5843:        $uid=~tr/A-Z/a-z/;
 5844:        my %uidhash=&idrget($udom,$uname);
 5845:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 5846:          && (!$forceid)) {
 5847: 	  unless ($uid eq $uidhash{$uname}) {
 5848: 	      return 'error: user id "'.$uid.'" does not match '.
 5849:                   'current user id "'.$uidhash{$uname}.'".';
 5850:           }
 5851:        } else {
 5852: 	  &idput($udom,($uname => $uid));
 5853:        }
 5854:     }
 5855: # -------------------------------------------------------------- Add names, etc
 5856:     my @tmp=&get('environment',
 5857: 		   ['firstname','middlename','lastname','generation','id',
 5858:                     'permanentemail','inststatus'],
 5859: 		   $udom,$uname);
 5860:     my %names;
 5861:     if ($tmp[0] =~ m/^error:.*/) { 
 5862:         %names=(); 
 5863:     } else {
 5864:         %names = @tmp;
 5865:     }
 5866: #
 5867: # Make sure to not trash student environment if instructor does not bother
 5868: # to supply name and email information
 5869: #
 5870:     if ($first)  { $names{'firstname'}  = $first; }
 5871:     if (defined($middle)) { $names{'middlename'} = $middle; }
 5872:     if ($last)   { $names{'lastname'}   = $last; }
 5873:     if (defined($gene))   { $names{'generation'} = $gene; }
 5874:     if ($email) {
 5875:        $email=~s/[^\w\@\.\-\,]//gs;
 5876:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 5877:     }
 5878:     if ($uid) { $names{'id'}  = $uid; }
 5879:     if (defined($inststatus)) { $names{'inststatus'} = $inststatus; } 
 5880:     my $reply = &put('environment', \%names, $udom,$uname);
 5881:     if ($reply ne 'ok') { return 'error: '.$reply; }
 5882:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 5883:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 5884:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 5885:                  $umode.', '.$first.', '.$middle.', '.
 5886: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
 5887:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 5888:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 5889:     } else {
 5890:         $logmsg .= ' during self creation';
 5891:     }
 5892:     &logthis($logmsg);
 5893:     return 'ok';
 5894: }
 5895: 
 5896: # -------------------------------------------------------------- Modify student
 5897: 
 5898: sub modifystudent {
 5899:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 5900:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 5901:         $selfenroll,$context)=@_;
 5902:     if (!$cid) {
 5903: 	unless ($cid=$env{'request.course.id'}) {
 5904: 	    return 'not_in_class';
 5905: 	}
 5906:     }
 5907: # --------------------------------------------------------------- Make the user
 5908:     my $reply=&modifyuser
 5909: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 5910:          $desiredhome,$email);
 5911:     unless ($reply eq 'ok') { return $reply; }
 5912:     # This will cause &modify_student_enrollment to get the uid from the
 5913:     # students environment
 5914:     $uid = undef if (!$forceid);
 5915:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 5916: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 5917:     return $reply;
 5918: }
 5919: 
 5920: sub modify_student_enrollment {
 5921:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 5922:     my ($cdom,$cnum,$chome);
 5923:     if (!$cid) {
 5924: 	unless ($cid=$env{'request.course.id'}) {
 5925: 	    return 'not_in_class';
 5926: 	}
 5927: 	$cdom=$env{'course.'.$cid.'.domain'};
 5928: 	$cnum=$env{'course.'.$cid.'.num'};
 5929:     } else {
 5930: 	($cdom,$cnum)=split(/_/,$cid);
 5931:     }
 5932:     $chome=$env{'course.'.$cid.'.home'};
 5933:     if (!$chome) {
 5934: 	$chome=&homeserver($cnum,$cdom);
 5935:     }
 5936:     if (!$chome) { return 'unknown_course'; }
 5937:     # Make sure the user exists
 5938:     my $uhome=&homeserver($uname,$udom);
 5939:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5940: 	return 'error: no such user';
 5941:     }
 5942:     # Get student data if we were not given enough information
 5943:     if (!defined($first)  || $first  eq '' || 
 5944:         !defined($last)   || $last   eq '' || 
 5945:         !defined($uid)    || $uid    eq '' || 
 5946:         !defined($middle) || $middle eq '' || 
 5947:         !defined($gene)   || $gene   eq '') {
 5948:         # They did not supply us with enough data to enroll the student, so
 5949:         # we need to pick up more information.
 5950:         my %tmp = &get('environment',
 5951:                        ['firstname','middlename','lastname', 'generation','id']
 5952:                        ,$udom,$uname);
 5953: 
 5954:         #foreach my $key (keys(%tmp)) {
 5955:         #    &logthis("key $key = ".$tmp{$key});
 5956:         #}
 5957:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 5958:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 5959:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 5960:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 5961:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 5962:     }
 5963:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 5964:     my $reply=cput('classlist',
 5965: 		   {"$uname:$udom" => 
 5966: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 5967: 		   $cdom,$cnum);
 5968:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 5969: 	return 'error: '.$reply;
 5970:     } else {
 5971: 	&devalidate_getsection_cache($udom,$uname,$cid);
 5972:     }
 5973:     # Add student role to user
 5974:     my $uurl='/'.$cid;
 5975:     $uurl=~s/\_/\//g;
 5976:     if ($usec) {
 5977: 	$uurl.='/'.$usec;
 5978:     }
 5979:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 5980: }
 5981: 
 5982: sub format_name {
 5983:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 5984:     my $name;
 5985:     if ($first ne 'lastname') {
 5986: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 5987:     } else {
 5988: 	if ($lastname=~/\S/) {
 5989: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 5990: 	    $name=~s/\s+,/,/;
 5991: 	} else {
 5992: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 5993: 	}
 5994:     }
 5995:     $name=~s/^\s+//;
 5996:     $name=~s/\s+$//;
 5997:     $name=~s/\s+/ /g;
 5998:     return $name;
 5999: }
 6000: 
 6001: # ------------------------------------------------- Write to course preferences
 6002: 
 6003: sub writecoursepref {
 6004:     my ($courseid,%prefs)=@_;
 6005:     $courseid=~s/^\///;
 6006:     $courseid=~s/\_/\//g;
 6007:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6008:     my $chome=homeserver($cnum,$cdomain);
 6009:     if (($chome eq '') || ($chome eq 'no_host')) { 
 6010: 	return 'error: no such course';
 6011:     }
 6012:     my $cstring='';
 6013:     foreach my $pref (keys(%prefs)) {
 6014: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 6015:     }
 6016:     $cstring=~s/\&$//;
 6017:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 6018: }
 6019: 
 6020: # ---------------------------------------------------------- Make/modify course
 6021: 
 6022: sub createcourse {
 6023:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 6024:         $course_owner,$crstype)=@_;
 6025:     $url=&declutter($url);
 6026:     my $cid='';
 6027:     unless (&allowed('ccc',$udom)) {
 6028:         return 'refused';
 6029:     }
 6030: # ------------------------------------------------------------------- Create ID
 6031:    my $uname=int(1+rand(9)).
 6032:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6033:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6034:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6035: # ----------------------------------------------- Make sure that does not exist
 6036:    my $uhome=&homeserver($uname,$udom,'true');
 6037:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6038:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6039:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6040:        $uhome=&homeserver($uname,$udom,'true');       
 6041:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6042:            return 'error: unable to generate unique course-ID';
 6043:        } 
 6044:    }
 6045: # ------------------------------------------------ Check supplied server name
 6046:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 6047:     if (! &is_library($course_server)) {
 6048:         return 'error:bad server name '.$course_server;
 6049:     }
 6050: # ------------------------------------------------------------- Make the course
 6051:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 6052:                       $course_server);
 6053:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 6054:     $uhome=&homeserver($uname,$udom,'true');
 6055:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6056: 	return 'error: no such course';
 6057:     }
 6058: # ----------------------------------------------------------------- Course made
 6059: # log existence
 6060:     my $newcourse = {
 6061:                     $udom.'_'.$uname => {
 6062:                                      description => $description,
 6063:                                      inst_code   => $inst_code,
 6064:                                      owner       => $course_owner,
 6065:                                      type        => $crstype,
 6066:                                                 },
 6067:                     };
 6068:     &courseidput($udom,$newcourse,$uhome,'notime');
 6069: # set toplevel url
 6070:     my $topurl=$url;
 6071:     unless ($nonstandard) {
 6072: # ------------------------------------------ For standard courses, make top url
 6073:         my $mapurl=&clutter($url);
 6074:         if ($mapurl eq '/res/') { $mapurl=''; }
 6075:         $env{'form.initmap'}=(<<ENDINITMAP);
 6076: <map>
 6077: <resource id="1" type="start"></resource>
 6078: <resource id="2" src="$mapurl"></resource>
 6079: <resource id="3" type="finish"></resource>
 6080: <link index="1" from="1" to="2"></link>
 6081: <link index="2" from="2" to="3"></link>
 6082: </map>
 6083: ENDINITMAP
 6084:         $topurl=&declutter(
 6085:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 6086:                           );
 6087:     }
 6088: # ----------------------------------------------------------- Write preferences
 6089:     &writecoursepref($udom.'_'.$uname,
 6090:                      ('description' => $description,
 6091:                       'url'         => $topurl));
 6092:     return '/'.$udom.'/'.$uname;
 6093: }
 6094: 
 6095: sub is_course {
 6096:     my ($cdom,$cnum) = @_;
 6097:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 6098: 				undef,'.');
 6099:     if (exists($courses{$cdom.'_'.$cnum})) {
 6100:         return 1;
 6101:     }
 6102:     return 0;
 6103: }
 6104: 
 6105: # ---------------------------------------------------------- Assign Custom Role
 6106: 
 6107: sub assigncustomrole {
 6108:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 6109:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 6110:                        $end,$start,$deleteflag,$selfenroll,$context);
 6111: }
 6112: 
 6113: # ----------------------------------------------------------------- Revoke Role
 6114: 
 6115: sub revokerole {
 6116:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 6117:     my $now=time;
 6118:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 6119: }
 6120: 
 6121: # ---------------------------------------------------------- Revoke Custom Role
 6122: 
 6123: sub revokecustomrole {
 6124:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 6125:     my $now=time;
 6126:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 6127:            $deleteflag,$selfenroll,$context);
 6128: }
 6129: 
 6130: # ------------------------------------------------------------ Disk usage
 6131: sub diskusage {
 6132:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 6133:     $directorypath =~ s/\/$//;
 6134:     my $listing=&reply('du2:'.&escape($directorypath).':'
 6135:                        .&escape($getpropath).':'.&escape($uname).':'
 6136:                        .&escape($udom),homeserver($uname,$udom));
 6137:     if ($listing eq 'unknown_cmd') {
 6138:         if ($getpropath) {
 6139:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 6140:         }
 6141:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 6142:     }
 6143:     return $listing;
 6144: }
 6145: 
 6146: sub is_locked {
 6147:     my ($file_name, $domain, $user) = @_;
 6148:     my @check;
 6149:     my $is_locked;
 6150:     push @check, $file_name;
 6151:     my %locked = &get('file_permissions',\@check,
 6152: 		      $env{'user.domain'},$env{'user.name'});
 6153:     my ($tmp)=keys(%locked);
 6154:     if ($tmp=~/^error:/) { undef(%locked); }
 6155:     
 6156:     if (ref($locked{$file_name}) eq 'ARRAY') {
 6157:         $is_locked = 'false';
 6158:         foreach my $entry (@{$locked{$file_name}}) {
 6159:            if (ref($entry) eq 'ARRAY') { 
 6160:                $is_locked = 'true';
 6161:                last;
 6162:            }
 6163:        }
 6164:     } else {
 6165:         $is_locked = 'false';
 6166:     }
 6167: }
 6168: 
 6169: sub declutter_portfile {
 6170:     my ($file) = @_;
 6171:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 6172:     return $file;
 6173: }
 6174: 
 6175: # ------------------------------------------------------------- Mark as Read Only
 6176: 
 6177: sub mark_as_readonly {
 6178:     my ($domain,$user,$files,$what) = @_;
 6179:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6180:     my ($tmp)=keys(%current_permissions);
 6181:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6182:     foreach my $file (@{$files}) {
 6183: 	$file = &declutter_portfile($file);
 6184:         push(@{$current_permissions{$file}},$what);
 6185:     }
 6186:     &put('file_permissions',\%current_permissions,$domain,$user);
 6187:     return;
 6188: }
 6189: 
 6190: # ------------------------------------------------------------Save Selected Files
 6191: 
 6192: sub save_selected_files {
 6193:     my ($user, $path, @files) = @_;
 6194:     my $filename = $user."savedfiles";
 6195:     my @other_files = &files_not_in_path($user, $path);
 6196:     open (OUT, '>'.$tmpdir.$filename);
 6197:     foreach my $file (@files) {
 6198:         print (OUT $env{'form.currentpath'}.$file."\n");
 6199:     }
 6200:     foreach my $file (@other_files) {
 6201:         print (OUT $file."\n");
 6202:     }
 6203:     close (OUT);
 6204:     return 'ok';
 6205: }
 6206: 
 6207: sub clear_selected_files {
 6208:     my ($user) = @_;
 6209:     my $filename = $user."savedfiles";
 6210:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6211:     print (OUT undef);
 6212:     close (OUT);
 6213:     return ("ok");    
 6214: }
 6215: 
 6216: sub files_in_path {
 6217:     my ($user, $path) = @_;
 6218:     my $filename = $user."savedfiles";
 6219:     my %return_files;
 6220:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6221:     while (my $line_in = <IN>) {
 6222:         chomp ($line_in);
 6223:         my @paths_and_file = split (m!/!, $line_in);
 6224:         my $file_part = pop (@paths_and_file);
 6225:         my $path_part = join ('/', @paths_and_file);
 6226:         $path_part.='/';
 6227:         my $path_and_file = $path_part.$file_part;
 6228:         if ($path_part eq $path) {
 6229:             $return_files{$file_part}= 'selected';
 6230:         }
 6231:     }
 6232:     close (IN);
 6233:     return (\%return_files);
 6234: }
 6235: 
 6236: # called in portfolio select mode, to show files selected NOT in current directory
 6237: sub files_not_in_path {
 6238:     my ($user, $path) = @_;
 6239:     my $filename = $user."savedfiles";
 6240:     my @return_files;
 6241:     my $path_part;
 6242:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6243:     while (my $line = <IN>) {
 6244:         #ok, I know it's clunky, but I want it to work
 6245:         my @paths_and_file = split(m|/|, $line);
 6246:         my $file_part = pop(@paths_and_file);
 6247:         chomp($file_part);
 6248:         my $path_part = join('/', @paths_and_file);
 6249:         $path_part .= '/';
 6250:         my $path_and_file = $path_part.$file_part;
 6251:         if ($path_part ne $path) {
 6252:             push(@return_files, ($path_and_file));
 6253:         }
 6254:     }
 6255:     close(OUT);
 6256:     return (@return_files);
 6257: }
 6258: 
 6259: #----------------------------------------------Get portfolio file permissions
 6260: 
 6261: sub get_portfile_permissions {
 6262:     my ($domain,$user) = @_;
 6263:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6264:     my ($tmp)=keys(%current_permissions);
 6265:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6266:     return \%current_permissions;
 6267: }
 6268: 
 6269: #---------------------------------------------Get portfolio file access controls
 6270: 
 6271: sub get_access_controls {
 6272:     my ($current_permissions,$group,$file) = @_;
 6273:     my %access;
 6274:     my $real_file = $file;
 6275:     $file =~ s/\.meta$//;
 6276:     if (defined($file)) {
 6277:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 6278:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 6279:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 6280:             }
 6281:         }
 6282:     } else {
 6283:         foreach my $key (keys(%{$current_permissions})) {
 6284:             if ($key =~ /\0accesscontrol$/) {
 6285:                 if (defined($group)) {
 6286:                     if ($key !~ m-^\Q$group\E/-) {
 6287:                         next;
 6288:                     }
 6289:                 }
 6290:                 my ($fullpath) = split(/\0/,$key);
 6291:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 6292:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 6293:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 6294:                     }
 6295:                 }
 6296:             }
 6297:         }
 6298:     }
 6299:     return %access;
 6300: }
 6301: 
 6302: sub modify_access_controls {
 6303:     my ($file_name,$changes,$domain,$user)=@_;
 6304:     my ($outcome,$deloutcome);
 6305:     my %store_permissions;
 6306:     my %new_values;
 6307:     my %new_control;
 6308:     my %translation;
 6309:     my @deletions = ();
 6310:     my $now = time;
 6311:     if (exists($$changes{'activate'})) {
 6312:         if (ref($$changes{'activate'}) eq 'HASH') {
 6313:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 6314:             my $numnew = scalar(@newitems);
 6315:             for (my $i=0; $i<$numnew; $i++) {
 6316:                 my $newkey = $newitems[$i];
 6317:                 my $newid = &Apache::loncommon::get_cgi_id();
 6318:                 if ($newkey =~ /^\d+:/) { 
 6319:                     $newkey =~ s/^(\d+)/$newid/;
 6320:                     $translation{$1} = $newid;
 6321:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 6322:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 6323:                     $translation{$1} = $newid;
 6324:                 }
 6325:                 $new_values{$file_name."\0".$newkey} = 
 6326:                                           $$changes{'activate'}{$newitems[$i]};
 6327:                 $new_control{$newkey} = $now;
 6328:             }
 6329:         }
 6330:     }
 6331:     my %todelete;
 6332:     my %changed_items;
 6333:     foreach my $action ('delete','update') {
 6334:         if (exists($$changes{$action})) {
 6335:             if (ref($$changes{$action}) eq 'HASH') {
 6336:                 foreach my $key (keys(%{$$changes{$action}})) {
 6337:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 6338:                     if ($action eq 'delete') { 
 6339:                         $todelete{$itemnum} = 1;
 6340:                     } else {
 6341:                         $changed_items{$itemnum} = $key;
 6342:                     }
 6343:                 }
 6344:             }
 6345:         }
 6346:     }
 6347:     # get lock on access controls for file.
 6348:     my $lockhash = {
 6349:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 6350:                                                        ':'.$env{'user.domain'},
 6351:                    }; 
 6352:     my $tries = 0;
 6353:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6354:    
 6355:     while (($gotlock ne 'ok') && $tries <3) {
 6356:         $tries ++;
 6357:         sleep 1;
 6358:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6359:     }
 6360:     if ($gotlock eq 'ok') {
 6361:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 6362:         my ($tmp)=keys(%curr_permissions);
 6363:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 6364:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 6365:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 6366:             if (ref($curr_controls) eq 'HASH') {
 6367:                 foreach my $control_item (keys(%{$curr_controls})) {
 6368:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 6369:                     if (defined($todelete{$itemnum})) {
 6370:                         push(@deletions,$file_name."\0".$control_item);
 6371:                     } else {
 6372:                         if (defined($changed_items{$itemnum})) {
 6373:                             $new_control{$changed_items{$itemnum}} = $now;
 6374:                             push(@deletions,$file_name."\0".$control_item);
 6375:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 6376:                         } else {
 6377:                             $new_control{$control_item} = $$curr_controls{$control_item};
 6378:                         }
 6379:                     }
 6380:                 }
 6381:             }
 6382:         }
 6383:         my ($group);
 6384:         if (&is_course($domain,$user)) {
 6385:             ($group,my $file) = split(/\//,$file_name,2);
 6386:         }
 6387:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 6388:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 6389:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 6390:         #  remove lock
 6391:         my @del_lock = ($file_name."\0".'locked_access_records');
 6392:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 6393:         my $sqlresult =
 6394:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 6395:                                     $group);
 6396:     } else {
 6397:         $outcome = "error: could not obtain lockfile\n";  
 6398:     }
 6399:     return ($outcome,$deloutcome,\%new_values,\%translation);
 6400: }
 6401: 
 6402: sub make_public_indefinitely {
 6403:     my ($requrl) = @_;
 6404:     my $now = time;
 6405:     my $action = 'activate';
 6406:     my $aclnum = 0;
 6407:     if (&is_portfolio_url($requrl)) {
 6408:         my (undef,$udom,$unum,$file_name,$group) =
 6409:             &parse_portfolio_url($requrl);
 6410:         my $current_perms = &get_portfile_permissions($udom,$unum);
 6411:         my %access_controls = &get_access_controls($current_perms,
 6412:                                                    $group,$file_name);
 6413:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 6414:             my ($num,$scope,$end,$start) = 
 6415:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6416:             if ($scope eq 'public') {
 6417:                 if ($start <= $now && $end == 0) {
 6418:                     $action = 'none';
 6419:                 } else {
 6420:                     $action = 'update';
 6421:                     $aclnum = $num;
 6422:                 }
 6423:                 last;
 6424:             }
 6425:         }
 6426:         if ($action eq 'none') {
 6427:              return 'ok';
 6428:         } else {
 6429:             my %changes;
 6430:             my $newend = 0;
 6431:             my $newstart = $now;
 6432:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 6433:             $changes{$action}{$newkey} = {
 6434:                 type => 'public',
 6435:                 time => {
 6436:                     start => $newstart,
 6437:                     end   => $newend,
 6438:                 },
 6439:             };
 6440:             my ($outcome,$deloutcome,$new_values,$translation) =
 6441:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 6442:             return $outcome;
 6443:         }
 6444:     } else {
 6445:         return 'invalid';
 6446:     }
 6447: }
 6448: 
 6449: #------------------------------------------------------Get Marked as Read Only
 6450: 
 6451: sub get_marked_as_readonly {
 6452:     my ($domain,$user,$what,$group) = @_;
 6453:     my $current_permissions = &get_portfile_permissions($domain,$user);
 6454:     my @readonly_files;
 6455:     my $cmp1=$what;
 6456:     if (ref($what)) { $cmp1=join('',@{$what}) };
 6457:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6458:         if (defined($group)) {
 6459:             if ($file_name !~ m-^\Q$group\E/-) {
 6460:                 next;
 6461:             }
 6462:         }
 6463:         if (ref($value) eq "ARRAY"){
 6464:             foreach my $stored_what (@{$value}) {
 6465:                 my $cmp2=$stored_what;
 6466:                 if (ref($stored_what) eq 'ARRAY') {
 6467:                     $cmp2=join('',@{$stored_what});
 6468:                 }
 6469:                 if ($cmp1 eq $cmp2) {
 6470:                     push(@readonly_files, $file_name);
 6471:                     last;
 6472:                 } elsif (!defined($what)) {
 6473:                     push(@readonly_files, $file_name);
 6474:                     last;
 6475:                 }
 6476:             }
 6477:         }
 6478:     }
 6479:     return @readonly_files;
 6480: }
 6481: #-----------------------------------------------------------Get Marked as Read Only Hash
 6482: 
 6483: sub get_marked_as_readonly_hash {
 6484:     my ($current_permissions,$group,$what) = @_;
 6485:     my %readonly_files;
 6486:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6487:         if (defined($group)) {
 6488:             if ($file_name !~ m-^\Q$group\E/-) {
 6489:                 next;
 6490:             }
 6491:         }
 6492:         if (ref($value) eq "ARRAY"){
 6493:             foreach my $stored_what (@{$value}) {
 6494:                 if (ref($stored_what) eq 'ARRAY') {
 6495:                     foreach my $lock_descriptor(@{$stored_what}) {
 6496:                         if ($lock_descriptor eq 'graded') {
 6497:                             $readonly_files{$file_name} = 'graded';
 6498:                         } elsif ($lock_descriptor eq 'handback') {
 6499:                             $readonly_files{$file_name} = 'handback';
 6500:                         } else {
 6501:                             if (!exists($readonly_files{$file_name})) {
 6502:                                 $readonly_files{$file_name} = 'locked';
 6503:                             }
 6504:                         }
 6505:                     }
 6506:                 } 
 6507:             }
 6508:         } 
 6509:     }
 6510:     return %readonly_files;
 6511: }
 6512: # ------------------------------------------------------------ Unmark as Read Only
 6513: 
 6514: sub unmark_as_readonly {
 6515:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 6516:     # for portfolio submissions, $what contains [$symb,$crsid] 
 6517:     my ($domain,$user,$what,$file_name,$group) = @_;
 6518:     $file_name = &declutter_portfile($file_name);
 6519:     my $symb_crs = $what;
 6520:     if (ref($what)) { $symb_crs=join('',@$what); }
 6521:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 6522:     my ($tmp)=keys(%current_permissions);
 6523:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6524:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 6525:     foreach my $file (@readonly_files) {
 6526: 	my $clean_file = &declutter_portfile($file);
 6527: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 6528: 	my $current_locks = $current_permissions{$file};
 6529:         my @new_locks;
 6530:         my @del_keys;
 6531:         if (ref($current_locks) eq "ARRAY"){
 6532:             foreach my $locker (@{$current_locks}) {
 6533:                 my $compare=$locker;
 6534:                 if (ref($locker) eq 'ARRAY') {
 6535:                     $compare=join('',@{$locker});
 6536:                     if ($compare ne $symb_crs) {
 6537:                         push(@new_locks, $locker);
 6538:                     }
 6539:                 }
 6540:             }
 6541:             if (scalar(@new_locks) > 0) {
 6542:                 $current_permissions{$file} = \@new_locks;
 6543:             } else {
 6544:                 push(@del_keys, $file);
 6545:                 &del('file_permissions',\@del_keys, $domain, $user);
 6546:                 delete($current_permissions{$file});
 6547:             }
 6548:         }
 6549:     }
 6550:     &put('file_permissions',\%current_permissions,$domain,$user);
 6551:     return;
 6552: }
 6553: 
 6554: # ------------------------------------------------------------ Directory lister
 6555: 
 6556: sub dirlist {
 6557:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 6558:     $uri=~s/^\///;
 6559:     $uri=~s/\/$//;
 6560:     my ($udom, $uname);
 6561:     if ($getuserdir) {
 6562:         $udom = $userdomain;
 6563:         $uname = $username;
 6564:     } else {
 6565:         (undef,$udom,$uname)=split(/\//,$uri);
 6566:         if(defined($userdomain)) {
 6567:             $udom = $userdomain;
 6568:         }
 6569:         if(defined($username)) {
 6570:             $uname = $username;
 6571:         }
 6572:     }
 6573:     my ($dirRoot,$listing,@listing_results);
 6574: 
 6575:     $dirRoot = $perlvar{'lonDocRoot'};
 6576:     if (defined($getpropath)) {
 6577:         $dirRoot = &propath($udom,$uname);
 6578:         $dirRoot =~ s/\/$//;
 6579:     } elsif (defined($getuserdir)) {
 6580:         my $subdir=$uname.'__';
 6581:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 6582:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 6583:                    ."/$udom/$subdir/$uname";
 6584:     } elsif (defined($alternateRoot)) {
 6585:         $dirRoot = $alternateRoot;
 6586:     }
 6587: 
 6588:     if($udom) {
 6589:         if($uname) {
 6590:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 6591:                               .$getuserdir.':'.&escape($dirRoot)
 6592:                               .':'.&escape($uname).':'.&escape($udom),
 6593:                               &homeserver($uname,$udom));
 6594:             if ($listing eq 'unknown_cmd') {
 6595:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 6596:                                   &homeserver($uname,$udom));
 6597:             } else {
 6598:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6599:             }
 6600:             if ($listing eq 'unknown_cmd') {
 6601:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 6602: 				  &homeserver($uname,$udom));
 6603:                 @listing_results = split(/:/,$listing);
 6604:             } else {
 6605:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6606:             }
 6607:             return @listing_results;
 6608:         } elsif(!$alternateRoot) {
 6609:             my %allusers;
 6610: 	    my %servers = &get_servers($udom,'library');
 6611:  	    foreach my $tryserver (keys(%servers)) {
 6612:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 6613:                                   &escape($udom),$tryserver);
 6614:                 if ($listing eq 'unknown_cmd') {
 6615: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 6616: 				      $udom, $tryserver);
 6617:                 } else {
 6618:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 6619:                 }
 6620: 		if ($listing eq 'unknown_cmd') {
 6621: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 6622: 				      $udom, $tryserver);
 6623: 		    @listing_results = split(/:/,$listing);
 6624: 		} else {
 6625: 		    @listing_results =
 6626: 			map { &unescape($_); } split(/:/,$listing);
 6627: 		}
 6628: 		if ($listing_results[0] ne 'no_such_dir' && 
 6629: 		    $listing_results[0] ne 'empty'       &&
 6630: 		    $listing_results[0] ne 'con_lost') {
 6631: 		    foreach my $line (@listing_results) {
 6632: 			my ($entry) = split(/&/,$line,2);
 6633: 			$allusers{$entry} = 1;
 6634: 		    }
 6635: 		}
 6636:             }
 6637:             my $alluserstr='';
 6638:             foreach my $user (sort(keys(%allusers))) {
 6639:                 $alluserstr.=$user.'&user:';
 6640:             }
 6641:             $alluserstr=~s/:$//;
 6642:             return split(/:/,$alluserstr);
 6643:         } else {
 6644:             return ('missing user name');
 6645:         }
 6646:     } elsif(!defined($getpropath)) {
 6647:         my @all_domains = sort(&all_domains());
 6648:         foreach my $domain (@all_domains) {
 6649:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 6650:         }
 6651:         return @all_domains;
 6652:     } else {
 6653:         return ('missing domain');
 6654:     }
 6655: }
 6656: 
 6657: # --------------------------------------------- GetFileTimestamp
 6658: # This function utilizes dirlist and returns the date stamp for
 6659: # when it was last modified.  It will also return an error of -1
 6660: # if an error occurs
 6661: 
 6662: sub GetFileTimestamp {
 6663:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 6664:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 6665:     $studentName   = &LONCAPA::clean_username($studentName);
 6666:     my ($fileStat) = 
 6667:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
 6668:                                  undef,$getuserdir);
 6669:     my @stats = split('&', $fileStat);
 6670:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6671:         # @stats contains first the filename, then the stat output
 6672:         return $stats[10]; # so this is 10 instead of 9.
 6673:     } else {
 6674:         return -1;
 6675:     }
 6676: }
 6677: 
 6678: sub stat_file {
 6679:     my ($uri) = @_;
 6680:     $uri = &clutter_with_no_wrapper($uri);
 6681: 
 6682:     my ($udom,$uname,$file);
 6683:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 6684: 	($udom,$uname,$file) =
 6685: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 6686: 	$file = 'userfiles/'.$file;
 6687:     }
 6688:     if ($uri =~ m-^/res/-) {
 6689: 	($udom,$uname) = 
 6690: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 6691: 	$file = $uri;
 6692:     }
 6693: 
 6694:     if (!$udom || !$uname || !$file) {
 6695: 	# unable to handle the uri
 6696: 	return ();
 6697:     }
 6698:     my $getpropath;
 6699:     if ($file =~ /^userfiles\//) {
 6700:         $getpropath = 1;
 6701:     }
 6702:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
 6703:     my @stats = split('&', $result);
 6704:     
 6705:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6706: 	shift(@stats); #filename is first
 6707: 	return @stats;
 6708:     }
 6709:     return ();
 6710: }
 6711: 
 6712: # -------------------------------------------------------- Value of a Condition
 6713: 
 6714: # gets the value of a specific preevaluated condition
 6715: #    stored in the string  $env{user.state.<cid>}
 6716: # or looks up a condition reference in the bighash and if if hasn't
 6717: # already been evaluated recurses into docondval to get the value of
 6718: # the condition, then memoizing it to 
 6719: #   $env{user.state.<cid>.<condition>}
 6720: sub directcondval {
 6721:     my $number=shift;
 6722:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 6723: 	&Apache::lonuserstate::evalstate();
 6724:     }
 6725:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 6726: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 6727:     } elsif ($number =~ /^_/) {
 6728: 	my $sub_condition;
 6729: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6730: 		&GDBM_READER(),0640)) {
 6731: 	    $sub_condition=$bighash{'conditions'.$number};
 6732: 	    untie(%bighash);
 6733: 	}
 6734: 	my $value = &docondval($sub_condition);
 6735: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 6736: 	return $value;
 6737:     }
 6738:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 6739:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 6740:     } else {
 6741:        return 2;
 6742:     }
 6743: }
 6744: 
 6745: # get the collection of conditions for this resource
 6746: sub condval {
 6747:     my $condidx=shift;
 6748:     my $allpathcond='';
 6749:     foreach my $cond (split(/\|/,$condidx)) {
 6750: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 6751: 	    $allpathcond.=
 6752: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 6753: 	}
 6754:     }
 6755:     $allpathcond=~s/\|$//;
 6756:     return &docondval($allpathcond);
 6757: }
 6758: 
 6759: #evaluates an expression of conditions
 6760: sub docondval {
 6761:     my ($allpathcond) = @_;
 6762:     my $result=0;
 6763:     if ($env{'request.course.id'}
 6764: 	&& defined($allpathcond)) {
 6765: 	my $operand='|';
 6766: 	my @stack;
 6767: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 6768: 	    if ($chunk eq '(') {
 6769: 		push @stack,($operand,$result);
 6770: 	    } elsif ($chunk eq ')') {
 6771: 		my $before=pop @stack;
 6772: 		if (pop @stack eq '&') {
 6773: 		    $result=$result>$before?$before:$result;
 6774: 		} else {
 6775: 		    $result=$result>$before?$result:$before;
 6776: 		}
 6777: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 6778: 		$operand=$chunk;
 6779: 	    } else {
 6780: 		my $new=directcondval($chunk);
 6781: 		if ($operand eq '&') {
 6782: 		    $result=$result>$new?$new:$result;
 6783: 		} else {
 6784: 		    $result=$result>$new?$result:$new;
 6785: 		}
 6786: 	    }
 6787: 	}
 6788:     }
 6789:     return $result;
 6790: }
 6791: 
 6792: # ---------------------------------------------------- Devalidate courseresdata
 6793: 
 6794: sub devalidatecourseresdata {
 6795:     my ($coursenum,$coursedomain)=@_;
 6796:     my $hashid=$coursenum.':'.$coursedomain;
 6797:     &devalidate_cache_new('courseres',$hashid);
 6798: }
 6799: 
 6800: 
 6801: # --------------------------------------------------- Course Resourcedata Query
 6802: #
 6803: #  Parameters:
 6804: #      $coursenum    - Number of the course.
 6805: #      $coursedomain - Domain at which the course was created.
 6806: #  Returns:
 6807: #     A hash of the course parameters along (I think) with timestamps
 6808: #     and version info.
 6809: 
 6810: sub get_courseresdata {
 6811:     my ($coursenum,$coursedomain)=@_;
 6812:     my $coursehom=&homeserver($coursenum,$coursedomain);
 6813:     my $hashid=$coursenum.':'.$coursedomain;
 6814:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 6815:     my %dumpreply;
 6816:     unless (defined($cached)) {
 6817: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 6818: 	$result=\%dumpreply;
 6819: 	my ($tmp) = keys(%dumpreply);
 6820: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6821: 	    &do_cache_new('courseres',$hashid,$result,600);
 6822: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 6823: 	    return $tmp;
 6824: 	} elsif ($tmp =~ /^(error)/) {
 6825: 	    $result=undef;
 6826: 	    &do_cache_new('courseres',$hashid,$result,600);
 6827: 	}
 6828:     }
 6829:     return $result;
 6830: }
 6831: 
 6832: sub devalidateuserresdata {
 6833:     my ($uname,$udom)=@_;
 6834:     my $hashid="$udom:$uname";
 6835:     &devalidate_cache_new('userres',$hashid);
 6836: }
 6837: 
 6838: sub get_userresdata {
 6839:     my ($uname,$udom)=@_;
 6840:     #most student don\'t have any data set, check if there is some data
 6841:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 6842: 
 6843:     my $hashid="$udom:$uname";
 6844:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 6845:     if (!defined($cached)) {
 6846: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 6847: 	$result=\%resourcedata;
 6848: 	&do_cache_new('userres',$hashid,$result,600);
 6849:     }
 6850:     my ($tmp)=keys(%$result);
 6851:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 6852: 	return $result;
 6853:     }
 6854:     #error 2 occurs when the .db doesn't exist
 6855:     if ($tmp!~/error: 2 /) {
 6856: 	&logthis("<font color=\"blue\">WARNING:".
 6857: 		 " Trying to get resource data for ".
 6858: 		 $uname." at ".$udom.": ".
 6859: 		 $tmp."</font>");
 6860:     } elsif ($tmp=~/error: 2 /) {
 6861: 	#&EXT_cache_set($udom,$uname);
 6862: 	&do_cache_new('userres',$hashid,undef,600);
 6863: 	undef($tmp); # not really an error so don't send it back
 6864:     }
 6865:     return $tmp;
 6866: }
 6867: #----------------------------------------------- resdata - return resource data
 6868: #  Purpose:
 6869: #    Return resource data for either users or for a course.
 6870: #  Parameters:
 6871: #     $name      - Course/user name.
 6872: #     $domain    - Name of the domain the user/course is registered on.
 6873: #     $type      - Type of thing $name is (must be 'course' or 'user'
 6874: #     @which     - Array of names of resources desired.
 6875: #  Returns:
 6876: #     The value of the first reasource in @which that is found in the
 6877: #     resource hash.
 6878: #  Exceptional Conditions:
 6879: #     If the $type passed in is not valid (not the string 'course' or 
 6880: #     'user', an undefined  reference is returned.
 6881: #     If none of the resources are found, an undef is returned
 6882: sub resdata {
 6883:     my ($name,$domain,$type,@which)=@_;
 6884:     my $result;
 6885:     if ($type eq 'course') {
 6886: 	$result=&get_courseresdata($name,$domain);
 6887:     } elsif ($type eq 'user') {
 6888: 	$result=&get_userresdata($name,$domain);
 6889:     }
 6890:     if (!ref($result)) { return $result; }    
 6891:     foreach my $item (@which) {
 6892: 	if (defined($result->{$item->[0]})) {
 6893: 	    return [$result->{$item->[0]},$item->[1]];
 6894: 	}
 6895:     }
 6896:     return undef;
 6897: }
 6898: 
 6899: #
 6900: # EXT resource caching routines
 6901: #
 6902: 
 6903: sub clear_EXT_cache_status {
 6904:     &delenv('cache.EXT.');
 6905: }
 6906: 
 6907: sub EXT_cache_status {
 6908:     my ($target_domain,$target_user) = @_;
 6909:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6910:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 6911:         # We know already the user has no data
 6912:         return 1;
 6913:     } else {
 6914:         return 0;
 6915:     }
 6916: }
 6917: 
 6918: sub EXT_cache_set {
 6919:     my ($target_domain,$target_user) = @_;
 6920:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6921:     #&appenv({$cachename => time});
 6922: }
 6923: 
 6924: # --------------------------------------------------------- Value of a Variable
 6925: sub EXT {
 6926: 
 6927:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 6928:     unless ($varname) { return ''; }
 6929:     #get real user name/domain, courseid and symb
 6930:     my $courseid;
 6931:     my $publicuser;
 6932:     if ($symbparm) {
 6933: 	$symbparm=&get_symb_from_alias($symbparm);
 6934:     }
 6935:     if (!($uname && $udom)) {
 6936:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 6937:       if (!$symbparm) {	$symbparm=$cursymb; }
 6938:     } else {
 6939: 	$courseid=$env{'request.course.id'};
 6940:     }
 6941:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 6942:     my $rest;
 6943:     if (defined($therest[0])) {
 6944:        $rest=join('.',@therest);
 6945:     } else {
 6946:        $rest='';
 6947:     }
 6948: 
 6949:     my $qualifierrest=$qualifier;
 6950:     if ($rest) { $qualifierrest.='.'.$rest; }
 6951:     my $spacequalifierrest=$space;
 6952:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 6953:     if ($realm eq 'user') {
 6954: # --------------------------------------------------------------- user.resource
 6955: 	if ($space eq 'resource') {
 6956: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 6957: 		  || defined($Apache::lonhomework::parsing_a_task))
 6958: 		 &&
 6959: 		 ($symbparm eq &symbread()) ) {	
 6960: 		# if we are in the middle of processing the resource the
 6961: 		# get the value we are planning on committing
 6962:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 6963:                     return $Apache::lonhomework::results{$qualifierrest};
 6964:                 } else {
 6965:                     return $Apache::lonhomework::history{$qualifierrest};
 6966:                 }
 6967: 	    } else {
 6968: 		my %restored;
 6969: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 6970: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 6971: 		} else {
 6972: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 6973: 		}
 6974: 		return $restored{$qualifierrest};
 6975: 	    }
 6976: # ----------------------------------------------------------------- user.access
 6977:         } elsif ($space eq 'access') {
 6978: 	    # FIXME - not supporting calls for a specific user
 6979:             return &allowed($qualifier,$rest);
 6980: # ------------------------------------------ user.preferences, user.environment
 6981:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 6982: 	    if (($uname eq $env{'user.name'}) &&
 6983: 		($udom eq $env{'user.domain'})) {
 6984: 		return $env{join('.',('environment',$qualifierrest))};
 6985: 	    } else {
 6986: 		my %returnhash;
 6987: 		if (!$publicuser) {
 6988: 		    %returnhash=&userenvironment($udom,$uname,
 6989: 						 $qualifierrest);
 6990: 		}
 6991: 		return $returnhash{$qualifierrest};
 6992: 	    }
 6993: # ----------------------------------------------------------------- user.course
 6994:         } elsif ($space eq 'course') {
 6995: 	    # FIXME - not supporting calls for a specific user
 6996:             return $env{join('.',('request.course',$qualifier))};
 6997: # ------------------------------------------------------------------- user.role
 6998:         } elsif ($space eq 'role') {
 6999: 	    # FIXME - not supporting calls for a specific user
 7000:             my ($role,$where)=split(/\./,$env{'request.role'});
 7001:             if ($qualifier eq 'value') {
 7002: 		return $role;
 7003:             } elsif ($qualifier eq 'extent') {
 7004:                 return $where;
 7005:             }
 7006: # ----------------------------------------------------------------- user.domain
 7007:         } elsif ($space eq 'domain') {
 7008:             return $udom;
 7009: # ------------------------------------------------------------------- user.name
 7010:         } elsif ($space eq 'name') {
 7011:             return $uname;
 7012: # ---------------------------------------------------- Any other user namespace
 7013:         } else {
 7014: 	    my %reply;
 7015: 	    if (!$publicuser) {
 7016: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 7017: 	    }
 7018: 	    return $reply{$qualifierrest};
 7019:         }
 7020:     } elsif ($realm eq 'query') {
 7021: # ---------------------------------------------- pull stuff out of query string
 7022:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 7023: 						[$spacequalifierrest]);
 7024: 	return $env{'form.'.$spacequalifierrest}; 
 7025:    } elsif ($realm eq 'request') {
 7026: # ------------------------------------------------------------- request.browser
 7027:         if ($space eq 'browser') {
 7028: 	    if ($qualifier eq 'textremote') {
 7029: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 7030: 		    return 1;
 7031: 		} else {
 7032: 		    return 0;
 7033: 		}
 7034: 	    } else {
 7035: 		return $env{'browser.'.$qualifier};
 7036: 	    }
 7037: # ------------------------------------------------------------ request.filename
 7038:         } else {
 7039:             return $env{'request.'.$spacequalifierrest};
 7040:         }
 7041:     } elsif ($realm eq 'course') {
 7042: # ---------------------------------------------------------- course.description
 7043:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 7044:     } elsif ($realm eq 'resource') {
 7045: 
 7046: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 7047: 	    if (!$symbparm) { $symbparm=&symbread(); }
 7048: 	}
 7049: 
 7050: 	if ($space eq 'title') {
 7051: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 7052: 	    return &gettitle($symbparm);
 7053: 	}
 7054: 	
 7055: 	if ($space eq 'map') {
 7056: 	    my ($map) = &decode_symb($symbparm);
 7057: 	    return &symbread($map);
 7058: 	}
 7059: 	if ($space eq 'filename') {
 7060: 	    if ($symbparm) {
 7061: 		return &clutter((&decode_symb($symbparm))[2]);
 7062: 	    }
 7063: 	    return &hreflocation('',$env{'request.filename'});
 7064: 	}
 7065: 
 7066: 	my ($section, $group, @groups);
 7067: 	my ($courselevelm,$courselevel);
 7068: 	if ($symbparm && defined($courseid) && 
 7069: 	    $courseid eq $env{'request.course.id'}) {
 7070: 
 7071: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 7072: 
 7073: # ----------------------------------------------------- Cascading lookup scheme
 7074: 	    my $symbp=$symbparm;
 7075: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 7076: 
 7077: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 7078: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 7079: 
 7080: 	    if (($env{'user.name'} eq $uname) &&
 7081: 		($env{'user.domain'} eq $udom)) {
 7082: 		$section=$env{'request.course.sec'};
 7083:                 @groups = split(/:/,$env{'request.course.groups'});  
 7084:                 @groups=&sort_course_groups($courseid,@groups); 
 7085: 	    } else {
 7086: 		if (! defined($usection)) {
 7087: 		    $section=&getsection($udom,$uname,$courseid);
 7088: 		} else {
 7089: 		    $section = $usection;
 7090: 		}
 7091:                 @groups = &get_users_groups($udom,$uname,$courseid);
 7092: 	    }
 7093: 
 7094: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 7095: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 7096: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 7097: 
 7098: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 7099: 	    my $courselevelr=$courseid.'.'.$symbparm;
 7100: 	    $courselevelm=$courseid.'.'.$mapparm;
 7101: 
 7102: # ----------------------------------------------------------- first, check user
 7103: 
 7104: 	    my $userreply=&resdata($uname,$udom,'user',
 7105: 				       ([$courselevelr,'resource'],
 7106: 					[$courselevelm,'map'     ],
 7107: 					[$courselevel, 'course'  ]));
 7108: 	    if (defined($userreply)) { return &get_reply($userreply); }
 7109: 
 7110: # ------------------------------------------------ second, check some of course
 7111:             my $coursereply;
 7112:             if (@groups > 0) {
 7113:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 7114:                                        $mapparm,$spacequalifierrest);
 7115:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 7116:             }
 7117: 
 7118: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7119: 				  $env{'course.'.$courseid.'.domain'},
 7120: 				  'course',
 7121: 				  ([$seclevelr,   'resource'],
 7122: 				   [$seclevelm,   'map'     ],
 7123: 				   [$seclevel,    'course'  ],
 7124: 				   [$courselevelr,'resource']));
 7125: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7126: 
 7127: # ------------------------------------------------------ third, check map parms
 7128: 	    my %parmhash=();
 7129: 	    my $thisparm='';
 7130: 	    if (tie(%parmhash,'GDBM_File',
 7131: 		    $env{'request.course.fn'}.'_parms.db',
 7132: 		    &GDBM_READER(),0640)) {
 7133: 		$thisparm=$parmhash{$symbparm};
 7134: 		untie(%parmhash);
 7135: 	    }
 7136: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 7137: 	}
 7138: # ------------------------------------------ fourth, look in resource metadata
 7139: 
 7140: 	$spacequalifierrest=~s/\./\_/;
 7141: 	my $filename;
 7142: 	if (!$symbparm) { $symbparm=&symbread(); }
 7143: 	if ($symbparm) {
 7144: 	    $filename=(&decode_symb($symbparm))[2];
 7145: 	} else {
 7146: 	    $filename=$env{'request.filename'};
 7147: 	}
 7148: 	my $metadata=&metadata($filename,$spacequalifierrest);
 7149: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7150: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 7151: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7152: 
 7153: # ---------------------------------------------- fourth, look in rest of course
 7154: 	if ($symbparm && defined($courseid) && 
 7155: 	    $courseid eq $env{'request.course.id'}) {
 7156: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7157: 				     $env{'course.'.$courseid.'.domain'},
 7158: 				     'course',
 7159: 				     ([$courselevelm,'map'   ],
 7160: 				      [$courselevel, 'course']));
 7161: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7162: 	}
 7163: # ------------------------------------------------------------------ Cascade up
 7164: 	unless ($space eq '0') {
 7165: 	    my @parts=split(/_/,$space);
 7166: 	    my $id=pop(@parts);
 7167: 	    my $part=join('_',@parts);
 7168: 	    if ($part eq '') { $part='0'; }
 7169: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 7170: 				 $symbparm,$udom,$uname,$section,1);
 7171: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 7172: 	}
 7173: 	if ($recurse) { return undef; }
 7174: 	my $pack_def=&packages_tab_default($filename,$varname);
 7175: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 7176: # ---------------------------------------------------- Any other user namespace
 7177:     } elsif ($realm eq 'environment') {
 7178: # ----------------------------------------------------------------- environment
 7179: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 7180: 	    return $env{'environment.'.$spacequalifierrest};
 7181: 	} else {
 7182: 	    if ($uname eq 'anonymous' && $udom eq '') {
 7183: 		return '';
 7184: 	    }
 7185: 	    my %returnhash=&userenvironment($udom,$uname,
 7186: 					    $spacequalifierrest);
 7187: 	    return $returnhash{$spacequalifierrest};
 7188: 	}
 7189:     } elsif ($realm eq 'system') {
 7190: # ----------------------------------------------------------------- system.time
 7191: 	if ($space eq 'time') {
 7192: 	    return time;
 7193:         }
 7194:     } elsif ($realm eq 'server') {
 7195: # ----------------------------------------------------------------- system.time
 7196: 	if ($space eq 'name') {
 7197: 	    return $ENV{'SERVER_NAME'};
 7198:         }
 7199:     }
 7200:     return '';
 7201: }
 7202: 
 7203: sub get_reply {
 7204:     my ($reply_value) = @_;
 7205:     if (ref($reply_value) eq 'ARRAY') {
 7206:         if (wantarray) {
 7207: 	    return @$reply_value;
 7208:         }
 7209:         return $reply_value->[0];
 7210:     } else {
 7211:         return $reply_value;
 7212:     }
 7213: }
 7214: 
 7215: sub check_group_parms {
 7216:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 7217:     my @groupitems = ();
 7218:     my $resultitem;
 7219:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 7220:     foreach my $group (@{$groups}) {
 7221:         foreach my $level (@levels) {
 7222:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 7223:              push(@groupitems,[$item,$level->[1]]);
 7224:         }
 7225:     }
 7226:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 7227:                             $env{'course.'.$courseid.'.domain'},
 7228:                                      'course',@groupitems);
 7229:     return $coursereply;
 7230: }
 7231: 
 7232: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 7233:     my ($courseid,@groups) = @_;
 7234:     @groups = sort(@groups);
 7235:     return @groups;
 7236: }
 7237: 
 7238: sub packages_tab_default {
 7239:     my ($uri,$varname)=@_;
 7240:     my (undef,$part,$name)=split(/\./,$varname);
 7241: 
 7242:     my (@extension,@specifics,$do_default);
 7243:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 7244: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 7245: 	if ($pack_type eq 'default') {
 7246: 	    $do_default=1;
 7247: 	} elsif ($pack_type eq 'extension') {
 7248: 	    push(@extension,[$package,$pack_type,$pack_part]);
 7249: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 7250: 	    # only look at packages defaults for packages that this id is
 7251: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 7252: 	}
 7253:     }
 7254:     # first look for a package that matches the requested part id
 7255:     foreach my $package (@specifics) {
 7256: 	my (undef,$pack_type,$pack_part)=@{$package};
 7257: 	next if ($pack_part ne $part);
 7258: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7259: 	    return $packagetab{"$pack_type&$name&default"};
 7260: 	}
 7261:     }
 7262:     # look for any possible matching non extension_ package
 7263:     foreach my $package (@specifics) {
 7264: 	my (undef,$pack_type,$pack_part)=@{$package};
 7265: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7266: 	    return $packagetab{"$pack_type&$name&default"};
 7267: 	}
 7268: 	if ($pack_type eq 'part') { $pack_part='0'; }
 7269: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 7270: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 7271: 	}
 7272:     }
 7273:     # look for any posible extension_ match
 7274:     foreach my $package (@extension) {
 7275: 	my ($package,$pack_type)=@{$package};
 7276: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7277: 	    return $packagetab{"$pack_type&$name&default"};
 7278: 	}
 7279: 	if (defined($packagetab{$package."&$name&default"})) {
 7280: 	    return $packagetab{$package."&$name&default"};
 7281: 	}
 7282:     }
 7283:     # look for a global default setting
 7284:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 7285: 	return $packagetab{"default&$name&default"};
 7286:     }
 7287:     return undef;
 7288: }
 7289: 
 7290: sub add_prefix_and_part {
 7291:     my ($prefix,$part)=@_;
 7292:     my $keyroot;
 7293:     if (defined($prefix) && $prefix !~ /^__/) {
 7294: 	# prefix that has a part already
 7295: 	$keyroot=$prefix;
 7296:     } elsif (defined($prefix)) {
 7297: 	# prefix that is missing a part
 7298: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 7299:     } else {
 7300: 	# no prefix at all
 7301: 	if (defined($part)) { $keyroot='_'.$part; }
 7302:     }
 7303:     return $keyroot;
 7304: }
 7305: 
 7306: # ---------------------------------------------------------------- Get metadata
 7307: 
 7308: my %metaentry;
 7309: sub metadata {
 7310:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 7311:     $uri=&declutter($uri);
 7312:     # if it is a non metadata possible uri return quickly
 7313:     if (($uri eq '') || 
 7314: 	(($uri =~ m|^/*adm/|) && 
 7315: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 7316:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 7317: 	return undef;
 7318:     }
 7319:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 7320: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 7321: 	return undef;
 7322:     }
 7323:     my $filename=$uri;
 7324:     $uri=~s/\.meta$//;
 7325: #
 7326: # Is the metadata already cached?
 7327: # Look at timestamp of caching
 7328: # Everything is cached by the main uri, libraries are never directly cached
 7329: #
 7330:     if (!defined($liburi)) {
 7331: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 7332: 	if (defined($cached)) { return $result->{':'.$what}; }
 7333:     }
 7334:     {
 7335: #
 7336: # Is this a recursive call for a library?
 7337: #
 7338: #	if (! exists($metacache{$uri})) {
 7339: #	    $metacache{$uri}={};
 7340: #	}
 7341: 	my $cachetime = 60*60;
 7342:         if ($liburi) {
 7343: 	    $liburi=&declutter($liburi);
 7344:             $filename=$liburi;
 7345:         } else {
 7346: 	    &devalidate_cache_new('meta',$uri);
 7347: 	    undef(%metaentry);
 7348: 	}
 7349:         my %metathesekeys=();
 7350:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 7351: 	my $metastring;
 7352: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 7353: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 7354: 	    $metastring = 
 7355: 		&Apache::lonnet::ssi_body($which,
 7356: 					  ('grade_target' => 'meta'));
 7357: 	    $cachetime = 1; # only want this cached in the child not long term
 7358: 	} elsif ($uri !~ m -^(editupload)/-) {
 7359: 	    my $file=&filelocation('',&clutter($filename));
 7360: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 7361: 	    $metastring=&getfile($file);
 7362: 	}
 7363:         my $parser=HTML::LCParser->new(\$metastring);
 7364:         my $token;
 7365:         undef %metathesekeys;
 7366:         while ($token=$parser->get_token) {
 7367: 	    if ($token->[0] eq 'S') {
 7368: 		if (defined($token->[2]->{'package'})) {
 7369: #
 7370: # This is a package - get package info
 7371: #
 7372: 		    my $package=$token->[2]->{'package'};
 7373: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7374: 		    if (defined($token->[2]->{'id'})) { 
 7375: 			$keyroot.='_'.$token->[2]->{'id'}; 
 7376: 		    }
 7377: 		    if ($metaentry{':packages'}) {
 7378: 			$metaentry{':packages'}.=','.$package.$keyroot;
 7379: 		    } else {
 7380: 			$metaentry{':packages'}=$package.$keyroot;
 7381: 		    }
 7382: 		    foreach my $pack_entry (keys(%packagetab)) {
 7383: 			my $part=$keyroot;
 7384: 			$part=~s/^\_//;
 7385: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 7386: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 7387: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 7388: 			    # ignore package.tab specified default values
 7389:                             # here &package_tab_default() will fetch those
 7390: 			    if ($subp eq 'default') { next; }
 7391: 			    my $value=$packagetab{$pack_entry};
 7392: 			    my $unikey;
 7393: 			    if ($pack =~ /_0$/) {
 7394: 				$unikey='parameter_0_'.$name;
 7395: 				$part=0;
 7396: 			    } else {
 7397: 				$unikey='parameter'.$keyroot.'_'.$name;
 7398: 			    }
 7399: 			    if ($subp eq 'display') {
 7400: 				$value.=' [Part: '.$part.']';
 7401: 			    }
 7402: 			    $metaentry{':'.$unikey.'.part'}=$part;
 7403: 			    $metathesekeys{$unikey}=1;
 7404: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7405: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 7406: 			    }
 7407: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 7408: 				$metaentry{':'.$unikey}=
 7409: 				    $metaentry{':'.$unikey.'.default'};
 7410: 			    }
 7411: 			}
 7412: 		    }
 7413: 		} else {
 7414: #
 7415: # This is not a package - some other kind of start tag
 7416: #
 7417: 		    my $entry=$token->[1];
 7418: 		    my $unikey;
 7419: 		    if ($entry eq 'import') {
 7420: 			$unikey='';
 7421: 		    } else {
 7422: 			$unikey=$entry;
 7423: 		    }
 7424: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7425: 
 7426: 		    if (defined($token->[2]->{'id'})) { 
 7427: 			$unikey.='_'.$token->[2]->{'id'}; 
 7428: 		    }
 7429: 
 7430: 		    if ($entry eq 'import') {
 7431: #
 7432: # Importing a library here
 7433: #
 7434: 			if ($depthcount<20) {
 7435: 			    my $location=$parser->get_text('/import');
 7436: 			    my $dir=$filename;
 7437: 			    $dir=~s|[^/]*$||;
 7438: 			    $location=&filelocation($dir,$location);
 7439: 			    my $metadata = 
 7440: 				&metadata($uri,'keys', $location,$unikey,
 7441: 					  $depthcount+1);
 7442: 			    foreach my $meta (split(',',$metadata)) {
 7443: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 7444: 				$metathesekeys{$meta}=1;
 7445: 			    }
 7446: 			}
 7447: 		    } else { 
 7448: 			
 7449: 			if (defined($token->[2]->{'name'})) { 
 7450: 			    $unikey.='_'.$token->[2]->{'name'}; 
 7451: 			}
 7452: 			$metathesekeys{$unikey}=1;
 7453: 			foreach my $param (@{$token->[3]}) {
 7454: 			    $metaentry{':'.$unikey.'.'.$param} =
 7455: 				$token->[2]->{$param};
 7456: 			}
 7457: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 7458: 			my $default=$metaentry{':'.$unikey.'.default'};
 7459: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 7460: 		 # only ws inside the tag, and not in default, so use default
 7461: 		 # as value
 7462: 			    $metaentry{':'.$unikey}=$default;
 7463: 			} elsif ( $internaltext =~ /\S/ ) {
 7464: 		  # something interesting inside the tag
 7465: 			    $metaentry{':'.$unikey}=$internaltext;
 7466: 			} else {
 7467: 		  # no interesting values, don't set a default
 7468: 			}
 7469: # end of not-a-package not-a-library import
 7470: 		    }
 7471: # end of not-a-package start tag
 7472: 		}
 7473: # the next is the end of "start tag"
 7474: 	    }
 7475: 	}
 7476: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 7477: 	$extension = lc($extension);
 7478: 	if ($extension eq 'htm') { $extension='html'; }
 7479: 
 7480: 	foreach my $key (keys(%packagetab)) {
 7481: 	    #no specific packages #how's our extension
 7482: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 7483: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 7484: 					 \%metathesekeys);
 7485: 	}
 7486: 
 7487: 	if (!exists($metaentry{':packages'})
 7488: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 7489: 	    foreach my $key (keys(%packagetab)) {
 7490: 		#no specific packages well let's get default then
 7491: 		if ($key!~/^default&/) { next; }
 7492: 		&metadata_create_package_def($uri,$key,'default',
 7493: 					     \%metathesekeys);
 7494: 	    }
 7495: 	}
 7496: # are there custom rights to evaluate
 7497: 	if ($metaentry{':copyright'} eq 'custom') {
 7498: 
 7499:     #
 7500:     # Importing a rights file here
 7501:     #
 7502: 	    unless ($depthcount) {
 7503: 		my $location=$metaentry{':customdistributionfile'};
 7504: 		my $dir=$filename;
 7505: 		$dir=~s|[^/]*$||;
 7506: 		$location=&filelocation($dir,$location);
 7507: 		my $rights_metadata =
 7508: 		    &metadata($uri,'keys',$location,'_rights',
 7509: 			      $depthcount+1);
 7510: 		foreach my $rights (split(',',$rights_metadata)) {
 7511: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 7512: 		    $metathesekeys{$rights}=1;
 7513: 		}
 7514: 	    }
 7515: 	}
 7516: 	# uniqifiy package listing
 7517: 	my %seen;
 7518: 	my @uniq_packages =
 7519: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 7520: 	$metaentry{':packages'} = join(',',@uniq_packages);
 7521: 
 7522: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 7523: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 7524: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 7525: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 7526: # this is the end of "was not already recently cached
 7527:     }
 7528:     return $metaentry{':'.$what};
 7529: }
 7530: 
 7531: sub metadata_create_package_def {
 7532:     my ($uri,$key,$package,$metathesekeys)=@_;
 7533:     my ($pack,$name,$subp)=split(/\&/,$key);
 7534:     if ($subp eq 'default') { next; }
 7535:     
 7536:     if (defined($metaentry{':packages'})) {
 7537: 	$metaentry{':packages'}.=','.$package;
 7538:     } else {
 7539: 	$metaentry{':packages'}=$package;
 7540:     }
 7541:     my $value=$packagetab{$key};
 7542:     my $unikey;
 7543:     $unikey='parameter_0_'.$name;
 7544:     $metaentry{':'.$unikey.'.part'}=0;
 7545:     $$metathesekeys{$unikey}=1;
 7546:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7547: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 7548:     }
 7549:     if (defined($metaentry{':'.$unikey.'.default'})) {
 7550: 	$metaentry{':'.$unikey}=
 7551: 	    $metaentry{':'.$unikey.'.default'};
 7552:     }
 7553: }
 7554: 
 7555: sub metadata_generate_part0 {
 7556:     my ($metadata,$metacache,$uri) = @_;
 7557:     my %allnames;
 7558:     foreach my $metakey (keys(%$metadata)) {
 7559: 	if ($metakey=~/^parameter\_(.*)/) {
 7560: 	  my $part=$$metacache{':'.$metakey.'.part'};
 7561: 	  my $name=$$metacache{':'.$metakey.'.name'};
 7562: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 7563: 	    $allnames{$name}=$part;
 7564: 	  }
 7565: 	}
 7566:     }
 7567:     foreach my $name (keys(%allnames)) {
 7568:       $$metadata{"parameter_0_$name"}=1;
 7569:       my $key=":parameter_0_$name";
 7570:       $$metacache{"$key.part"}='0';
 7571:       $$metacache{"$key.name"}=$name;
 7572:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 7573: 					   $allnames{$name}.'_'.$name.
 7574: 					   '.type'};
 7575:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 7576: 			     '.display'};
 7577:       my $expr='[Part: '.$allnames{$name}.']';
 7578:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 7579:       $$metacache{"$key.display"}=$olddis;
 7580:     }
 7581: }
 7582: 
 7583: # ------------------------------------------------------ Devalidate title cache
 7584: 
 7585: sub devalidate_title_cache {
 7586:     my ($url)=@_;
 7587:     if (!$env{'request.course.id'}) { return; }
 7588:     my $symb=&symbread($url);
 7589:     if (!$symb) { return; }
 7590:     my $key=$env{'request.course.id'}."\0".$symb;
 7591:     &devalidate_cache_new('title',$key);
 7592: }
 7593: 
 7594: # ------------------------------------------------- Get the title of a resource
 7595: 
 7596: sub gettitle {
 7597:     my $urlsymb=shift;
 7598:     my $symb=&symbread($urlsymb);
 7599:     if ($symb) {
 7600: 	my $key=$env{'request.course.id'}."\0".$symb;
 7601: 	my ($result,$cached)=&is_cached_new('title',$key);
 7602: 	if (defined($cached)) { 
 7603: 	    return $result;
 7604: 	}
 7605: 	my ($map,$resid,$url)=&decode_symb($symb);
 7606: 	my $title='';
 7607: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 7608: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 7609: 	} else {
 7610: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7611: 		    &GDBM_READER(),0640)) {
 7612: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 7613: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 7614: 		untie(%bighash);
 7615: 	    }
 7616: 	}
 7617: 	$title=~s/\&colon\;/\:/gs;
 7618: 	if ($title) {
 7619: 	    return &do_cache_new('title',$key,$title,600);
 7620: 	}
 7621: 	$urlsymb=$url;
 7622:     }
 7623:     my $title=&metadata($urlsymb,'title');
 7624:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 7625:     return $title;
 7626: }
 7627: 
 7628: sub get_slot {
 7629:     my ($which,$cnum,$cdom)=@_;
 7630:     if (!$cnum || !$cdom) {
 7631: 	(undef,my $courseid)=&whichuser();
 7632: 	$cdom=$env{'course.'.$courseid.'.domain'};
 7633: 	$cnum=$env{'course.'.$courseid.'.num'};
 7634:     }
 7635:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 7636:     my %slotinfo;
 7637:     if (exists($remembered{$key})) {
 7638: 	$slotinfo{$which} = $remembered{$key};
 7639:     } else {
 7640: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 7641: 	&Apache::lonhomework::showhash(%slotinfo);
 7642: 	my ($tmp)=keys(%slotinfo);
 7643: 	if ($tmp=~/^error:/) { return (); }
 7644: 	$remembered{$key} = $slotinfo{$which};
 7645:     }
 7646:     if (ref($slotinfo{$which}) eq 'HASH') {
 7647: 	return %{$slotinfo{$which}};
 7648:     }
 7649:     return $slotinfo{$which};
 7650: }
 7651: # ------------------------------------------------- Update symbolic store links
 7652: 
 7653: sub symblist {
 7654:     my ($mapname,%newhash)=@_;
 7655:     $mapname=&deversion(&declutter($mapname));
 7656:     my %hash;
 7657:     if (($env{'request.course.fn'}) && (%newhash)) {
 7658:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7659:                       &GDBM_WRCREAT(),0640)) {
 7660: 	    foreach my $url (keys %newhash) {
 7661: 		next if ($url eq 'last_known'
 7662: 			 && $env{'form.no_update_last_known'});
 7663: 		$hash{declutter($url)}=&encode_symb($mapname,
 7664: 						    $newhash{$url}->[1],
 7665: 						    $newhash{$url}->[0]);
 7666:             }
 7667:             if (untie(%hash)) {
 7668: 		return 'ok';
 7669:             }
 7670:         }
 7671:     }
 7672:     return 'error';
 7673: }
 7674: 
 7675: # --------------------------------------------------------------- Verify a symb
 7676: 
 7677: sub symbverify {
 7678:     my ($symb,$thisurl)=@_;
 7679:     my $thisfn=$thisurl;
 7680:     $thisfn=&declutter($thisfn);
 7681: # direct jump to resource in page or to a sequence - will construct own symbs
 7682:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 7683: # check URL part
 7684:     my ($map,$resid,$url)=&decode_symb($symb);
 7685: 
 7686:     unless ($url eq $thisfn) { return 0; }
 7687: 
 7688:     $symb=&symbclean($symb);
 7689:     $thisurl=&deversion($thisurl);
 7690:     $thisfn=&deversion($thisfn);
 7691: 
 7692:     my %bighash;
 7693:     my $okay=0;
 7694: 
 7695:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7696:                             &GDBM_READER(),0640)) {
 7697:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 7698:         unless ($ids) { 
 7699:            $ids=$bighash{'ids_/'.$thisurl};
 7700:         }
 7701:         if ($ids) {
 7702: # ------------------------------------------------------------------- Has ID(s)
 7703: 	    foreach my $id (split(/\,/,$ids)) {
 7704: 	       my ($mapid,$resid)=split(/\./,$id);
 7705:                if (
 7706:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 7707:    eq $symb) { 
 7708: 		   if (($env{'request.role.adv'}) ||
 7709: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 7710: 		       $okay=1; 
 7711: 		   }
 7712: 	       }
 7713: 	   }
 7714:         }
 7715: 	untie(%bighash);
 7716:     }
 7717:     return $okay;
 7718: }
 7719: 
 7720: # --------------------------------------------------------------- Clean-up symb
 7721: 
 7722: sub symbclean {
 7723:     my $symb=shift;
 7724:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7725: # remove version from map
 7726:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 7727: 
 7728: # remove version from URL
 7729:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 7730: 
 7731: # remove wrapper
 7732: 
 7733:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 7734:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 7735:     return $symb;
 7736: }
 7737: 
 7738: # ---------------------------------------------- Split symb to find map and url
 7739: 
 7740: sub encode_symb {
 7741:     my ($map,$resid,$url)=@_;
 7742:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 7743: }
 7744: 
 7745: sub decode_symb {
 7746:     my $symb=shift;
 7747:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7748:     my ($map,$resid,$url)=split(/___/,$symb);
 7749:     return (&fixversion($map),$resid,&fixversion($url));
 7750: }
 7751: 
 7752: sub fixversion {
 7753:     my $fn=shift;
 7754:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 7755:     my %bighash;
 7756:     my $uri=&clutter($fn);
 7757:     my $key=$env{'request.course.id'}.'_'.$uri;
 7758: # is this cached?
 7759:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 7760:     if (defined($cached)) { return $result; }
 7761: # unfortunately not cached, or expired
 7762:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7763: 	    &GDBM_READER(),0640)) {
 7764:  	if ($bighash{'version_'.$uri}) {
 7765:  	    my $version=$bighash{'version_'.$uri};
 7766:  	    unless (($version eq 'mostrecent') || 
 7767: 		    ($version==&getversion($uri))) {
 7768:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 7769:  	    }
 7770:  	}
 7771:  	untie %bighash;
 7772:     }
 7773:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 7774: }
 7775: 
 7776: sub deversion {
 7777:     my $url=shift;
 7778:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 7779:     return $url;
 7780: }
 7781: 
 7782: # ------------------------------------------------------ Return symb list entry
 7783: 
 7784: sub symbread {
 7785:     my ($thisfn,$donotrecurse)=@_;
 7786:     my $cache_str='request.symbread.cached.'.$thisfn;
 7787:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 7788: # no filename provided? try from environment
 7789:     unless ($thisfn) {
 7790:         if ($env{'request.symb'}) {
 7791: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 7792: 	}
 7793: 	$thisfn=$env{'request.filename'};
 7794:     }
 7795:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7796: # is that filename actually a symb? Verify, clean, and return
 7797:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 7798: 	if (&symbverify($thisfn,$1)) {
 7799: 	    return $env{$cache_str}=&symbclean($thisfn);
 7800: 	}
 7801:     }
 7802:     $thisfn=declutter($thisfn);
 7803:     my %hash;
 7804:     my %bighash;
 7805:     my $syval='';
 7806:     if (($env{'request.course.fn'}) && ($thisfn)) {
 7807:         my $targetfn = $thisfn;
 7808:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 7809:             $targetfn = 'adm/wrapper/'.$thisfn;
 7810:         }
 7811: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 7812: 	    $targetfn=$1;
 7813: 	}
 7814:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7815:                       &GDBM_READER(),0640)) {
 7816: 	    $syval=$hash{$targetfn};
 7817:             untie(%hash);
 7818:         }
 7819: # ---------------------------------------------------------- There was an entry
 7820:         if ($syval) {
 7821: 	    #unless ($syval=~/\_\d+$/) {
 7822: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 7823: 		    #&appenv({'request.ambiguous' => $thisfn});
 7824: 		    #return $env{$cache_str}='';
 7825: 		#}    
 7826: 		#$syval.=$1;
 7827: 	    #}
 7828:         } else {
 7829: # ------------------------------------------------------- Was not in symb table
 7830:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7831:                             &GDBM_READER(),0640)) {
 7832: # ---------------------------------------------- Get ID(s) for current resource
 7833:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 7834:               unless ($ids) { 
 7835:                  $ids=$bighash{'ids_/'.$thisfn};
 7836:               }
 7837:               unless ($ids) {
 7838: # alias?
 7839: 		  $ids=$bighash{'mapalias_'.$thisfn};
 7840:               }
 7841:               if ($ids) {
 7842: # ------------------------------------------------------------------- Has ID(s)
 7843:                  my @possibilities=split(/\,/,$ids);
 7844:                  if ($#possibilities==0) {
 7845: # ----------------------------------------------- There is only one possibility
 7846: 		     my ($mapid,$resid)=split(/\./,$ids);
 7847: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7848: 						    $resid,$thisfn);
 7849:                  } elsif (!$donotrecurse) {
 7850: # ------------------------------------------ There is more than one possibility
 7851:                      my $realpossible=0;
 7852:                      foreach my $id (@possibilities) {
 7853: 			 my $file=$bighash{'src_'.$id};
 7854:                          if (&allowed('bre',$file)) {
 7855:          		    my ($mapid,$resid)=split(/\./,$id);
 7856:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 7857: 				$realpossible++;
 7858:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7859: 						    $resid,$thisfn);
 7860:                             }
 7861: 			 }
 7862:                      }
 7863: 		     if ($realpossible!=1) { $syval=''; }
 7864:                  } else {
 7865:                      $syval='';
 7866:                  }
 7867: 	      }
 7868:               untie(%bighash)
 7869:            }
 7870:         }
 7871:         if ($syval) {
 7872: 	    return $env{$cache_str}=$syval;
 7873:         }
 7874:     }
 7875:     &appenv({'request.ambiguous' => $thisfn});
 7876:     return $env{$cache_str}='';
 7877: }
 7878: 
 7879: # ---------------------------------------------------------- Return random seed
 7880: 
 7881: sub numval {
 7882:     my $txt=shift;
 7883:     $txt=~tr/A-J/0-9/;
 7884:     $txt=~tr/a-j/0-9/;
 7885:     $txt=~tr/K-T/0-9/;
 7886:     $txt=~tr/k-t/0-9/;
 7887:     $txt=~tr/U-Z/0-5/;
 7888:     $txt=~tr/u-z/0-5/;
 7889:     $txt=~s/\D//g;
 7890:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 7891:     return int($txt);
 7892: }
 7893: 
 7894: sub numval2 {
 7895:     my $txt=shift;
 7896:     $txt=~tr/A-J/0-9/;
 7897:     $txt=~tr/a-j/0-9/;
 7898:     $txt=~tr/K-T/0-9/;
 7899:     $txt=~tr/k-t/0-9/;
 7900:     $txt=~tr/U-Z/0-5/;
 7901:     $txt=~tr/u-z/0-5/;
 7902:     $txt=~s/\D//g;
 7903:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7904:     my $total;
 7905:     foreach my $val (@txts) { $total+=$val; }
 7906:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 7907:     return int($total);
 7908: }
 7909: 
 7910: sub numval3 {
 7911:     use integer;
 7912:     my $txt=shift;
 7913:     $txt=~tr/A-J/0-9/;
 7914:     $txt=~tr/a-j/0-9/;
 7915:     $txt=~tr/K-T/0-9/;
 7916:     $txt=~tr/k-t/0-9/;
 7917:     $txt=~tr/U-Z/0-5/;
 7918:     $txt=~tr/u-z/0-5/;
 7919:     $txt=~s/\D//g;
 7920:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7921:     my $total;
 7922:     foreach my $val (@txts) { $total+=$val; }
 7923:     if ($_64bit) { $total=(($total<<32)>>32); }
 7924:     return $total;
 7925: }
 7926: 
 7927: sub digest {
 7928:     my ($data)=@_;
 7929:     my $digest=&Digest::MD5::md5($data);
 7930:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 7931:     my ($e,$f);
 7932:     {
 7933:         use integer;
 7934:         $e=($a+$b);
 7935:         $f=($c+$d);
 7936:         if ($_64bit) {
 7937:             $e=(($e<<32)>>32);
 7938:             $f=(($f<<32)>>32);
 7939:         }
 7940:     }
 7941:     if (wantarray) {
 7942: 	return ($e,$f);
 7943:     } else {
 7944: 	my $g;
 7945: 	{
 7946: 	    use integer;
 7947: 	    $g=($e+$f);
 7948: 	    if ($_64bit) {
 7949: 		$g=(($g<<32)>>32);
 7950: 	    }
 7951: 	}
 7952: 	return $g;
 7953:     }
 7954: }
 7955: 
 7956: sub latest_rnd_algorithm_id {
 7957:     return '64bit5';
 7958: }
 7959: 
 7960: sub get_rand_alg {
 7961:     my ($courseid)=@_;
 7962:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 7963:     if ($courseid) {
 7964: 	return $env{"course.$courseid.rndseed"};
 7965:     }
 7966:     return &latest_rnd_algorithm_id();
 7967: }
 7968: 
 7969: sub validCODE {
 7970:     my ($CODE)=@_;
 7971:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 7972:     return 0;
 7973: }
 7974: 
 7975: sub getCODE {
 7976:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 7977:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 7978: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 7979: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 7980: 	return $Apache::lonhomework::history{'resource.CODE'};
 7981:     }
 7982:     return undef;
 7983: }
 7984: 
 7985: sub rndseed {
 7986:     my ($symb,$courseid,$domain,$username)=@_;
 7987:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 7988:     if (!defined($symb)) {
 7989: 	unless ($symb=$wsymb) { return time; }
 7990:     }
 7991:     if (!$courseid) { $courseid=$wcourseid; }
 7992:     if (!$domain) { $domain=$wdomain; }
 7993:     if (!$username) { $username=$wusername }
 7994:     my $which=&get_rand_alg();
 7995: 
 7996:     if (defined(&getCODE())) {
 7997: 	if ($which eq '64bit5') {
 7998: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 7999: 	} elsif ($which eq '64bit4') {
 8000: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 8001: 	} else {
 8002: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 8003: 	}
 8004:     } elsif ($which eq '64bit5') {
 8005: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 8006:     } elsif ($which eq '64bit4') {
 8007: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 8008:     } elsif ($which eq '64bit3') {
 8009: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 8010:     } elsif ($which eq '64bit2') {
 8011: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 8012:     } elsif ($which eq '64bit') {
 8013: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 8014:     }
 8015:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 8016: }
 8017: 
 8018: sub rndseed_32bit {
 8019:     my ($symb,$courseid,$domain,$username)=@_;
 8020:     {
 8021: 	use integer;
 8022: 	my $symbchck=unpack("%32C*",$symb) << 27;
 8023: 	my $symbseed=numval($symb) << 22;
 8024: 	my $namechck=unpack("%32C*",$username) << 17;
 8025: 	my $nameseed=numval($username) << 12;
 8026: 	my $domainseed=unpack("%32C*",$domain) << 7;
 8027: 	my $courseseed=unpack("%32C*",$courseid);
 8028: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 8029: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8030: 	#&logthis("rndseed :$num:$symb");
 8031: 	if ($_64bit) { $num=(($num<<32)>>32); }
 8032: 	return $num;
 8033:     }
 8034: }
 8035: 
 8036: sub rndseed_64bit {
 8037:     my ($symb,$courseid,$domain,$username)=@_;
 8038:     {
 8039: 	use integer;
 8040: 	my $symbchck=unpack("%32S*",$symb) << 21;
 8041: 	my $symbseed=numval($symb) << 10;
 8042: 	my $namechck=unpack("%32S*",$username);
 8043: 	
 8044: 	my $nameseed=numval($username) << 21;
 8045: 	my $domainseed=unpack("%32S*",$domain) << 10;
 8046: 	my $courseseed=unpack("%32S*",$courseid);
 8047: 	
 8048: 	my $num1=$symbchck+$symbseed+$namechck;
 8049: 	my $num2=$nameseed+$domainseed+$courseseed;
 8050: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8051: 	#&logthis("rndseed :$num:$symb");
 8052: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8053: 	return "$num1,$num2";
 8054:     }
 8055: }
 8056: 
 8057: sub rndseed_64bit2 {
 8058:     my ($symb,$courseid,$domain,$username)=@_;
 8059:     {
 8060: 	use integer;
 8061: 	# strings need to be an even # of cahracters long, it it is odd the
 8062:         # last characters gets thrown away
 8063: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8064: 	my $symbseed=numval($symb) << 10;
 8065: 	my $namechck=unpack("%32S*",$username.' ');
 8066: 	
 8067: 	my $nameseed=numval($username) << 21;
 8068: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8069: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8070: 	
 8071: 	my $num1=$symbchck+$symbseed+$namechck;
 8072: 	my $num2=$nameseed+$domainseed+$courseseed;
 8073: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8074: 	#&logthis("rndseed :$num:$symb");
 8075: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8076: 	return "$num1,$num2";
 8077:     }
 8078: }
 8079: 
 8080: sub rndseed_64bit3 {
 8081:     my ($symb,$courseid,$domain,$username)=@_;
 8082:     {
 8083: 	use integer;
 8084: 	# strings need to be an even # of cahracters long, it it is odd the
 8085:         # last characters gets thrown away
 8086: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8087: 	my $symbseed=numval2($symb) << 10;
 8088: 	my $namechck=unpack("%32S*",$username.' ');
 8089: 	
 8090: 	my $nameseed=numval2($username) << 21;
 8091: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8092: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8093: 	
 8094: 	my $num1=$symbchck+$symbseed+$namechck;
 8095: 	my $num2=$nameseed+$domainseed+$courseseed;
 8096: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8097: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8098: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8099: 	
 8100: 	return "$num1:$num2";
 8101:     }
 8102: }
 8103: 
 8104: sub rndseed_64bit4 {
 8105:     my ($symb,$courseid,$domain,$username)=@_;
 8106:     {
 8107: 	use integer;
 8108: 	# strings need to be an even # of cahracters long, it it is odd the
 8109:         # last characters gets thrown away
 8110: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8111: 	my $symbseed=numval3($symb) << 10;
 8112: 	my $namechck=unpack("%32S*",$username.' ');
 8113: 	
 8114: 	my $nameseed=numval3($username) << 21;
 8115: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8116: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8117: 	
 8118: 	my $num1=$symbchck+$symbseed+$namechck;
 8119: 	my $num2=$nameseed+$domainseed+$courseseed;
 8120: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8121: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8122: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8123: 	
 8124: 	return "$num1:$num2";
 8125:     }
 8126: }
 8127: 
 8128: sub rndseed_64bit5 {
 8129:     my ($symb,$courseid,$domain,$username)=@_;
 8130:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 8131:     return "$num1:$num2";
 8132: }
 8133: 
 8134: sub rndseed_CODE_64bit {
 8135:     my ($symb,$courseid,$domain,$username)=@_;
 8136:     {
 8137: 	use integer;
 8138: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8139: 	my $symbseed=numval2($symb);
 8140: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8141: 	my $CODEseed=numval(&getCODE());
 8142: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8143: 	my $num1=$symbseed+$CODEchck;
 8144: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8145: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8146: 	#&logthis("rndseed :$num1:$num2:$symb");
 8147: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8148: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8149: 	return "$num1:$num2";
 8150:     }
 8151: }
 8152: 
 8153: sub rndseed_CODE_64bit4 {
 8154:     my ($symb,$courseid,$domain,$username)=@_;
 8155:     {
 8156: 	use integer;
 8157: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8158: 	my $symbseed=numval3($symb);
 8159: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8160: 	my $CODEseed=numval3(&getCODE());
 8161: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8162: 	my $num1=$symbseed+$CODEchck;
 8163: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8164: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8165: 	#&logthis("rndseed :$num1:$num2:$symb");
 8166: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8167: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8168: 	return "$num1:$num2";
 8169:     }
 8170: }
 8171: 
 8172: sub rndseed_CODE_64bit5 {
 8173:     my ($symb,$courseid,$domain,$username)=@_;
 8174:     my $code = &getCODE();
 8175:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 8176:     return "$num1:$num2";
 8177: }
 8178: 
 8179: sub setup_random_from_rndseed {
 8180:     my ($rndseed)=@_;
 8181:     if ($rndseed =~/([,:])/) {
 8182: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 8183: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 8184:     } else {
 8185: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 8186:     }
 8187: }
 8188: 
 8189: sub latest_receipt_algorithm_id {
 8190:     return 'receipt3';
 8191: }
 8192: 
 8193: sub recunique {
 8194:     my $fucourseid=shift;
 8195:     my $unique;
 8196:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 8197: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8198: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 8199:     } else {
 8200: 	$unique=$perlvar{'lonReceipt'};
 8201:     }
 8202:     return unpack("%32C*",$unique);
 8203: }
 8204: 
 8205: sub recprefix {
 8206:     my $fucourseid=shift;
 8207:     my $prefix;
 8208:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 8209: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8210: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 8211:     } else {
 8212: 	$prefix=$perlvar{'lonHostID'};
 8213:     }
 8214:     return unpack("%32C*",$prefix);
 8215: }
 8216: 
 8217: sub ireceipt {
 8218:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 8219: 
 8220:     my $return =&recprefix($fucourseid).'-';
 8221: 
 8222:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 8223: 	$env{'request.state'} eq 'construct') {
 8224: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 8225: 	return $return;
 8226:     }
 8227: 
 8228:     my $cuname=unpack("%32C*",$funame);
 8229:     my $cudom=unpack("%32C*",$fudom);
 8230:     my $cucourseid=unpack("%32C*",$fucourseid);
 8231:     my $cusymb=unpack("%32C*",$fusymb);
 8232:     my $cunique=&recunique($fucourseid);
 8233:     my $cpart=unpack("%32S*",$part);
 8234:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 8235: 
 8236: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 8237: 			       
 8238: 	$return.= ($cunique%$cuname+
 8239: 		   $cunique%$cudom+
 8240: 		   $cusymb%$cuname+
 8241: 		   $cusymb%$cudom+
 8242: 		   $cucourseid%$cuname+
 8243: 		   $cucourseid%$cudom+
 8244: 		   $cpart%$cuname+
 8245: 		   $cpart%$cudom);
 8246:     } else {
 8247: 	$return.= ($cunique%$cuname+
 8248: 		   $cunique%$cudom+
 8249: 		   $cusymb%$cuname+
 8250: 		   $cusymb%$cudom+
 8251: 		   $cucourseid%$cuname+
 8252: 		   $cucourseid%$cudom);
 8253:     }
 8254:     return $return;
 8255: }
 8256: 
 8257: sub receipt {
 8258:     my ($part)=@_;
 8259:     my ($symb,$courseid,$domain,$name) = &whichuser();
 8260:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 8261: }
 8262: 
 8263: sub whichuser {
 8264:     my ($passedsymb)=@_;
 8265:     my ($symb,$courseid,$domain,$name,$publicuser);
 8266:     if (defined($env{'form.grade_symb'})) {
 8267: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 8268: 	my $allowed=&allowed('vgr',$tmp_courseid);
 8269: 	if (!$allowed &&
 8270: 	    exists($env{'request.course.sec'}) &&
 8271: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 8272: 	    $allowed=&allowed('vgr',$tmp_courseid.
 8273: 			      '/'.$env{'request.course.sec'});
 8274: 	}
 8275: 	if ($allowed) {
 8276: 	    ($symb)=&get_env_multiple('form.grade_symb');
 8277: 	    $courseid=$tmp_courseid;
 8278: 	    ($domain)=&get_env_multiple('form.grade_domain');
 8279: 	    ($name)=&get_env_multiple('form.grade_username');
 8280: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 8281: 	}
 8282:     }
 8283:     if (!$passedsymb) {
 8284: 	$symb=&symbread();
 8285:     } else {
 8286: 	$symb=$passedsymb;
 8287:     }
 8288:     $courseid=$env{'request.course.id'};
 8289:     $domain=$env{'user.domain'};
 8290:     $name=$env{'user.name'};
 8291:     if ($name eq 'public' && $domain eq 'public') {
 8292: 	if (!defined($env{'form.username'})) {
 8293: 	    $env{'form.username'}.=time.rand(10000000);
 8294: 	}
 8295: 	$name.=$env{'form.username'};
 8296:     }
 8297:     return ($symb,$courseid,$domain,$name,$publicuser);
 8298: 
 8299: }
 8300: 
 8301: # ------------------------------------------------------------ Serves up a file
 8302: # returns either the contents of the file or 
 8303: # -1 if the file doesn't exist
 8304: #
 8305: # if the target is a file that was uploaded via DOCS, 
 8306: # a check will be made to see if a current copy exists on the local server,
 8307: # if it does this will be served, otherwise a copy will be retrieved from
 8308: # the home server for the course and stored in /home/httpd/html/userfiles on
 8309: # the local server.   
 8310: 
 8311: sub getfile {
 8312:     my ($file) = @_;
 8313:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8314:     &repcopy($file);
 8315:     return &readfile($file);
 8316: }
 8317: 
 8318: sub repcopy_userfile {
 8319:     my ($file)=@_;
 8320:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8321:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 8322:     my ($cdom,$cnum,$filename) = 
 8323: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 8324:     my $uri="/uploaded/$cdom/$cnum/$filename";
 8325:     if (-e "$file") {
 8326: # we already have a local copy, check it out
 8327: 	my @fileinfo = stat($file);
 8328: 	my $rtncode;
 8329: 	my $info;
 8330: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 8331: 	if ($lwpresp ne 'ok') {
 8332: # there is no such file anymore, even though we had a local copy
 8333: 	    if ($rtncode eq '404') {
 8334: 		unlink($file);
 8335: 	    }
 8336: 	    return -1;
 8337: 	}
 8338: 	if ($info < $fileinfo[9]) {
 8339: # nice, the file we have is up-to-date, just say okay
 8340: 	    return 'ok';
 8341: 	} else {
 8342: # the file is outdated, get rid of it
 8343: 	    unlink($file);
 8344: 	}
 8345:     }
 8346: # one way or the other, at this point, we don't have the file
 8347: # construct the correct path for the file
 8348:     my @parts = ($cdom,$cnum); 
 8349:     if ($filename =~ m|^(.+)/[^/]+$|) {
 8350: 	push @parts, split(/\//,$1);
 8351:     }
 8352:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 8353:     foreach my $part (@parts) {
 8354: 	$path .= '/'.$part;
 8355: 	if (!-e $path) {
 8356: 	    mkdir($path,0770);
 8357: 	}
 8358:     }
 8359: # now the path exists for sure
 8360: # get a user agent
 8361:     my $ua=new LWP::UserAgent;
 8362:     my $transferfile=$file.'.in.transfer';
 8363: # FIXME: this should flock
 8364:     if (-e $transferfile) { return 'ok'; }
 8365:     my $request;
 8366:     $uri=~s/^\///;
 8367:     my $homeserver = &homeserver($cnum,$cdom);
 8368:     my $protocol = $protocol{$homeserver};
 8369:     $protocol = 'http' if ($protocol ne 'https');
 8370:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
 8371:     my $response=$ua->request($request,$transferfile);
 8372: # did it work?
 8373:     if ($response->is_error()) {
 8374: 	unlink($transferfile);
 8375: 	&logthis("Userfile repcopy failed for $uri");
 8376: 	return -1;
 8377:     }
 8378: # worked, rename the transfer file
 8379:     rename($transferfile,$file);
 8380:     return 'ok';
 8381: }
 8382: 
 8383: sub tokenwrapper {
 8384:     my $uri=shift;
 8385:     $uri=~s|^https?\://([^/]+)||;
 8386:     $uri=~s|^/||;
 8387:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 8388:     my $token=$1;
 8389:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 8390:     if ($udom && $uname && $file) {
 8391: 	$file=~s|(\?\.*)*$||;
 8392:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 8393:         my $homeserver = &homeserver($uname,$udom);
 8394:         my $protocol = $protocol{$homeserver};
 8395:         $protocol = 'http' if ($protocol ne 'https');
 8396:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
 8397:                (($uri=~/\?/)?'&':'?').'token='.$token.
 8398:                                '&tokenissued='.$perlvar{'lonHostID'};
 8399:     } else {
 8400:         return '/adm/notfound.html';
 8401:     }
 8402: }
 8403: 
 8404: # call with reqtype HEAD: get last modification time
 8405: # call with reqtype GET: get the file contents
 8406: # Do not call this with reqtype GET for large files! It loads everything into memory
 8407: #
 8408: sub getuploaded {
 8409:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 8410:     $uri=~s/^\///;
 8411:     my $homeserver = &homeserver($cnum,$cdom);
 8412:     my $protocol = $protocol{$homeserver};
 8413:     $protocol = 'http' if ($protocol ne 'https');
 8414:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
 8415:     my $ua=new LWP::UserAgent;
 8416:     my $request=new HTTP::Request($reqtype,$uri);
 8417:     my $response=$ua->request($request);
 8418:     $$rtncode = $response->code;
 8419:     if (! $response->is_success()) {
 8420: 	return 'failed';
 8421:     }      
 8422:     if ($reqtype eq 'HEAD') {
 8423: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 8424:     } elsif ($reqtype eq 'GET') {
 8425: 	$$info = $response->content;
 8426:     }
 8427:     return 'ok';
 8428: }
 8429: 
 8430: sub readfile {
 8431:     my $file = shift;
 8432:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 8433:     my $fh;
 8434:     open($fh,"<$file");
 8435:     my $a='';
 8436:     while (my $line = <$fh>) { $a .= $line; }
 8437:     return $a;
 8438: }
 8439: 
 8440: sub filelocation {
 8441:     my ($dir,$file) = @_;
 8442:     my $location;
 8443:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 8444: 
 8445:     if ($file =~ m-^/adm/-) {
 8446: 	$file=~s-^/adm/wrapper/-/-;
 8447: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8448:     }
 8449: 
 8450:     if ($file=~m:^/~:) { # is a contruction space reference
 8451:         $location = $file;
 8452:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 8453:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 8454: 	# is a correct contruction space reference
 8455:         $location = $file;
 8456:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
 8457:         $location = $file;
 8458:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 8459:         my ($udom,$uname,$filename)=
 8460:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 8461:         my $home=&homeserver($uname,$udom);
 8462:         my $is_me=0;
 8463:         my @ids=&current_machine_ids();
 8464:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 8465:         if ($is_me) {
 8466:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
 8467:         } else {
 8468:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 8469:   	      $udom.'/'.$uname.'/'.$filename;
 8470:         }
 8471:     } elsif ($file =~ m-^/adm/-) {
 8472: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 8473:     } else {
 8474:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8475:         $file=~s:^/res/:/:;
 8476:         if ( !( $file =~ m:^/:) ) {
 8477:             $location = $dir. '/'.$file;
 8478:         } else {
 8479:             $location = '/home/httpd/html/res'.$file;
 8480:         }
 8481:     }
 8482:     $location=~s://+:/:g; # remove duplicate /
 8483:     while ($location=~m{/\.\./}) {
 8484: 	if ($location =~ m{/[^/]+/\.\./}) {
 8485: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 8486: 	} else {
 8487: 	    $location=~ s{/\.\./}{/}g;
 8488: 	}
 8489:     } #remove dir/..
 8490:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 8491:     return $location;
 8492: }
 8493: 
 8494: sub hreflocation {
 8495:     my ($dir,$file)=@_;
 8496:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
 8497: 	$file=filelocation($dir,$file);
 8498:     } elsif ($file=~m-^/adm/-) {
 8499: 	$file=~s-^/adm/wrapper/-/-;
 8500: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8501:     }
 8502:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 8503: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 8504:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 8505: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 8506:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 8507: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 8508: 	    -/uploaded/$1/$2/-x;
 8509:     }
 8510:     if ($file=~ m{^/userfiles/}) {
 8511: 	$file =~ s{^/userfiles/}{/uploaded/};
 8512:     }
 8513:     return $file;
 8514: }
 8515: 
 8516: sub current_machine_domains {
 8517:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 8518: }
 8519: 
 8520: sub machine_domains {
 8521:     my ($hostname) = @_;
 8522:     my @domains;
 8523:     my %hostname = &all_hostnames();
 8524:     while( my($id, $name) = each(%hostname)) {
 8525: #	&logthis("-$id-$name-$hostname-");
 8526: 	if ($hostname eq $name) {
 8527: 	    push(@domains,&host_domain($id));
 8528: 	}
 8529:     }
 8530:     return @domains;
 8531: }
 8532: 
 8533: sub current_machine_ids {
 8534:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 8535: }
 8536: 
 8537: sub machine_ids {
 8538:     my ($hostname) = @_;
 8539:     $hostname ||= &hostname($perlvar{'lonHostID'});
 8540:     my @ids;
 8541:     my %name_to_host = &all_names();
 8542:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 8543: 	return @{ $name_to_host{$hostname} };
 8544:     }
 8545:     return;
 8546: }
 8547: 
 8548: sub additional_machine_domains {
 8549:     my @domains;
 8550:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 8551:     while( my $line = <$fh>) {
 8552:         $line =~ s/\s//g;
 8553:         push(@domains,$line);
 8554:     }
 8555:     return @domains;
 8556: }
 8557: 
 8558: sub default_login_domain {
 8559:     my $domain = $perlvar{'lonDefDomain'};
 8560:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 8561:     foreach my $posdom (&current_machine_domains(),
 8562:                         &additional_machine_domains()) {
 8563:         if (lc($posdom) eq lc($testdomain)) {
 8564:             $domain=$posdom;
 8565:             last;
 8566:         }
 8567:     }
 8568:     return $domain;
 8569: }
 8570: 
 8571: # ------------------------------------------------------------- Declutters URLs
 8572: 
 8573: sub declutter {
 8574:     my $thisfn=shift;
 8575:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8576:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8577:     $thisfn=~s/^\///;
 8578:     $thisfn=~s|^adm/wrapper/||;
 8579:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 8580:     $thisfn=~s/^res\///;
 8581:     $thisfn=~s/\?.+$//;
 8582:     return $thisfn;
 8583: }
 8584: 
 8585: # ------------------------------------------------------------- Clutter up URLs
 8586: 
 8587: sub clutter {
 8588:     my $thisfn='/'.&declutter(shift);
 8589:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 8590: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 8591:        $thisfn='/res'.$thisfn; 
 8592:     }
 8593:     if ($thisfn !~m|/adm|) {
 8594: 	if ($thisfn =~ m|/ext/|) {
 8595: 	    $thisfn='/adm/wrapper'.$thisfn;
 8596: 	} else {
 8597: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 8598: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 8599: 	    if ($embstyle eq 'ssi'
 8600: 		|| ($embstyle eq 'hdn')
 8601: 		|| ($embstyle eq 'rat')
 8602: 		|| ($embstyle eq 'prv')
 8603: 		|| ($embstyle eq 'ign')) {
 8604: 		#do nothing with these
 8605: 	    } elsif (($embstyle eq 'img') 
 8606: 		|| ($embstyle eq 'emb')
 8607: 		|| ($embstyle eq 'wrp')) {
 8608: 		$thisfn='/adm/wrapper'.$thisfn;
 8609: 	    } elsif ($embstyle eq 'unk'
 8610: 		     && $thisfn!~/\.(sequence|page)$/) {
 8611: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 8612: 	    } else {
 8613: #		&logthis("Got a blank emb style");
 8614: 	    }
 8615: 	}
 8616:     }
 8617:     return $thisfn;
 8618: }
 8619: 
 8620: sub clutter_with_no_wrapper {
 8621:     my $uri = &clutter(shift);
 8622:     if ($uri =~ m-^/adm/-) {
 8623: 	$uri =~ s-^/adm/wrapper/-/-;
 8624: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 8625:     }
 8626:     return $uri;
 8627: }
 8628: 
 8629: sub freeze_escape {
 8630:     my ($value)=@_;
 8631:     if (ref($value)) {
 8632: 	$value=&nfreeze($value);
 8633: 	return '__FROZEN__'.&escape($value);
 8634:     }
 8635:     return &escape($value);
 8636: }
 8637: 
 8638: 
 8639: sub thaw_unescape {
 8640:     my ($value)=@_;
 8641:     if ($value =~ /^__FROZEN__/) {
 8642: 	substr($value,0,10,undef);
 8643: 	$value=&unescape($value);
 8644: 	return &thaw($value);
 8645:     }
 8646:     return &unescape($value);
 8647: }
 8648: 
 8649: sub correct_line_ends {
 8650:     my ($result)=@_;
 8651:     $$result =~s/\r\n/\n/mg;
 8652:     $$result =~s/\r/\n/mg;
 8653: }
 8654: # ================================================================ Main Program
 8655: 
 8656: sub goodbye {
 8657:    &logthis("Starting Shut down");
 8658: #not converted to using infrastruture and probably shouldn't be
 8659:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 8660: #converted
 8661: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 8662:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 8663: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 8664: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 8665: #1.1 only
 8666: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 8667: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 8668: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 8669: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 8670:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 8671:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 8672:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 8673:    &flushcourselogs();
 8674:    &logthis("Shutting down");
 8675: }
 8676: 
 8677: sub get_dns {
 8678:     my ($url,$func,$ignore_cache) = @_;
 8679:     if (!$ignore_cache) {
 8680: 	my ($content,$cached)=
 8681: 	    &Apache::lonnet::is_cached_new('dns',$url);
 8682: 	if ($cached) {
 8683: 	    &$func($content);
 8684: 	    return;
 8685: 	}
 8686:     }
 8687: 
 8688:     my %alldns;
 8689:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8690:     foreach my $dns (<$config>) {
 8691: 	next if ($dns !~ /^\^(\S*)/x);
 8692:         my $line = $1;
 8693:         my ($host,$protocol) = split(/:/,$line);
 8694:         if ($protocol ne 'https') {
 8695:             $protocol = 'http';
 8696:         }
 8697: 	$alldns{$host} = $protocol;
 8698:     }
 8699:     while (%alldns) {
 8700: 	my ($dns) = keys(%alldns);
 8701: 	my $ua=new LWP::UserAgent;
 8702: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
 8703: 	my $response=$ua->request($request);
 8704:         delete($alldns{$dns});
 8705: 	next if ($response->is_error());
 8706: 	my @content = split("\n",$response->content);
 8707: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 8708: 	&$func(\@content);
 8709: 	return;
 8710:     }
 8711:     close($config);
 8712:     my $which = (split('/',$url))[3];
 8713:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 8714:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 8715:     my @content = <$config>;
 8716:     &$func(\@content);
 8717:     return;
 8718: }
 8719: # ------------------------------------------------------------ Read domain file
 8720: {
 8721:     my $loaded;
 8722:     my %domain;
 8723: 
 8724:     sub parse_domain_tab {
 8725: 	my ($lines) = @_;
 8726: 	foreach my $line (@$lines) {
 8727: 	    next if ($line =~ /^(\#|\s*$ )/x);
 8728: 
 8729: 	    chomp($line);
 8730: 	    my ($name,@elements) = split(/:/,$line,9);
 8731: 	    my %this_domain;
 8732: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 8733: 			       'lang_def', 'city', 'longi', 'lati',
 8734: 			       'primary') {
 8735: 		$this_domain{$field} = shift(@elements);
 8736: 	    }
 8737: 	    $domain{$name} = \%this_domain;
 8738: 	}
 8739:     }
 8740: 
 8741:     sub reset_domain_info {
 8742: 	undef($loaded);
 8743: 	undef(%domain);
 8744:     }
 8745: 
 8746:     sub load_domain_tab {
 8747: 	my ($ignore_cache) = @_;
 8748: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 8749: 	my $fh;
 8750: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 8751: 	    my @lines = <$fh>;
 8752: 	    &parse_domain_tab(\@lines);
 8753: 	}
 8754: 	close($fh);
 8755: 	$loaded = 1;
 8756:     }
 8757: 
 8758:     sub domain {
 8759: 	&load_domain_tab() if (!$loaded);
 8760: 
 8761: 	my ($name,$what) = @_;
 8762: 	return if ( !exists($domain{$name}) );
 8763: 
 8764: 	if (!$what) {
 8765: 	    return $domain{$name}{'description'};
 8766: 	}
 8767: 	return $domain{$name}{$what};
 8768:     }
 8769: 
 8770:     sub domain_info {
 8771:         &load_domain_tab() if (!$loaded);
 8772:         return %domain;
 8773:     }
 8774: 
 8775: }
 8776: 
 8777: 
 8778: # ------------------------------------------------------------- Read hosts file
 8779: {
 8780:     my %hostname;
 8781:     my %hostdom;
 8782:     my %libserv;
 8783:     my $loaded;
 8784:     my %name_to_host;
 8785: 
 8786:     sub parse_hosts_tab {
 8787: 	my ($file) = @_;
 8788: 	foreach my $configline (@$file) {
 8789: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 8790: 	    next if ($configline =~ /^\^/);
 8791: 	    chomp($configline);
 8792: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
 8793: 	    $name=~s/\s//g;
 8794: 	    if ($id && $domain && $role && $name) {
 8795: 		$hostname{$id}=$name;
 8796: 		push(@{$name_to_host{$name}}, $id);
 8797: 		$hostdom{$id}=$domain;
 8798: 		if ($role eq 'library') { $libserv{$id}=$name; }
 8799:                 if (defined($protocol)) {
 8800:                     if ($protocol eq 'https') {
 8801:                         $protocol{$id} = $protocol;
 8802:                     } else {
 8803:                         $protocol{$id} = 'http'; 
 8804:                     }
 8805:                 } else {
 8806:                     $protocol{$id} = 'http';
 8807:                 }
 8808: 	    }
 8809: 	}
 8810:     }
 8811:     
 8812:     sub reset_hosts_info {
 8813: 	&purge_remembered();
 8814: 	&reset_domain_info();
 8815: 	&reset_hosts_ip_info();
 8816: 	undef(%name_to_host);
 8817: 	undef(%hostname);
 8818: 	undef(%hostdom);
 8819: 	undef(%libserv);
 8820: 	undef($loaded);
 8821:     }
 8822: 
 8823:     sub load_hosts_tab {
 8824: 	my ($ignore_cache) = @_;
 8825: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 8826: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8827: 	my @config = <$config>;
 8828: 	&parse_hosts_tab(\@config);
 8829: 	close($config);
 8830: 	$loaded=1;
 8831:     }
 8832: 
 8833:     sub hostname {
 8834: 	&load_hosts_tab() if (!$loaded);
 8835: 
 8836: 	my ($lonid) = @_;
 8837: 	return $hostname{$lonid};
 8838:     }
 8839: 
 8840:     sub all_hostnames {
 8841: 	&load_hosts_tab() if (!$loaded);
 8842: 
 8843: 	return %hostname;
 8844:     }
 8845: 
 8846:     sub all_names {
 8847: 	&load_hosts_tab() if (!$loaded);
 8848: 
 8849: 	return %name_to_host;
 8850:     }
 8851: 
 8852:     sub all_host_domain {
 8853:         &load_hosts_tab() if (!$loaded);
 8854:         return %hostdom;
 8855:     }
 8856: 
 8857:     sub is_library {
 8858: 	&load_hosts_tab() if (!$loaded);
 8859: 
 8860: 	return exists($libserv{$_[0]});
 8861:     }
 8862: 
 8863:     sub all_library {
 8864: 	&load_hosts_tab() if (!$loaded);
 8865: 
 8866: 	return %libserv;
 8867:     }
 8868: 
 8869:     sub get_servers {
 8870: 	&load_hosts_tab() if (!$loaded);
 8871: 
 8872: 	my ($domain,$type) = @_;
 8873: 	my %possible_hosts = ($type eq 'library') ? %libserv
 8874: 	                                          : %hostname;
 8875: 	my %result;
 8876: 	if (ref($domain) eq 'ARRAY') {
 8877: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8878: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 8879: 		    $result{$host} = $hostname;
 8880: 		}
 8881: 	    }
 8882: 	} else {
 8883: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8884: 		if ($hostdom{$host} eq $domain) {
 8885: 		    $result{$host} = $hostname;
 8886: 		}
 8887: 	    }
 8888: 	}
 8889: 	return %result;
 8890:     }
 8891: 
 8892:     sub host_domain {
 8893: 	&load_hosts_tab() if (!$loaded);
 8894: 
 8895: 	my ($lonid) = @_;
 8896: 	return $hostdom{$lonid};
 8897:     }
 8898: 
 8899:     sub all_domains {
 8900: 	&load_hosts_tab() if (!$loaded);
 8901: 
 8902: 	my %seen;
 8903: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 8904: 	return @uniq;
 8905:     }
 8906: }
 8907: 
 8908: { 
 8909:     my %iphost;
 8910:     my %name_to_ip;
 8911:     my %lonid_to_ip;
 8912: 
 8913:     sub get_hosts_from_ip {
 8914: 	my ($ip) = @_;
 8915: 	my %iphosts = &get_iphost();
 8916: 	if (ref($iphosts{$ip})) {
 8917: 	    return @{$iphosts{$ip}};
 8918: 	}
 8919: 	return;
 8920:     }
 8921:     
 8922:     sub reset_hosts_ip_info {
 8923: 	undef(%iphost);
 8924: 	undef(%name_to_ip);
 8925: 	undef(%lonid_to_ip);
 8926:     }
 8927: 
 8928:     sub get_host_ip {
 8929: 	my ($lonid) = @_;
 8930: 	if (exists($lonid_to_ip{$lonid})) {
 8931: 	    return $lonid_to_ip{$lonid};
 8932: 	}
 8933: 	my $name=&hostname($lonid);
 8934:    	my $ip = gethostbyname($name);
 8935: 	return if (!$ip || length($ip) ne 4);
 8936: 	$ip=inet_ntoa($ip);
 8937: 	$name_to_ip{$name}   = $ip;
 8938: 	$lonid_to_ip{$lonid} = $ip;
 8939: 	return $ip;
 8940:     }
 8941:     
 8942:     sub get_iphost {
 8943: 	my ($ignore_cache) = @_;
 8944: 
 8945: 	if (!$ignore_cache) {
 8946: 	    if (%iphost) {
 8947: 		return %iphost;
 8948: 	    }
 8949: 	    my ($ip_info,$cached)=
 8950: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 8951: 	    if ($cached) {
 8952: 		%iphost      = %{$ip_info->[0]};
 8953: 		%name_to_ip  = %{$ip_info->[1]};
 8954: 		%lonid_to_ip = %{$ip_info->[2]};
 8955: 		return %iphost;
 8956: 	    }
 8957: 	}
 8958: 
 8959: 	# get yesterday's info for fallback
 8960: 	my %old_name_to_ip;
 8961: 	my ($ip_info,$cached)=
 8962: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 8963: 	if ($cached) {
 8964: 	    %old_name_to_ip = %{$ip_info->[1]};
 8965: 	}
 8966: 
 8967: 	my %name_to_host = &all_names();
 8968: 	foreach my $name (keys(%name_to_host)) {
 8969: 	    my $ip;
 8970: 	    if (!exists($name_to_ip{$name})) {
 8971: 		$ip = gethostbyname($name);
 8972: 		if (!$ip || length($ip) ne 4) {
 8973: 		    if (defined($old_name_to_ip{$name})) {
 8974: 			$ip = $old_name_to_ip{$name};
 8975: 			&logthis("Can't find $name defaulting to old $ip");
 8976: 		    } else {
 8977: 			&logthis("Name $name no IP found");
 8978: 			next;
 8979: 		    }
 8980: 		} else {
 8981: 		    $ip=inet_ntoa($ip);
 8982: 		}
 8983: 		$name_to_ip{$name} = $ip;
 8984: 	    } else {
 8985: 		$ip = $name_to_ip{$name};
 8986: 	    }
 8987: 	    foreach my $id (@{ $name_to_host{$name} }) {
 8988: 		$lonid_to_ip{$id} = $ip;
 8989: 	    }
 8990: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 8991: 	}
 8992: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 8993: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 8994: 				      48*60*60);
 8995: 
 8996: 	return %iphost;
 8997:     }
 8998: }
 8999: 
 9000: BEGIN {
 9001: 
 9002: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 9003:     unless ($readit) {
 9004: {
 9005:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 9006:     %perlvar = (%perlvar,%{$configvars});
 9007: }
 9008: 
 9009: 
 9010: # ------------------------------------------------------ Read spare server file
 9011: {
 9012:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 9013: 
 9014:     while (my $configline=<$config>) {
 9015:        chomp($configline);
 9016:        if ($configline) {
 9017: 	   my ($host,$type) = split(':',$configline,2);
 9018: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 9019: 	   push(@{ $spareid{$type} }, $host);
 9020:        }
 9021:     }
 9022:     close($config);
 9023: }
 9024: # ------------------------------------------------------------ Read permissions
 9025: {
 9026:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 9027: 
 9028:     while (my $configline=<$config>) {
 9029: 	chomp($configline);
 9030: 	if ($configline) {
 9031: 	    my ($role,$perm)=split(/ /,$configline);
 9032: 	    if ($perm ne '') { $pr{$role}=$perm; }
 9033: 	}
 9034:     }
 9035:     close($config);
 9036: }
 9037: 
 9038: # -------------------------------------------- Read plain texts for permissions
 9039: {
 9040:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 9041: 
 9042:     while (my $configline=<$config>) {
 9043: 	chomp($configline);
 9044: 	if ($configline) {
 9045: 	    my ($short,@plain)=split(/:/,$configline);
 9046:             %{$prp{$short}} = ();
 9047: 	    if (@plain > 0) {
 9048:                 $prp{$short}{'std'} = $plain[0];
 9049:                 for (my $i=1; $i<@plain; $i++) {
 9050:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 9051:                 }
 9052:             }
 9053: 	}
 9054:     }
 9055:     close($config);
 9056: }
 9057: 
 9058: # ---------------------------------------------------------- Read package table
 9059: {
 9060:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 9061: 
 9062:     while (my $configline=<$config>) {
 9063: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 9064: 	chomp($configline);
 9065: 	my ($short,$plain)=split(/:/,$configline);
 9066: 	my ($pack,$name)=split(/\&/,$short);
 9067: 	if ($plain ne '') {
 9068: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 9069: 	    $packagetab{$short}=$plain; 
 9070: 	}
 9071:     }
 9072:     close($config);
 9073: }
 9074: 
 9075: # ------------- set up temporary directory
 9076: {
 9077:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 9078: 
 9079: }
 9080: 
 9081: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 9082: 				'compress_threshold'=> 20_000,
 9083:  			        });
 9084: 
 9085: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 9086: $dumpcount=0;
 9087: $locknum=0;
 9088: 
 9089: &logtouch();
 9090: &logthis('<font color="yellow">INFO: Read configuration</font>');
 9091: $readit=1;
 9092:     {
 9093: 	use integer;
 9094: 	my $test=(2**32)+1;
 9095: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 9096: 	&logthis(" Detected 64bit platform ($_64bit)");
 9097:     }
 9098: }
 9099: }
 9100: 
 9101: 1;
 9102: __END__
 9103: 
 9104: =pod
 9105: 
 9106: =head1 NAME
 9107: 
 9108: Apache::lonnet - Subroutines to ask questions about things in the network.
 9109: 
 9110: =head1 SYNOPSIS
 9111: 
 9112: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 9113: 
 9114:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 9115: 
 9116: Common parameters:
 9117: 
 9118: =over 4
 9119: 
 9120: =item *
 9121: 
 9122: $uname : an internal username (if $cname expecting a course Id specifically)
 9123: 
 9124: =item *
 9125: 
 9126: $udom : a domain (if $cdom expecting a course's domain specifically)
 9127: 
 9128: =item *
 9129: 
 9130: $symb : a resource instance identifier
 9131: 
 9132: =item *
 9133: 
 9134: $namespace : the name of a .db file that contains the data needed or
 9135: being set.
 9136: 
 9137: =back
 9138: 
 9139: =head1 OVERVIEW
 9140: 
 9141: lonnet provides subroutines which interact with the
 9142: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 9143: about classes, users, and resources.
 9144: 
 9145: For many of these objects you can also use this to store data about
 9146: them or modify them in various ways.
 9147: 
 9148: =head2 Symbs
 9149: 
 9150: To identify a specific instance of a resource, LON-CAPA uses symbols
 9151: or "symbs"X<symb>. These identifiers are built from the URL of the
 9152: map, the resource number of the resource in the map, and the URL of
 9153: the resource itself. The latter is somewhat redundant, but might help
 9154: if maps change.
 9155: 
 9156: An example is
 9157: 
 9158:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 9159: 
 9160: The respective map entry is
 9161: 
 9162:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 9163:   title="Problem 2">
 9164:  </resource>
 9165: 
 9166: Symbs are used by the random number generator, as well as to store and
 9167: restore data specific to a certain instance of for example a problem.
 9168: 
 9169: =head2 Storing And Retrieving Data
 9170: 
 9171: X<store()>X<cstore()>X<restore()>Three of the most important functions
 9172: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 9173: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 9174: is is the non-critical message twin of cstore. These functions are for
 9175: handlers to store a perl hash to a user's permanent data space in an
 9176: easy manner, and to retrieve it again on another call. It is expected
 9177: that a handler would use this once at the beginning to retrieve data,
 9178: and then again once at the end to send only the new data back.
 9179: 
 9180: The data is stored in the user's data directory on the user's
 9181: homeserver under the ID of the course.
 9182: 
 9183: The hash that is returned by restore will have all of the previous
 9184: value for all of the elements of the hash.
 9185: 
 9186: Example:
 9187: 
 9188:  #creating a hash
 9189:  my %hash;
 9190:  $hash{'foo'}='bar';
 9191: 
 9192:  #storing it
 9193:  &Apache::lonnet::cstore(\%hash);
 9194: 
 9195:  #changing a value
 9196:  $hash{'foo'}='notbar';
 9197: 
 9198:  #adding a new value
 9199:  $hash{'bar'}='foo';
 9200:  &Apache::lonnet::cstore(\%hash);
 9201: 
 9202:  #retrieving the hash
 9203:  my %history=&Apache::lonnet::restore();
 9204: 
 9205:  #print the hash
 9206:  foreach my $key (sort(keys(%history))) {
 9207:    print("\%history{$key} = $history{$key}");
 9208:  }
 9209: 
 9210: Will print out:
 9211: 
 9212:  %history{1:foo} = bar
 9213:  %history{1:keys} = foo:timestamp
 9214:  %history{1:timestamp} = 990455579
 9215:  %history{2:bar} = foo
 9216:  %history{2:foo} = notbar
 9217:  %history{2:keys} = foo:bar:timestamp
 9218:  %history{2:timestamp} = 990455580
 9219:  %history{bar} = foo
 9220:  %history{foo} = notbar
 9221:  %history{timestamp} = 990455580
 9222:  %history{version} = 2
 9223: 
 9224: Note that the special hash entries C<keys>, C<version> and
 9225: C<timestamp> were added to the hash. C<version> will be equal to the
 9226: total number of versions of the data that have been stored. The
 9227: C<timestamp> attribute will be the UNIX time the hash was
 9228: stored. C<keys> is available in every historical section to list which
 9229: keys were added or changed at a specific historical revision of a
 9230: hash.
 9231: 
 9232: B<Warning>: do not store the hash that restore returns directly. This
 9233: will cause a mess since it will restore the historical keys as if the
 9234: were new keys. I.E. 1:foo will become 1:1:foo etc.
 9235: 
 9236: Calling convention:
 9237: 
 9238:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 9239:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 9240: 
 9241: For more detailed information, see lonnet specific documentation.
 9242: 
 9243: =head1 RETURN MESSAGES
 9244: 
 9245: =over 4
 9246: 
 9247: =item * B<con_lost>: unable to contact remote host
 9248: 
 9249: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 9250: when the connection is brought back up
 9251: 
 9252: =item * B<con_failed>: unable to contact remote host and unable to save message
 9253: for later delivery
 9254: 
 9255: =item * B<error:>: an error a occurred, a description of the error follows the :
 9256: 
 9257: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 9258: that was requested
 9259: 
 9260: =back
 9261: 
 9262: =head1 PUBLIC SUBROUTINES
 9263: 
 9264: =head2 Session Environment Functions
 9265: 
 9266: =over 4
 9267: 
 9268: =item * 
 9269: X<appenv()>
 9270: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
 9271: the user envirnoment file, and will be restored for each access this
 9272: user makes during this session, also modifies the %env for the current
 9273: process. Optional rolesarrayref - if defined contains a reference to an array
 9274: of roles which are exempt from the restriction on modifying user.role entries 
 9275: in the user's environment.db and in %env.    
 9276: 
 9277: =item *
 9278: X<delenv()>
 9279: B<delenv($delthis,$regexp)>: removes all items from the session
 9280: environment file that begin with $delthis. If the
 9281: optional second arg - $regexp - is true, $delthis is treated as a
 9282: regular expression, otherwise \Q$delthis\E is used.
 9283: The values are also deleted from the current processes %env.
 9284: 
 9285: =item * get_env_multiple($name) 
 9286: 
 9287: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9288: values may be defined and end up as an array ref.
 9289: 
 9290: returns an array of values
 9291: 
 9292: =back
 9293: 
 9294: =head2 User Information
 9295: 
 9296: =over 4
 9297: 
 9298: =item *
 9299: X<queryauthenticate()>
 9300: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 9301: authentication scheme
 9302: 
 9303: =item *
 9304: X<authenticate()>
 9305: B<authenticate($uname,$upass,$udom)>: try to
 9306: authenticate user from domain's lib servers (first use the current
 9307: one). C<$upass> should be the users password.
 9308: 
 9309: =item *
 9310: X<homeserver()>
 9311: B<homeserver($uname,$udom)>: find the server which has
 9312: the user's directory and files (there must be only one), this caches
 9313: the answer, and also caches if there is a borken connection.
 9314: 
 9315: =item *
 9316: X<idget()>
 9317: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 9318: (IDs are a unique resource in a domain, there must be only 1 ID per
 9319: username, and only 1 username per ID in a specific domain) (returns
 9320: hash: id=>name,id=>name)
 9321: 
 9322: =item *
 9323: X<idrget()>
 9324: B<idrget($udom,@unames)>: find the IDs behind a list of
 9325: usernames (returns hash: name=>id,name=>id)
 9326: 
 9327: =item *
 9328: X<idput()>
 9329: B<idput($udom,%ids)>: store away a list of names and associated IDs
 9330: 
 9331: =item *
 9332: X<rolesinit()>
 9333: B<rolesinit($udom,$username,$authhost)>: get user privileges
 9334: 
 9335: =item *
 9336: X<getsection()>
 9337: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 9338: course $cname, return section name/number or '' for "not in course"
 9339: and '-1' for "no section"
 9340: 
 9341: =item *
 9342: X<userenvironment()>
 9343: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 9344: passed in @what from the requested user's environment, returns a hash
 9345: 
 9346: =item * 
 9347: X<userlog_query()>
 9348: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 9349: activity.log file. %filters defines filters applied when parsing the
 9350: log file. These can be start or end timestamps, or the type of action
 9351: - log to look for Login or Logout events, check for Checkin or
 9352: Checkout, role for role selection. The response is in the form
 9353: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 9354: escaped strings of the action recorded in the activity.log file.
 9355: 
 9356: =back
 9357: 
 9358: =head2 User Roles
 9359: 
 9360: =over 4
 9361: 
 9362: =item *
 9363: 
 9364: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 9365:  F: full access
 9366:  U,I,K: authentication modes (cxx only)
 9367:  '': forbidden
 9368:  1: user needs to choose course
 9369:  2: browse allowed
 9370:  A: passphrase authentication needed
 9371: 
 9372: =item *
 9373: 
 9374: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 9375: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 9376: and course level
 9377: 
 9378: =item *
 9379: 
 9380: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 9381: explanation of a user role term
 9382: 
 9383: =item *
 9384: 
 9385: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
 9386: All arguments are optional. Returns a hash of a roles, either for
 9387: co-author/assistant author roles for a user's Construction Space
 9388: (default), or if $context is 'userroles', roles for the user himself,
 9389: In the hash, keys are set to colon-separated $uname,$udom,$role, and
 9390: (optionally) if $withsec is true, a fourth colon-separated item - $section.
 9391: For each key, value is set to colon-separated start and end times for
 9392: the role.  If no username and domain are specified, will default to
 9393: current user/domain. Types, roles, and roledoms are references to arrays
 9394: of role statuses (active, future or previous), roles 
 9395: (e.g., cc,in, st etc.) and domains of the roles which can be used
 9396: to restrict the list of roles reported. If no array ref is 
 9397: provided for types, will default to return only active roles.
 9398: 
 9399: =back
 9400: 
 9401: =head2 User Modification
 9402: 
 9403: =over 4
 9404: 
 9405: =item *
 9406: 
 9407: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
 9408: user for the level given by URL.  Optional start and end dates (leave empty
 9409: string or zero for "no date")
 9410: 
 9411: =item *
 9412: 
 9413: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 9414: change a users, password, possible return values are: ok,
 9415: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 9416: refused
 9417: 
 9418: =item *
 9419: 
 9420: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 9421: 
 9422: =item *
 9423: 
 9424: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
 9425:            $forceid,$desiredhome,$email,$inststatus) : 
 9426: modify user
 9427: 
 9428: =item *
 9429: 
 9430: modifystudent
 9431: 
 9432: modify a student's enrollment and identification information.
 9433: The course id is resolved based on the current users environment.  
 9434: This means the envoking user must be a course coordinator or otherwise
 9435: associated with a course.
 9436: 
 9437: This call is essentially a wrapper for lonnet::modifyuser and
 9438: lonnet::modify_student_enrollment
 9439: 
 9440: Inputs: 
 9441: 
 9442: =over 4
 9443: 
 9444: =item B<$udom> Student's loncapa domain
 9445: 
 9446: =item B<$uname> Student's loncapa login name
 9447: 
 9448: =item B<$uid> Student/Employee ID
 9449: 
 9450: =item B<$umode> Student's authentication mode
 9451: 
 9452: =item B<$upass> Student's password
 9453: 
 9454: =item B<$first> Student's first name
 9455: 
 9456: =item B<$middle> Student's middle name
 9457: 
 9458: =item B<$last> Student's last name
 9459: 
 9460: =item B<$gene> Student's generation
 9461: 
 9462: =item B<$usec> Student's section in course
 9463: 
 9464: =item B<$end> Unix time of the roles expiration
 9465: 
 9466: =item B<$start> Unix time of the roles start date
 9467: 
 9468: =item B<$forceid> If defined, allow $uid to be changed
 9469: 
 9470: =item B<$desiredhome> server to use as home server for student
 9471: 
 9472: =item B<$email> Student's permanent e-mail address
 9473: 
 9474: =item B<$type> Type of enrollment (auto or manual)
 9475: 
 9476: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
 9477: 
 9478: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
 9479: 
 9480: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
 9481: 
 9482: =item B<$context> role change context (shown in User Management Logs display in a course)
 9483: 
 9484: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
 9485: 
 9486: =back
 9487: 
 9488: =item *
 9489: 
 9490: modify_student_enrollment
 9491: 
 9492: Change a students enrollment status in a class.  The environment variable
 9493: 'role.request.course' must be defined for this function to proceed.
 9494: 
 9495: Inputs:
 9496: 
 9497: =over 4
 9498: 
 9499: =item $udom, students domain
 9500: 
 9501: =item $uname, students name
 9502: 
 9503: =item $uid, students user id
 9504: 
 9505: =item $first, students first name
 9506: 
 9507: =item $middle
 9508: 
 9509: =item $last
 9510: 
 9511: =item $gene
 9512: 
 9513: =item $usec
 9514: 
 9515: =item $end
 9516: 
 9517: =item $start
 9518: 
 9519: =item $type
 9520: 
 9521: =item $locktype
 9522: 
 9523: =item $cid
 9524: 
 9525: =item $selfenroll
 9526: 
 9527: =item $context
 9528: 
 9529: =back
 9530: 
 9531: 
 9532: =item *
 9533: 
 9534: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 9535: custom role; give a custom role to a user for the level given by URL.  Specify
 9536: name and domain of role author, and role name
 9537: 
 9538: =item *
 9539: 
 9540: revokerole($udom,$uname,$url,$role) : revoke a role for url
 9541: 
 9542: =item *
 9543: 
 9544: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 9545: 
 9546: =back
 9547: 
 9548: =head2 Course Infomation
 9549: 
 9550: =over 4
 9551: 
 9552: =item *
 9553: 
 9554: coursedescription($courseid) : returns a hash of information about the
 9555: specified course id, including all environment settings for the
 9556: course, the description of the course will be in the hash under the
 9557: key 'description'
 9558: 
 9559: =item *
 9560: 
 9561: resdata($name,$domain,$type,@which) : request for current parameter
 9562: setting for a specific $type, where $type is either 'course' or 'user',
 9563: @what should be a list of parameters to ask about. This routine caches
 9564: answers for 5 minutes.
 9565: 
 9566: =item *
 9567: 
 9568: get_courseresdata($courseid, $domain) : dump the entire course resource
 9569: data base, returning a hash that is keyed by the resource name and has
 9570: values that are the resource value.  I believe that the timestamps and
 9571: versions are also returned.
 9572: 
 9573: 
 9574: =back
 9575: 
 9576: =head2 Course Modification
 9577: 
 9578: =over 4
 9579: 
 9580: =item *
 9581: 
 9582: writecoursepref($courseid,%prefs) : write preferences (environment
 9583: database) for a course
 9584: 
 9585: =item *
 9586: 
 9587: createcourse($udom,$description,$url) : make/modify course
 9588: 
 9589: =back
 9590: 
 9591: =head2 Resource Subroutines
 9592: 
 9593: =over 4
 9594: 
 9595: =item *
 9596: 
 9597: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 9598: 
 9599: =item *
 9600: 
 9601: repcopy($filename) : subscribes to the requested file, and attempts to
 9602: replicate from the owning library server, Might return
 9603: 'unavailable', 'not_found', 'forbidden', 'ok', or
 9604: 'bad_request', also attempts to grab the metadata for the
 9605: resource. Expects the local filesystem pathname
 9606: (/home/httpd/html/res/....)
 9607: 
 9608: =back
 9609: 
 9610: =head2 Resource Information
 9611: 
 9612: =over 4
 9613: 
 9614: =item *
 9615: 
 9616: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 9617: a vairety of different possible values, $varname should be a request
 9618: string, and the other parameters can be used to specify who and what
 9619: one is asking about.
 9620: 
 9621: Possible values for $varname are environment.lastname (or other item
 9622: from the envirnment hash), user.name (or someother aspect about the
 9623: user), resource.0.maxtries (or some other part and parameter of a
 9624: resource)
 9625: 
 9626: =item *
 9627: 
 9628: directcondval($number) : get current value of a condition; reads from a state
 9629: string
 9630: 
 9631: =item *
 9632: 
 9633: condval($condidx) : value of condition index based on state
 9634: 
 9635: =item *
 9636: 
 9637: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 9638: resource's metadata, $what should be either a specific key, or either
 9639: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 9640: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 9641: 
 9642: this function automatically caches all requests
 9643: 
 9644: =item *
 9645: 
 9646: metadata_query($query,$custom,$customshow) : make a metadata query against the
 9647: network of library servers; returns file handle of where SQL and regex results
 9648: will be stored for query
 9649: 
 9650: =item *
 9651: 
 9652: symbread($filename) : return symbolic list entry (filename argument optional);
 9653: returns the data handle
 9654: 
 9655: =item *
 9656: 
 9657: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 9658: a possible symb for the URL in $thisfn, and if is an encryypted
 9659: resource that the user accessed using /enc/ returns a 1 on success, 0
 9660: on failure, user must be in a course, as it assumes the existance of
 9661: the course initial hash, and uses $env('request.course.id'}
 9662: 
 9663: 
 9664: =item *
 9665: 
 9666: symbclean($symb) : removes versions numbers from a symb, returns the
 9667: cleaned symb
 9668: 
 9669: =item *
 9670: 
 9671: is_on_map($uri) : checks if the $uri is somewhere on the current
 9672: course map, user must be in a course for it to work.
 9673: 
 9674: =item *
 9675: 
 9676: numval($salt) : return random seed value (addend for rndseed)
 9677: 
 9678: =item *
 9679: 
 9680: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 9681: a random seed, all arguments are optional, if they aren't sent it uses the
 9682: environment to derive them. Note: if symb isn't sent and it can't get one
 9683: from &symbread it will use the current time as its return value
 9684: 
 9685: =item *
 9686: 
 9687: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 9688: unfakeable, receipt
 9689: 
 9690: =item *
 9691: 
 9692: receipt() : API to ireceipt working off of env values; given out to users
 9693: 
 9694: =item *
 9695: 
 9696: countacc($url) : count the number of accesses to a given URL
 9697: 
 9698: =item *
 9699: 
 9700: 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
 9701: 
 9702: =item *
 9703: 
 9704: 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)
 9705: 
 9706: =item *
 9707: 
 9708: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 9709: 
 9710: =item *
 9711: 
 9712: devalidate($symb) : devalidate temporary spreadsheet calculations,
 9713: forcing spreadsheet to reevaluate the resource scores next time.
 9714: 
 9715: =back
 9716: 
 9717: =head2 Storing/Retreiving Data
 9718: 
 9719: =over 4
 9720: 
 9721: =item *
 9722: 
 9723: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 9724: for this url; hashref needs to be given and should be a \%hashname; the
 9725: remaining args aren't required and if they aren't passed or are '' they will
 9726: be derived from the env
 9727: 
 9728: =item *
 9729: 
 9730: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 9731: uses critical subroutine
 9732: 
 9733: =item *
 9734: 
 9735: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 9736: all args are optional
 9737: 
 9738: =item *
 9739: 
 9740: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 9741: dumps the complete (or key matching regexp) namespace into a hash
 9742: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 9743: normally &store()ed into
 9744: 
 9745: $range should be either an integer '100' (give me the first 100
 9746:                                            matching records)
 9747:               or be  two integers sperated by a - with no spaces
 9748:                  '30-50' (give me the 30th through the 50th matching
 9749:                           records)
 9750: 
 9751: 
 9752: =item *
 9753: 
 9754: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 9755: replaces a &store() version of data with a replacement set of data
 9756: for a particular resource in a namespace passed in the $storehash hash 
 9757: reference
 9758: 
 9759: =item *
 9760: 
 9761: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 9762: works very similar to store/cstore, but all data is stored in a
 9763: temporary location and can be reset using tmpreset, $storehash should
 9764: be a hash reference, returns nothing on success
 9765: 
 9766: =item *
 9767: 
 9768: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 9769: similar to restore, but all data is stored in a temporary location and
 9770: can be reset using tmpreset. Returns a hash of values on success,
 9771: error string otherwise.
 9772: 
 9773: =item *
 9774: 
 9775: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 9776: deltes all keys for $symb form the temporary storage hash.
 9777: 
 9778: =item *
 9779: 
 9780: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9781: reference filled in from namesp ($udom and $uname are optional)
 9782: 
 9783: =item *
 9784: 
 9785: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 9786: namesp ($udom and $uname are optional)
 9787: 
 9788: =item *
 9789: 
 9790: dump($namespace,$udom,$uname,$regexp,$range) : 
 9791: dumps the complete (or key matching regexp) namespace into a hash
 9792: ($udom, $uname, $regexp, $range are optional)
 9793: 
 9794: $range should be either an integer '100' (give me the first 100
 9795:                                            matching records)
 9796:               or be  two integers sperated by a - with no spaces
 9797:                  '30-50' (give me the 30th through the 50th matching
 9798:                           records)
 9799: =item *
 9800: 
 9801: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 9802: $store can be a scalar, an array reference, or if the amount to be 
 9803: incremented is > 1, a hash reference.
 9804: 
 9805: ($udom and $uname are optional)
 9806: 
 9807: =item *
 9808: 
 9809: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 9810: ($udom and $uname are optional)
 9811: 
 9812: =item *
 9813: 
 9814: cput($namespace,$storehash,$udom,$uname) : critical put
 9815: ($udom and $uname are optional)
 9816: 
 9817: =item *
 9818: 
 9819: newput($namespace,$storehash,$udom,$uname) :
 9820: 
 9821: Attempts to store the items in the $storehash, but only if they don't
 9822: currently exist, if this succeeds you can be certain that you have 
 9823: successfully created a new key value pair in the $namespace db.
 9824: 
 9825: 
 9826: Args:
 9827:  $namespace: name of database to store values to
 9828:  $storehash: hashref to store to the db
 9829:  $udom: (optional) domain of user containing the db
 9830:  $uname: (optional) name of user caontaining the db
 9831: 
 9832: Returns:
 9833:  'ok' -> succeeded in storing all keys of $storehash
 9834:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 9835:                         least <key> already existed in the db (other
 9836:                         requested keys may also already exist)
 9837:  'error: <msg>' -> unable to tie the DB or other error occurred
 9838:  'con_lost' -> unable to contact request server
 9839:  'refused' -> action was not allowed by remote machine
 9840: 
 9841: 
 9842: =item *
 9843: 
 9844: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9845: reference filled in from namesp (encrypts the return communication)
 9846: ($udom and $uname are optional)
 9847: 
 9848: =item *
 9849: 
 9850: log($udom,$name,$home,$message) : write to permanent log for user; use
 9851: critical subroutine
 9852: 
 9853: =item *
 9854: 
 9855: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
 9856: array reference filled in from namespace found in domain level on either
 9857: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
 9858: 
 9859: =item *
 9860: 
 9861: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
 9862: domain level either on specified domain server ($uhome) or primary domain 
 9863: server ($udom and $uhome are optional)
 9864: 
 9865: =item * 
 9866: 
 9867: get_domain_defaults($target_domain) : returns hash with defaults for
 9868: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
 9869: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
 9870: or localauth), initial password or a kerberos realm, language (e.g., en-us).
 9871: Values are retrieved from cache (if current), or from domain's configuration.db
 9872: (if available), or lastly from values in lonTabs/dns_domain,tab, 
 9873: or lonTabs/domain.tab. 
 9874: 
 9875: %domdefaults = &get_auth_defaults($target_domain);
 9876: 
 9877: =back
 9878: 
 9879: =head2 Network Status Functions
 9880: 
 9881: =over 4
 9882: 
 9883: =item *
 9884: 
 9885: dirlist($uri) : return directory list based on URI
 9886: 
 9887: =item *
 9888: 
 9889: spareserver() : find server with least workload from spare.tab
 9890: 
 9891: =back
 9892: 
 9893: =head2 Apache Request
 9894: 
 9895: =over 4
 9896: 
 9897: =item *
 9898: 
 9899: ssi($url,%hash) : server side include, does a complete request cycle on url to
 9900: localhost, posts hash
 9901: 
 9902: =back
 9903: 
 9904: =head2 Data to String to Data
 9905: 
 9906: =over 4
 9907: 
 9908: =item *
 9909: 
 9910: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 9911: and '&' separators, supports elements that are arrayrefs and hashrefs
 9912: 
 9913: =item *
 9914: 
 9915: hashref2str($hashref) : convert a hashref into a string complete with
 9916: escaping and '=' and '&' separators, supports elements that are
 9917: arrayrefs and hashrefs
 9918: 
 9919: =item *
 9920: 
 9921: arrayref2str($arrayref) : convert an arrayref into a string complete
 9922: with escaping and '&' separators, supports elements that are arrayrefs
 9923: and hashrefs
 9924: 
 9925: =item *
 9926: 
 9927: str2hash($string) : convert string to hash using unescaping and
 9928: splitting on '=' and '&', supports elements that are arrayrefs and
 9929: hashrefs
 9930: 
 9931: =item *
 9932: 
 9933: str2array($string) : convert string to hash using unescaping and
 9934: splitting on '&', supports elements that are arrayrefs and hashrefs
 9935: 
 9936: =back
 9937: 
 9938: =head2 Logging Routines
 9939: 
 9940: =over 4
 9941: 
 9942: These routines allow one to make log messages in the lonnet.log and
 9943: lonnet.perm logfiles.
 9944: 
 9945: =item *
 9946: 
 9947: logtouch() : make sure the logfile, lonnet.log, exists
 9948: 
 9949: =item *
 9950: 
 9951: logthis() : append message to the normal lonnet.log file, it gets
 9952: preiodically rolled over and deleted.
 9953: 
 9954: =item *
 9955: 
 9956: logperm() : append a permanent message to lonnet.perm.log, this log
 9957: file never gets deleted by any automated portion of the system, only
 9958: messages of critical importance should go in here.
 9959: 
 9960: =back
 9961: 
 9962: =head2 General File Helper Routines
 9963: 
 9964: =over 4
 9965: 
 9966: =item *
 9967: 
 9968: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 9969: (a) files in /uploaded
 9970:   (i) If a local copy of the file exists - 
 9971:       compares modification date of local copy with last-modified date for 
 9972:       definitive version stored on home server for course. If local copy is 
 9973:       stale, requests a new version from the home server and stores it. 
 9974:       If the original has been removed from the home server, then local copy 
 9975:       is unlinked.
 9976:   (ii) If local copy does not exist -
 9977:       requests the file from the home server and stores it. 
 9978:   
 9979:   If $caller is 'uploadrep':  
 9980:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 9981:     for request for files originally uploaded via DOCS. 
 9982:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 9983:   
 9984:   Otherwise:
 9985:      This indicates a call from the content generation phase of the request.
 9986:      -  returns the entire contents of the file or -1.
 9987:      
 9988: (b) files in /res
 9989:    - returns the entire contents of a file or -1; 
 9990:    it properly subscribes to and replicates the file if neccessary.
 9991: 
 9992: 
 9993: =item *
 9994: 
 9995: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 9996:                   reference
 9997: 
 9998: returns either a stat() list of data about the file or an empty list
 9999: if the file doesn't exist or couldn't find out about it (connection
10000: problems or user unknown)
10001: 
10002: =item *
10003: 
10004: filelocation($dir,$file) : returns file system location of a file
10005: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10006: directory that relative $file lookups are to looked in ($dir of /a/dir
10007: and a file of ../bob will become /a/bob)
10008: 
10009: =item *
10010: 
10011: hreflocation($dir,$file) : returns file system location or a URL; same as
10012: filelocation except for hrefs
10013: 
10014: =item *
10015: 
10016: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10017: 
10018: =back
10019: 
10020: =head2 Usererfile file routines (/uploaded*)
10021: 
10022: =over 4
10023: 
10024: =item *
10025: 
10026: userfileupload(): main rotine for putting a file in a user or course's
10027:                   filespace, arguments are,
10028: 
10029:  formname - required - this is the name of the element in $env where the
10030:            filename, and the contents of the file to create/modifed exist
10031:            the filename is in $env{'form.'.$formname.'.filename'} and the
10032:            contents of the file is located in $env{'form.'.$formname}
10033:  coursedoc - if true, store the file in the course of the active role
10034:              of the current user
10035:  subdir - required - subdirectory to put the file in under ../userfiles/
10036:          if undefined, it will be placed in "unknown"
10037: 
10038:  (This routine calls clean_filename() to remove any dangerous
10039:  characters from the filename, and then calls finuserfileupload() to
10040:  complete the transaction)
10041: 
10042:  returns either the url of the uploaded file (/uploaded/....) if successful
10043:  and /adm/notfound.html if unsuccessful
10044: 
10045: =item *
10046: 
10047: clean_filename(): routine for cleaing a filename up for storage in
10048:                  userfile space, argument is:
10049: 
10050:  filename - proposed filename
10051: 
10052: returns: the new clean filename
10053: 
10054: =item *
10055: 
10056: finishuserfileupload(): routine that creaes and sends the file to
10057: userspace, probably shouldn't be called directly
10058: 
10059:   docuname: username or courseid of destination for the file
10060:   docudom: domain of user/course of destination for the file
10061:   formname: same as for userfileupload()
10062:   fname: filename (inculding subdirectories) for the file
10063: 
10064:  returns either the url of the uploaded file (/uploaded/....) if successful
10065:  and /adm/notfound.html if unsuccessful
10066: 
10067: =item *
10068: 
10069: renameuserfile(): renames an existing userfile to a new name
10070: 
10071:   Args:
10072:    docuname: username or courseid of destination for the file
10073:    docudom: domain of user/course of destination for the file
10074:    old: current file name (including any subdirs under userfiles)
10075:    new: desired file name (including any subdirs under userfiles)
10076: 
10077: =item *
10078: 
10079: mkdiruserfile(): creates a directory is a userfiles dir
10080: 
10081:   Args:
10082:    docuname: username or courseid of destination for the file
10083:    docudom: domain of user/course of destination for the file
10084:    dir: dir to create (including any subdirs under userfiles)
10085: 
10086: =item *
10087: 
10088: removeuserfile(): removes a file that exists in userfiles
10089: 
10090:   Args:
10091:    docuname: username or courseid of destination for the file
10092:    docudom: domain of user/course of destination for the file
10093:    fname: filname to delete (including any subdirs under userfiles)
10094: 
10095: =item *
10096: 
10097: removeuploadedurl(): convience function for removeuserfile()
10098: 
10099:   Args:
10100:    url:  a full /uploaded/... url to delete
10101: 
10102: =item * 
10103: 
10104: get_portfile_permissions():
10105:   Args:
10106:     domain: domain of user or course contain the portfolio files
10107:     user: name of user or num of course contain the portfolio files
10108:   Returns:
10109:     hashref of a dump of the proper file_permissions.db
10110:    
10111: 
10112: =item * 
10113: 
10114: get_access_controls():
10115: 
10116: Args:
10117:   current_permissions: the hash ref returned from get_portfile_permissions()
10118:   group: (optional) the group you want the files associated with
10119:   file: (optional) the file you want access info on
10120: 
10121: Returns:
10122:     a hash (keys are file names) of hashes containing
10123:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10124:         values are XML containing access control settings (see below) 
10125: 
10126: Internal notes:
10127: 
10128:  access controls are stored in file_permissions.db as key=value pairs.
10129:     key -> path to file/file_name\0uniqueID:scope_end_start
10130:         where scope -> public,guest,course,group,domains or users.
10131:               end -> UNIX time for end of access (0 -> no end date)
10132:               start -> UNIX time for start of access
10133: 
10134:     value -> XML description of access control
10135:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10136:             <start></start>
10137:             <end></end>
10138: 
10139:             <password></password>  for scope type = guest
10140: 
10141:             <domain></domain>     for scope type = course or group
10142:             <number></number>
10143:             <roles id="">
10144:              <role></role>
10145:              <access></access>
10146:              <section></section>
10147:              <group></group>
10148:             </roles>
10149: 
10150:             <dom></dom>         for scope type = domains
10151: 
10152:             <users>             for scope type = users
10153:              <user>
10154:               <uname></uname>
10155:               <udom></udom>
10156:              </user>
10157:             </users>
10158:            </scope> 
10159:               
10160:  Access data is also aggregated for each file in an additional key=value pair:
10161:  key -> path to file/file_name\0accesscontrol 
10162:  value -> reference to hash
10163:           hash contains key = value pairs
10164:           where key = uniqueID:scope_end_start
10165:                 value = UNIX time record was last updated
10166: 
10167:           Used to improve speed of look-ups of access controls for each file.  
10168:  
10169:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10170: 
10171: modify_access_controls():
10172: 
10173: Modifies access controls for a portfolio file
10174: Args
10175: 1. file name
10176: 2. reference to hash of required changes,
10177: 3. domain
10178: 4. username
10179:   where domain,username are the domain of the portfolio owner 
10180:   (either a user or a course) 
10181: 
10182: Returns:
10183: 1. result of additions or updates ('ok' or 'error', with error message). 
10184: 2. result of deletions ('ok' or 'error', with error message).
10185: 3. reference to hash of any new or updated access controls.
10186: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10187:    key = integer (inbound ID)
10188:    value = uniqueID  
10189: 
10190: =back
10191: 
10192: =head2 HTTP Helper Routines
10193: 
10194: =over 4
10195: 
10196: =item *
10197: 
10198: escape() : unpack non-word characters into CGI-compatible hex codes
10199: 
10200: =item *
10201: 
10202: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10203: 
10204: =back
10205: 
10206: =head1 PRIVATE SUBROUTINES
10207: 
10208: =head2 Underlying communication routines (Shouldn't call)
10209: 
10210: =over 4
10211: 
10212: =item *
10213: 
10214: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10215: 
10216: =item *
10217: 
10218: reply() : uses subreply to send a message to remote machine, logs all failures
10219: 
10220: =item *
10221: 
10222: critical() : passes a critical message to another server; if cannot
10223: get through then place message in connection buffer directory and
10224: returns con_delayed, if incapable of saving message, returns
10225: con_failed
10226: 
10227: =item *
10228: 
10229: reconlonc() : tries to reconnect lonc client processes.
10230: 
10231: =back
10232: 
10233: =head2 Resource Access Logging
10234: 
10235: =over 4
10236: 
10237: =item *
10238: 
10239: flushcourselogs() : flush (save) buffer logs and access logs
10240: 
10241: =item *
10242: 
10243: courselog($what) : save message for course in hash
10244: 
10245: =item *
10246: 
10247: courseacclog($what) : save message for course using &courselog().  Perform
10248: special processing for specific resource types (problems, exams, quizzes, etc).
10249: 
10250: =item *
10251: 
10252: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10253: as a PerlChildExitHandler
10254: 
10255: =back
10256: 
10257: =head2 Other
10258: 
10259: =over 4
10260: 
10261: =item *
10262: 
10263: symblist($mapname,%newhash) : update symbolic storage links
10264: 
10265: =back
10266: 
10267: =cut
10268: 

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