File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.976: download - view: text, annotated - select for diffs
Mon Dec 8 23:00:47 2008 UTC (15 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_8_X, HEAD, GCI_1
- Bug 5839. Cache information about availability of User Tools (About Me, Portfolio, Blog) for users in a domain.
- Availability determined by user-specific setting in user's environment.db (set by DC) or on domain defaults for user's insitutional affilaition.
- User tools available by default for users from domains on pre-2.8 versions, and domains for which DC has yet to set defaults.
- New routines: &usertools_access() and &is_advanced_user().
- Changes to &get_domain_defaults() so defaults for user tool availability are provided from this routine, and also to support change in storage  of quota defaults.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.976 2008/12/08 23:00:47 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: 
  181: # -------------------------------------------------- Non-critical communication
  182: sub subreply {
  183:     my ($cmd,$server)=@_;
  184:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  185:     #
  186:     #  With loncnew process trimming, there's a timing hole between lonc server
  187:     #  process exit and the master server picking up the listen on the AF_UNIX
  188:     #  socket.  In that time interval, a lock file will exist:
  189: 
  190:     my $lockfile=$peerfile.".lock";
  191:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  192: 	sleep(1);
  193:     }
  194:     # At this point, either a loncnew parent is listening or an old lonc
  195:     # or loncnew child is listening so we can connect or everything's dead.
  196:     #
  197:     #   We'll give the connection a few tries before abandoning it.  If
  198:     #   connection is not possible, we'll con_lost back to the client.
  199:     #   
  200:     my $client;
  201:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  202: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  203: 				      Type    => SOCK_STREAM,
  204: 				      Timeout => 10);
  205: 	if ($client) {
  206: 	    last;		# Connected!
  207: 	} else {
  208: 	    &create_connection(&hostname($server),$server);
  209: 	}
  210:         sleep(1);		# Try again later if failed connection.
  211:     }
  212:     my $answer;
  213:     if ($client) {
  214: 	print $client "sethost:$server:$cmd\n";
  215: 	$answer=<$client>;
  216: 	if (!$answer) { $answer="con_lost"; }
  217: 	chomp($answer);
  218:     } else {
  219: 	$answer = 'con_lost';	# Failed connection.
  220:     }
  221:     return $answer;
  222: }
  223: 
  224: sub reply {
  225:     my ($cmd,$server)=@_;
  226:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  227:     my $answer=subreply($cmd,$server);
  228:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  229:        &logthis("<font color=\"blue\">WARNING:".
  230:                 " $cmd to $server returned $answer</font>");
  231:     }
  232:     return $answer;
  233: }
  234: 
  235: # ----------------------------------------------------------- Send USR1 to lonc
  236: 
  237: sub reconlonc {
  238:     my ($lonid) = @_;
  239:     my $hostname = &hostname($lonid);
  240:     if ($lonid) {
  241: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  242: 	if ($hostname && -e $peerfile) {
  243: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  244: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  245: 					     Type    => SOCK_STREAM,
  246: 					     Timeout => 10);
  247: 	    if ($client) {
  248: 		print $client ("reset_retries\n");
  249: 		my $answer=<$client>;
  250: 		#reset just this one.
  251: 	    }
  252: 	}
  253: 	return;
  254:     }
  255: 
  256:     &logthis("Trying to reconnect lonc");
  257:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  258:     if (open(my $fh,"<$loncfile")) {
  259: 	my $loncpid=<$fh>;
  260:         chomp($loncpid);
  261:         if (kill 0 => $loncpid) {
  262: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  263:             kill USR1 => $loncpid;
  264:             sleep 1;
  265:          } else {
  266: 	    &logthis(
  267:                "<font color=\"blue\">WARNING:".
  268:                " lonc at pid $loncpid not responding, giving up</font>");
  269:         }
  270:     } else {
  271: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  272:     }
  273: }
  274: 
  275: # ------------------------------------------------------ Critical communication
  276: 
  277: sub critical {
  278:     my ($cmd,$server)=@_;
  279:     unless (&hostname($server)) {
  280:         &logthis("<font color=\"blue\">WARNING:".
  281:                " Critical message to unknown server ($server)</font>");
  282:         return 'no_such_host';
  283:     }
  284:     my $answer=reply($cmd,$server);
  285:     if ($answer eq 'con_lost') {
  286: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  287: 	my $answer=reply($cmd,$server);
  288:         if ($answer eq 'con_lost') {
  289:             my $now=time;
  290:             my $middlename=$cmd;
  291:             $middlename=substr($middlename,0,16);
  292:             $middlename=~s/\W//g;
  293:             my $dfilename=
  294:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  295:             $dumpcount++;
  296:             {
  297: 		my $dfh;
  298: 		if (open($dfh,">$dfilename")) {
  299: 		    print $dfh "$cmd\n"; 
  300: 		    close($dfh);
  301: 		}
  302:             }
  303:             sleep 2;
  304:             my $wcmd='';
  305:             {
  306: 		my $dfh;
  307: 		if (open($dfh,"<$dfilename")) {
  308: 		    $wcmd=<$dfh>; 
  309: 		    close($dfh);
  310: 		}
  311:             }
  312:             chomp($wcmd);
  313:             if ($wcmd eq $cmd) {
  314: 		&logthis("<font color=\"blue\">WARNING: ".
  315:                          "Connection buffer $dfilename: $cmd</font>");
  316:                 &logperm("D:$server:$cmd");
  317: 	        return 'con_delayed';
  318:             } else {
  319:                 &logthis("<font color=\"red\">CRITICAL:"
  320:                         ." Critical connection failed: $server $cmd</font>");
  321:                 &logperm("F:$server:$cmd");
  322:                 return 'con_failed';
  323:             }
  324:         }
  325:     }
  326:     return $answer;
  327: }
  328: 
  329: # ------------------------------------------- check if return value is an error
  330: 
  331: sub error {
  332:     my ($result) = @_;
  333:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  334: 	if ($2 == 2) { return undef; }
  335: 	return $1;
  336:     }
  337:     return undef;
  338: }
  339: 
  340: sub convert_and_load_session_env {
  341:     my ($lonidsdir,$handle)=@_;
  342:     my @profile;
  343:     {
  344: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  345: 	if (!$opened) {
  346: 	    return 0;
  347: 	}
  348: 	flock($idf,LOCK_SH);
  349: 	@profile=<$idf>;
  350: 	close($idf);
  351:     }
  352:     my %temp_env;
  353:     foreach my $line (@profile) {
  354: 	if ($line !~ m/=/) {
  355: 	    return 0;
  356: 	}
  357: 	chomp($line);
  358: 	my ($envname,$envvalue)=split(/=/,$line,2);
  359: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  360:     }
  361:     unlink("$lonidsdir/$handle.id");
  362:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  363: 	    0640)) {
  364: 	%disk_env = %temp_env;
  365: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  366: 	untie(%disk_env);
  367:     }
  368:     return 1;
  369: }
  370: 
  371: # ------------------------------------------- Transfer profile into environment
  372: my $env_loaded;
  373: sub transfer_profile_to_env {
  374:     my ($lonidsdir,$handle,$force_transfer) = @_;
  375:     if (!$force_transfer && $env_loaded) { return; } 
  376: 
  377:     if (!defined($lonidsdir)) {
  378: 	$lonidsdir = $perlvar{'lonIDsDir'};
  379:     }
  380:     if (!defined($handle)) {
  381:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  382:     }
  383: 
  384:     my $convert;
  385:     {
  386:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  387: 	if (!$opened) {
  388: 	    return;
  389: 	}
  390: 	flock($idf,LOCK_SH);
  391: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  392: 		&GDBM_READER(),0640)) {
  393: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  394: 	    untie(%disk_env);
  395: 	} else {
  396: 	    $convert = 1;
  397: 	}
  398:     }
  399:     if ($convert) {
  400: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  401: 	    &logthis("Failed to load session, or convert session.");
  402: 	}
  403:     }
  404: 
  405:     my %remove;
  406:     while ( my $envname = each(%env) ) {
  407:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  408:             if ($time < time-300) {
  409:                 $remove{$key}++;
  410:             }
  411:         }
  412:     }
  413: 
  414:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  415:     $env_loaded=1;
  416:     foreach my $expired_key (keys(%remove)) {
  417:         &delenv($expired_key);
  418:     }
  419: }
  420: 
  421: # ---------------------------------------------------- Check for valid session 
  422: sub check_for_valid_session {
  423:     my ($r) = @_;
  424:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  425:     my $lonid=$cookies{'lonID'};
  426:     return undef if (!$lonid);
  427: 
  428:     my $handle=&LONCAPA::clean_handle($lonid->value);
  429:     my $lonidsdir=$r->dir_config('lonIDsDir');
  430:     return undef if (!-e "$lonidsdir/$handle.id");
  431: 
  432:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  433:     return undef if (!$opened);
  434: 
  435:     flock($idf,LOCK_SH);
  436:     my %disk_env;
  437:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  438: 	    &GDBM_READER(),0640)) {
  439: 	return undef;	
  440:     }
  441: 
  442:     if (!defined($disk_env{'user.name'})
  443: 	|| !defined($disk_env{'user.domain'})) {
  444: 	return undef;
  445:     }
  446:     return $handle;
  447: }
  448: 
  449: sub timed_flock {
  450:     my ($file,$lock_type) = @_;
  451:     my $failed=0;
  452:     eval {
  453: 	local $SIG{__DIE__}='DEFAULT';
  454: 	local $SIG{ALRM}=sub {
  455: 	    $failed=1;
  456: 	    die("failed lock");
  457: 	};
  458: 	alarm(13);
  459: 	flock($file,$lock_type);
  460: 	alarm(0);
  461:     };
  462:     if ($failed) {
  463: 	return undef;
  464:     } else {
  465: 	return 1;
  466:     }
  467: }
  468: 
  469: # ---------------------------------------------------------- Append Environment
  470: 
  471: sub appenv {
  472:     my ($newenv,$roles) = @_;
  473:     if (ref($newenv) eq 'HASH') {
  474:         foreach my $key (keys(%{$newenv})) {
  475:             my $refused = 0;
  476: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  477:                 $refused = 1;
  478:                 if (ref($roles) eq 'ARRAY') {
  479:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  480:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  481:                         $refused = 0;
  482:                     }
  483:                 }
  484:             }
  485:             if ($refused) {
  486:                 &logthis("<font color=\"blue\">WARNING: ".
  487:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  488:                          .'</font>');
  489: 	        delete($newenv->{$key});
  490:             } else {
  491:                 $env{$key}=$newenv->{$key};
  492:             }
  493:         }
  494:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  495:         if ($opened
  496: 	    && &timed_flock($env_file,LOCK_EX)
  497: 	    &&
  498: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  499: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  500: 	    while (my ($key,$value) = each(%{$newenv})) {
  501: 	        $disk_env{$key} = $value;
  502: 	    }
  503: 	    untie(%disk_env);
  504:         }
  505:     }
  506:     return 'ok';
  507: }
  508: # ----------------------------------------------------- Delete from Environment
  509: 
  510: sub delenv {
  511:     my $delthis=shift;
  512:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  513:         &logthis("<font color=\"blue\">WARNING: ".
  514:                 "Attempt to delete from environment ".$delthis);
  515:         return 'error';
  516:     }
  517:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  518:     if ($opened
  519: 	&& &timed_flock($env_file,LOCK_EX)
  520: 	&&
  521: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  522: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  523: 	foreach my $key (keys(%disk_env)) {
  524: 	    if ($key=~/^$delthis/) { 
  525: 		delete($env{$key});
  526: 		delete($disk_env{$key});
  527: 	    }
  528: 	}
  529: 	untie(%disk_env);
  530:     }
  531:     return 'ok';
  532: }
  533: 
  534: sub get_env_multiple {
  535:     my ($name) = @_;
  536:     my @values;
  537:     if (defined($env{$name})) {
  538:         # exists is it an array
  539:         if (ref($env{$name})) {
  540:             @values=@{ $env{$name} };
  541:         } else {
  542:             $values[0]=$env{$name};
  543:         }
  544:     }
  545:     return(@values);
  546: }
  547: 
  548: # ------------------------------------------------------------------- Locking
  549: 
  550: sub set_lock {
  551:     my ($text)=@_;
  552:     $locknum++;
  553:     my $id=$$.'-'.$locknum;
  554:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  555:              'session.lock.'.$id => $text});
  556:     return $id;
  557: }
  558: 
  559: sub get_locks {
  560:     my $num=0;
  561:     my %texts=();
  562:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  563:        if ($lock=~/\w/) {
  564:           $num++;
  565:           $texts{$lock}=$env{'session.lock.'.$lock};
  566:        }
  567:    }
  568:    return ($num,%texts);
  569: }
  570: 
  571: sub remove_lock {
  572:     my ($id)=@_;
  573:     my $newlocks='';
  574:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  575:        if (($lock=~/\w/) && ($lock ne $id)) {
  576:           $newlocks.=','.$lock;
  577:        }
  578:     }
  579:     &appenv({'session.locks' => $newlocks});
  580:     &delenv('session.lock.'.$id);
  581: }
  582: 
  583: sub remove_all_locks {
  584:     my $activelocks=$env{'session.locks'};
  585:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  586:        if ($lock=~/\w/) {
  587:           &remove_lock($lock);
  588:        }
  589:     }
  590: }
  591: 
  592: 
  593: # ------------------------------------------ Find out current server userload
  594: sub userload {
  595:     my $numusers=0;
  596:     {
  597: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  598: 	my $filename;
  599: 	my $curtime=time;
  600: 	while ($filename=readdir(LONIDS)) {
  601: 	    next if ($filename eq '.' || $filename eq '..');
  602: 	    next if ($filename =~ /publicuser_\d+\.id/);
  603: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  604: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  605: 	}
  606: 	closedir(LONIDS);
  607:     }
  608:     my $userloadpercent=0;
  609:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  610:     if ($maxuserload) {
  611: 	$userloadpercent=100*$numusers/$maxuserload;
  612:     }
  613:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  614:     return $userloadpercent;
  615: }
  616: 
  617: # ------------------------------------------ Fight off request when overloaded
  618: 
  619: sub overloaderror {
  620:     my ($r,$checkserver)=@_;
  621:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  622:     my $loadavg;
  623:     if ($checkserver eq $perlvar{'lonHostID'}) {
  624:        open(my $loadfile,'/proc/loadavg');
  625:        $loadavg=<$loadfile>;
  626:        $loadavg =~ s/\s.*//g;
  627:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  628:        close($loadfile);
  629:     } else {
  630:        $loadavg=&reply('load',$checkserver);
  631:     }
  632:     my $overload=$loadavg-100;
  633:     if ($overload>0) {
  634: 	$r->err_headers_out->{'Retry-After'}=$overload;
  635:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  636:         return 413;
  637:     }    
  638:     return '';
  639: }
  640: 
  641: # ------------------------------ Find server with least workload from spare.tab
  642: 
  643: sub spareserver {
  644:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  645:     my $spare_server;
  646:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  647:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  648:                                                      :  $userloadpercent;
  649:     
  650:     foreach my $try_server (@{ $spareid{'primary'} }) {
  651: 	($spare_server, $lowest_load) =
  652: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  653:     }
  654: 
  655:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  656: 
  657:     if (!$found_server) {
  658: 	foreach my $try_server (@{ $spareid{'default'} }) {
  659: 	    ($spare_server, $lowest_load) =
  660: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  661: 	}
  662:     }
  663: 
  664:     if (!$want_server_name) {
  665:         my $protocol = 'http';
  666:         if ($protocol{$spare_server} eq 'https') {
  667:             $protocol = $protocol{$spare_server};
  668:         }
  669: 	$spare_server = $protocol.'://'.&hostname($spare_server);
  670:     }
  671:     return $spare_server;
  672: }
  673: 
  674: sub compare_server_load {
  675:     my ($try_server, $spare_server, $lowest_load) = @_;
  676: 
  677:     my $loadans     = &reply('load',    $try_server);
  678:     my $userloadans = &reply('userload',$try_server);
  679: 
  680:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  681: 	next; #didn't get a number from the server
  682:     }
  683: 
  684:     my $load;
  685:     if ($loadans =~ /\d/) {
  686: 	if ($userloadans =~ /\d/) {
  687: 	    #both are numbers, pick the bigger one
  688: 	    $load = ($loadans > $userloadans) ? $loadans 
  689: 		                              : $userloadans;
  690: 	} else {
  691: 	    $load = $loadans;
  692: 	}
  693:     } else {
  694: 	$load = $userloadans;
  695:     }
  696: 
  697:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  698: 	$spare_server = $try_server;
  699: 	$lowest_load  = $load;
  700:     }
  701:     return ($spare_server,$lowest_load);
  702: }
  703: 
  704: # --------------------------- ask offload servers if user already has a session
  705: sub find_existing_session {
  706:     my ($udom,$uname) = @_;
  707:     foreach my $try_server (@{ $spareid{'primary'} },
  708: 			    @{ $spareid{'default'} }) {
  709: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
  710:     }
  711:     return;
  712: }
  713: 
  714: # -------------------------------- ask if server already has a session for user
  715: sub has_user_session {
  716:     my ($lonid,$udom,$uname) = @_;
  717:     my $result = &reply(join(':','userhassession',
  718: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  719:     return 1 if ($result eq 'ok');
  720: 
  721:     return 0;
  722: }
  723: 
  724: # --------------------------------------------- Try to change a user's password
  725: 
  726: sub changepass {
  727:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  728:     $currentpass = &escape($currentpass);
  729:     $newpass     = &escape($newpass);
  730:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  731: 		       $server);
  732:     if (! $answer) {
  733: 	&logthis("No reply on password change request to $server ".
  734: 		 "by $uname in domain $udom.");
  735:     } elsif ($answer =~ "^ok") {
  736:         &logthis("$uname in $udom successfully changed their password ".
  737: 		 "on $server.");
  738:     } elsif ($answer =~ "^pwchange_failure") {
  739: 	&logthis("$uname in $udom was unable to change their password ".
  740: 		 "on $server.  The action was blocked by either lcpasswd ".
  741: 		 "or pwchange");
  742:     } elsif ($answer =~ "^non_authorized") {
  743:         &logthis("$uname in $udom did not get their password correct when ".
  744: 		 "attempting to change it on $server.");
  745:     } elsif ($answer =~ "^auth_mode_error") {
  746:         &logthis("$uname in $udom attempted to change their password despite ".
  747: 		 "not being locally or internally authenticated on $server.");
  748:     } elsif ($answer =~ "^unknown_user") {
  749:         &logthis("$uname in $udom attempted to change their password ".
  750: 		 "on $server but were unable to because $server is not ".
  751: 		 "their home server.");
  752:     } elsif ($answer =~ "^refused") {
  753: 	&logthis("$server refused to change $uname in $udom password because ".
  754: 		 "it was sent an unencrypted request to change the password.");
  755:     }
  756:     return $answer;
  757: }
  758: 
  759: # ----------------------- Try to determine user's current authentication scheme
  760: 
  761: sub queryauthenticate {
  762:     my ($uname,$udom)=@_;
  763:     my $uhome=&homeserver($uname,$udom);
  764:     if (!$uhome) {
  765: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  766: 	return 'no_host';
  767:     }
  768:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  769:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  770: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  771:     }
  772:     return $answer;
  773: }
  774: 
  775: # --------- Try to authenticate user from domain's lib servers (first this one)
  776: 
  777: sub authenticate {
  778:     my ($uname,$upass,$udom,$checkdefauth)=@_;
  779:     $upass=&escape($upass);
  780:     $uname= &LONCAPA::clean_username($uname);
  781:     my $uhome=&homeserver($uname,$udom,1);
  782:     my $newhome;
  783:     if ((!$uhome) || ($uhome eq 'no_host')) {
  784: # Maybe the machine was offline and only re-appeared again recently?
  785:         &reconlonc();
  786: # One more
  787: 	$uhome=&homeserver($uname,$udom,1);
  788:         if (($uhome eq 'no_host') && $checkdefauth) {
  789:             if (defined(&domain($udom,'primary'))) {
  790:                 $newhome=&domain($udom,'primary');
  791:             }
  792:             if ($newhome ne '') {
  793:                 $uhome = $newhome;
  794:             }
  795:         }
  796: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  797: 	    &logthis("User $uname at $udom is unknown in authenticate");
  798: 	    return 'no_host';
  799:         }
  800:     }
  801:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
  802:     if ($answer eq 'authorized') {
  803:         if ($newhome) {
  804:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
  805:             return 'no_account_on_host'; 
  806:         } else {
  807:             &logthis("User $uname at $udom authorized by $uhome");
  808:             return $uhome;
  809:         }
  810:     }
  811:     if ($answer eq 'non_authorized') {
  812: 	&logthis("User $uname at $udom rejected by $uhome");
  813: 	return 'no_host'; 
  814:     }
  815:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  816:     return 'no_host';
  817: }
  818: 
  819: # ---------------------- Find the homebase for a user from domain's lib servers
  820: 
  821: my %homecache;
  822: sub homeserver {
  823:     my ($uname,$udom,$ignoreBadCache)=@_;
  824:     my $index="$uname:$udom";
  825: 
  826:     if (exists($homecache{$index})) { return $homecache{$index}; }
  827: 
  828:     my %servers = &get_servers($udom,'library');
  829:     foreach my $tryserver (keys(%servers)) {
  830:         next if ($ignoreBadCache ne 'true' && 
  831: 		 exists($badServerCache{$tryserver}));
  832: 
  833: 	my $answer=reply("home:$udom:$uname",$tryserver);
  834: 	if ($answer eq 'found') {
  835: 	    delete($badServerCache{$tryserver}); 
  836: 	    return $homecache{$index}=$tryserver;
  837: 	} elsif ($answer eq 'no_host') {
  838: 	    $badServerCache{$tryserver}=1;
  839: 	}
  840:     }    
  841:     return 'no_host';
  842: }
  843: 
  844: # ------------------------------------- Find the usernames behind a list of IDs
  845: 
  846: sub idget {
  847:     my ($udom,@ids)=@_;
  848:     my %returnhash=();
  849:     
  850:     my %servers = &get_servers($udom,'library');
  851:     foreach my $tryserver (keys(%servers)) {
  852: 	my $idlist=join('&',@ids);
  853: 	$idlist=~tr/A-Z/a-z/; 
  854: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  855: 	my @answer=();
  856: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  857: 	    @answer=split(/\&/,$reply);
  858: 	}                    ;
  859: 	my $i;
  860: 	for ($i=0;$i<=$#ids;$i++) {
  861: 	    if ($answer[$i]) {
  862: 		$returnhash{$ids[$i]}=$answer[$i];
  863: 	    } 
  864: 	}
  865:     } 
  866:     return %returnhash;
  867: }
  868: 
  869: # ------------------------------------- Find the IDs behind a list of usernames
  870: 
  871: sub idrget {
  872:     my ($udom,@unames)=@_;
  873:     my %returnhash=();
  874:     foreach my $uname (@unames) {
  875:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  876:     }
  877:     return %returnhash;
  878: }
  879: 
  880: # ------------------------------- Store away a list of names and associated IDs
  881: 
  882: sub idput {
  883:     my ($udom,%ids)=@_;
  884:     my %servers=();
  885:     foreach my $uname (keys(%ids)) {
  886: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  887:         my $uhom=&homeserver($uname,$udom);
  888:         if ($uhom ne 'no_host') {
  889:             my $id=&escape($ids{$uname});
  890:             $id=~tr/A-Z/a-z/;
  891:             my $esc_unam=&escape($uname);
  892: 	    if ($servers{$uhom}) {
  893: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  894:             } else {
  895:                 $servers{$uhom}=$id.'='.$esc_unam;
  896:             }
  897:         }
  898:     }
  899:     foreach my $server (keys(%servers)) {
  900:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  901:     }
  902: }
  903: 
  904: # ------------------------------------------- get items from domain db files   
  905: 
  906: sub get_dom {
  907:     my ($namespace,$storearr,$udom,$uhome)=@_;
  908:     my $items='';
  909:     foreach my $item (@$storearr) {
  910:         $items.=&escape($item).'&';
  911:     }
  912:     $items=~s/\&$//;
  913:     if (!$udom) {
  914:         $udom=$env{'user.domain'};
  915:         if (defined(&domain($udom,'primary'))) {
  916:             $uhome=&domain($udom,'primary');
  917:         } else {
  918:             undef($uhome);
  919:         }
  920:     } else {
  921:         if (!$uhome) {
  922:             if (defined(&domain($udom,'primary'))) {
  923:                 $uhome=&domain($udom,'primary');
  924:             }
  925:         }
  926:     }
  927:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  928:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  929:         my %returnhash;
  930:         if ($rep eq '' || $rep =~ /^error: 2 /) {
  931:             return %returnhash;
  932:         }
  933:         my @pairs=split(/\&/,$rep);
  934:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  935:             return @pairs;
  936:         }
  937:         my $i=0;
  938:         foreach my $item (@$storearr) {
  939:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  940:             $i++;
  941:         }
  942:         return %returnhash;
  943:     } else {
  944:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
  945:     }
  946: }
  947: 
  948: # -------------------------------------------- put items in domain db files 
  949: 
  950: sub put_dom {
  951:     my ($namespace,$storehash,$udom,$uhome)=@_;
  952:     if (!$udom) {
  953:         $udom=$env{'user.domain'};
  954:         if (defined(&domain($udom,'primary'))) {
  955:             $uhome=&domain($udom,'primary');
  956:         } else {
  957:             undef($uhome);
  958:         }
  959:     } else {
  960:         if (!$uhome) {
  961:             if (defined(&domain($udom,'primary'))) {
  962:                 $uhome=&domain($udom,'primary');
  963:             }
  964:         }
  965:     } 
  966:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  967:         my $items='';
  968:         foreach my $item (keys(%$storehash)) {
  969:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  970:         }
  971:         $items=~s/\&$//;
  972:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  973:     } else {
  974:         &logthis("put_dom failed - no homeserver and/or domain");
  975:     }
  976: }
  977: 
  978: sub retrieve_inst_usertypes {
  979:     my ($udom) = @_;
  980:     my (%returnhash,@order);
  981:     if (defined(&domain($udom,'primary'))) {
  982:         my $uhome=&domain($udom,'primary');
  983:         my $rep=&reply("inst_usertypes:$udom",$uhome);
  984:         if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
  985:             &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
  986:             return (\%returnhash,\@order);
  987:         }
  988:         my ($hashitems,$orderitems) = split(/:/,$rep); 
  989:         my @pairs=split(/\&/,$hashitems);
  990:         foreach my $item (@pairs) {
  991:             my ($key,$value)=split(/=/,$item,2);
  992:             $key = &unescape($key);
  993:             next if ($key =~ /^error: 2 /);
  994:             $returnhash{$key}=&thaw_unescape($value);
  995:         }
  996:         my @esc_order = split(/\&/,$orderitems);
  997:         foreach my $item (@esc_order) {
  998:             push(@order,&unescape($item));
  999:         }
 1000:     } else {
 1001:         &logthis("get_dom failed - no primary domain server for $udom");
 1002:     }
 1003:     return (\%returnhash,\@order);
 1004: }
 1005: 
 1006: sub is_domainimage {
 1007:     my ($url) = @_;
 1008:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1009:         if (&domain($1) ne '') {
 1010:             return '1';
 1011:         }
 1012:     }
 1013:     return;
 1014: }
 1015: 
 1016: sub inst_directory_query {
 1017:     my ($srch) = @_;
 1018:     my $udom = $srch->{'srchdomain'};
 1019:     my %results;
 1020:     my $homeserver = &domain($udom,'primary');
 1021:     my $outcome;
 1022:     if ($homeserver ne '') {
 1023: 	my $queryid=&reply("querysend:instdirsearch:".
 1024: 			   &escape($srch->{'srchby'}).':'.
 1025: 			   &escape($srch->{'srchterm'}).':'.
 1026: 			   &escape($srch->{'srchtype'}),$homeserver);
 1027: 	my $host=&hostname($homeserver);
 1028: 	if ($queryid !~/^\Q$host\E\_/) {
 1029: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1030: 	    return;
 1031: 	}
 1032: 	my $response = &get_query_reply($queryid);
 1033: 	my $maxtries = 5;
 1034: 	my $tries = 1;
 1035: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1036: 	    $response = &get_query_reply($queryid);
 1037: 	    $tries ++;
 1038: 	}
 1039: 
 1040:         if (!&error($response) && $response ne 'refused') {
 1041:             if ($response eq 'unavailable') {
 1042:                 $outcome = $response;
 1043:             } else {
 1044:                 $outcome = 'ok';
 1045:                 my @matches = split(/\n/,$response);
 1046:                 foreach my $match (@matches) {
 1047:                     my ($key,$value) = split(/=/,$match);
 1048:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1049:                 }
 1050:             }
 1051:         }
 1052:     }
 1053:     return ($outcome,%results);
 1054: }
 1055: 
 1056: sub usersearch {
 1057:     my ($srch) = @_;
 1058:     my $dom = $srch->{'srchdomain'};
 1059:     my %results;
 1060:     my %libserv = &all_library();
 1061:     my $query = 'usersearch';
 1062:     foreach my $tryserver (keys(%libserv)) {
 1063:         if (&host_domain($tryserver) eq $dom) {
 1064:             my $host=&hostname($tryserver);
 1065:             my $queryid=
 1066:                 &reply("querysend:".&escape($query).':'.
 1067:                        &escape($srch->{'srchby'}).':'.
 1068:                        &escape($srch->{'srchtype'}).':'.
 1069:                        &escape($srch->{'srchterm'}),$tryserver);
 1070:             if ($queryid !~/^\Q$host\E\_/) {
 1071:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1072:                 next;
 1073:             }
 1074:             my $reply = &get_query_reply($queryid);
 1075:             my $maxtries = 1;
 1076:             my $tries = 1;
 1077:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1078:                 $reply = &get_query_reply($queryid);
 1079:                 $tries ++;
 1080:             }
 1081:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1082:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1083:             } else {
 1084:                 my @matches;
 1085:                 if ($reply =~ /\n/) {
 1086:                     @matches = split(/\n/,$reply);
 1087:                 } else {
 1088:                     @matches = split(/\&/,$reply);
 1089:                 }
 1090:                 foreach my $match (@matches) {
 1091:                     my ($uname,$udom,%userhash);
 1092:                     foreach my $entry (split(/:/,$match)) {
 1093:                         my ($key,$value) =
 1094:                             map {&unescape($_);} split(/=/,$entry);
 1095:                         $userhash{$key} = $value;
 1096:                         if ($key eq 'username') {
 1097:                             $uname = $value;
 1098:                         } elsif ($key eq 'domain') {
 1099:                             $udom = $value;
 1100:                         }
 1101:                     }
 1102:                     $results{$uname.':'.$udom} = \%userhash;
 1103:                 }
 1104:             }
 1105:         }
 1106:     }
 1107:     return %results;
 1108: }
 1109: 
 1110: sub get_instuser {
 1111:     my ($udom,$uname,$id) = @_;
 1112:     my $homeserver = &domain($udom,'primary');
 1113:     my ($outcome,%results);
 1114:     if ($homeserver ne '') {
 1115:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1116:                            &escape($id).':'.&escape($udom),$homeserver);
 1117:         my $host=&hostname($homeserver);
 1118:         if ($queryid !~/^\Q$host\E\_/) {
 1119:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1120:             return;
 1121:         }
 1122:         my $response = &get_query_reply($queryid);
 1123:         my $maxtries = 5;
 1124:         my $tries = 1;
 1125:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1126:             $response = &get_query_reply($queryid);
 1127:             $tries ++;
 1128:         }
 1129:         if (!&error($response) && $response ne 'refused') {
 1130:             if ($response eq 'unavailable') {
 1131:                 $outcome = $response;
 1132:             } else {
 1133:                 $outcome = 'ok';
 1134:                 my @matches = split(/\n/,$response);
 1135:                 foreach my $match (@matches) {
 1136:                     my ($key,$value) = split(/=/,$match);
 1137:                     $results{&unescape($key)} = &thaw_unescape($value);
 1138:                 }
 1139:             }
 1140:         }
 1141:     }
 1142:     my %userinfo;
 1143:     if (ref($results{$uname}) eq 'HASH') {
 1144:         %userinfo = %{$results{$uname}};
 1145:     } 
 1146:     return ($outcome,%userinfo);
 1147: }
 1148: 
 1149: sub inst_rulecheck {
 1150:     my ($udom,$uname,$id,$item,$rules) = @_;
 1151:     my %returnhash;
 1152:     if ($udom ne '') {
 1153:         if (ref($rules) eq 'ARRAY') {
 1154:             @{$rules} = map {&escape($_);} (@{$rules});
 1155:             my $rulestr = join(':',@{$rules});
 1156:             my $homeserver=&domain($udom,'primary');
 1157:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1158:                 my $response;
 1159:                 if ($item eq 'username') {                
 1160:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1161:                                               ':'.&escape($uname).':'.$rulestr,
 1162:                                               $homeserver));
 1163:                 } elsif ($item eq 'id') {
 1164:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1165:                                               ':'.&escape($id).':'.$rulestr,
 1166:                                               $homeserver));
 1167:                 } elsif ($item eq 'selfcreate') {
 1168:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1169:                                                &escape($udom).':'.&escape($uname).
 1170:                                               ':'.$rulestr,$homeserver));
 1171:                 }
 1172:                 if ($response ne 'refused') {
 1173:                     my @pairs=split(/\&/,$response);
 1174:                     foreach my $item (@pairs) {
 1175:                         my ($key,$value)=split(/=/,$item,2);
 1176:                         $key = &unescape($key);
 1177:                         next if ($key =~ /^error: 2 /);
 1178:                         $returnhash{$key}=&thaw_unescape($value);
 1179:                     }
 1180:                 }
 1181:             }
 1182:         }
 1183:     }
 1184:     return %returnhash;
 1185: }
 1186: 
 1187: sub inst_userrules {
 1188:     my ($udom,$check) = @_;
 1189:     my (%ruleshash,@ruleorder);
 1190:     if ($udom ne '') {
 1191:         my $homeserver=&domain($udom,'primary');
 1192:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1193:             my $response;
 1194:             if ($check eq 'id') {
 1195:                 $response=&reply('instidrules:'.&escape($udom),
 1196:                                  $homeserver);
 1197:             } elsif ($check eq 'email') {
 1198:                 $response=&reply('instemailrules:'.&escape($udom),
 1199:                                  $homeserver);
 1200:             } else {
 1201:                 $response=&reply('instuserrules:'.&escape($udom),
 1202:                                  $homeserver);
 1203:             }
 1204:             if (($response ne 'refused') && ($response ne 'error') && 
 1205:                 ($response ne 'unknown_cmd') && 
 1206:                 ($response ne 'no_such_host')) {
 1207:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1208:                 my @pairs=split(/\&/,$hashitems);
 1209:                 foreach my $item (@pairs) {
 1210:                     my ($key,$value)=split(/=/,$item,2);
 1211:                     $key = &unescape($key);
 1212:                     next if ($key =~ /^error: 2 /);
 1213:                     $ruleshash{$key}=&thaw_unescape($value);
 1214:                 }
 1215:                 my @esc_order = split(/\&/,$orderitems);
 1216:                 foreach my $item (@esc_order) {
 1217:                     push(@ruleorder,&unescape($item));
 1218:                 }
 1219:             }
 1220:         }
 1221:     }
 1222:     return (\%ruleshash,\@ruleorder);
 1223: }
 1224: 
 1225: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1226: 
 1227: sub get_domain_defaults {
 1228:     my ($domain) = @_;
 1229:     my $cachetime = 60*60*24;
 1230:     my ($defauthtype,$defautharg,$deflang,%deftools);
 1231:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1232:     if (defined($cached)) {
 1233:         if (ref($result) eq 'HASH') {
 1234:             return %{$result};
 1235:         }
 1236:     }
 1237:     my %domdefaults;
 1238:     my %domconfig =
 1239:          &Apache::lonnet::get_dom('configuration',['defaults','quotas'],$domain);
 1240:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1241:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1242:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1243:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1244:     } else {
 1245:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1246:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1247:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1248:     }
 1249:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1250:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1251:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1252:         } else {
 1253:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1254:         } 
 1255:         my @usertools = ('aboutme','blog','portfolio');
 1256:         foreach my $item (@usertools) {
 1257:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1258:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1259:             }
 1260:         }
 1261:     }
 1262:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1263:                                   $cachetime);
 1264:     return %domdefaults;
 1265: }
 1266: 
 1267: # --------------------------------------------------- Assign a key to a student
 1268: 
 1269: sub assign_access_key {
 1270: #
 1271: # a valid key looks like uname:udom#comments
 1272: # comments are being appended
 1273: #
 1274:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1275:     $kdom=
 1276:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1277:     $knum=
 1278:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1279:     $cdom=
 1280:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1281:     $cnum=
 1282:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1283:     $udom=$env{'user.name'} unless (defined($udom));
 1284:     $uname=$env{'user.domain'} unless (defined($uname));
 1285:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1286:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1287:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1288:                                                   # assigned to this person
 1289:                                                   # - this should not happen,
 1290:                                                   # unless something went wrong
 1291:                                                   # the first time around
 1292: # ready to assign
 1293:         $logentry=$1.'; '.$logentry;
 1294:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1295:                                                  $kdom,$knum) eq 'ok') {
 1296: # key now belongs to user
 1297: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1298:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1299:                 &appenv({'environment.'.$envkey => $ckey});
 1300:                 return 'ok';
 1301:             } else {
 1302:                 return 
 1303:   'error: Count not permanently assign key, will need to be re-entered later.';
 1304: 	    }
 1305:         } else {
 1306:             return 'error: Could not assign key, try again later.';
 1307:         }
 1308:     } elsif (!$existing{$ckey}) {
 1309: # the key does not exist
 1310: 	return 'error: The key does not exist';
 1311:     } else {
 1312: # the key is somebody else's
 1313: 	return 'error: The key is already in use';
 1314:     }
 1315: }
 1316: 
 1317: # ------------------------------------------ put an additional comment on a key
 1318: 
 1319: sub comment_access_key {
 1320: #
 1321: # a valid key looks like uname:udom#comments
 1322: # comments are being appended
 1323: #
 1324:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1325:     $cdom=
 1326:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1327:     $cnum=
 1328:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1329:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1330:     if ($existing{$ckey}) {
 1331:         $existing{$ckey}.='; '.$logentry;
 1332: # ready to assign
 1333:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1334:                                                  $cdom,$cnum) eq 'ok') {
 1335: 	    return 'ok';
 1336:         } else {
 1337: 	    return 'error: Count not store comment.';
 1338:         }
 1339:     } else {
 1340: # the key does not exist
 1341: 	return 'error: The key does not exist';
 1342:     }
 1343: }
 1344: 
 1345: # ------------------------------------------------------ Generate a set of keys
 1346: 
 1347: sub generate_access_keys {
 1348:     my ($number,$cdom,$cnum,$logentry)=@_;
 1349:     $cdom=
 1350:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1351:     $cnum=
 1352:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1353:     unless (&allowed('mky',$cdom)) { return 0; }
 1354:     unless (($cdom) && ($cnum)) { return 0; }
 1355:     if ($number>10000) { return 0; }
 1356:     sleep(2); # make sure don't get same seed twice
 1357:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1358:     my $total=0;
 1359:     for (my $i=1;$i<=$number;$i++) {
 1360:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1361:                   sprintf("%lx",int(100000*rand)).'-'.
 1362:                   sprintf("%lx",int(100000*rand));
 1363:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1364:        $newkey=~s/0/h/g; # and also 0 and O
 1365:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1366:        if ($existing{$newkey}) {
 1367:            $i--;
 1368:        } else {
 1369: 	  if (&put('accesskeys',
 1370:               { $newkey => '# generated '.localtime().
 1371:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1372:                            '; '.$logentry },
 1373: 		   $cdom,$cnum) eq 'ok') {
 1374:               $total++;
 1375: 	  }
 1376:        }
 1377:     }
 1378:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1379:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1380:     return $total;
 1381: }
 1382: 
 1383: # ------------------------------------------------------- Validate an accesskey
 1384: 
 1385: sub validate_access_key {
 1386:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1387:     $cdom=
 1388:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1389:     $cnum=
 1390:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1391:     $udom=$env{'user.domain'} unless (defined($udom));
 1392:     $uname=$env{'user.name'} unless (defined($uname));
 1393:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1394:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1395: }
 1396: 
 1397: # ------------------------------------- Find the section of student in a course
 1398: sub devalidate_getsection_cache {
 1399:     my ($udom,$unam,$courseid)=@_;
 1400:     my $hashid="$udom:$unam:$courseid";
 1401:     &devalidate_cache_new('getsection',$hashid);
 1402: }
 1403: 
 1404: sub courseid_to_courseurl {
 1405:     my ($courseid) = @_;
 1406:     #already url style courseid
 1407:     return $courseid if ($courseid =~ m{^/});
 1408: 
 1409:     if (exists($env{'course.'.$courseid.'.num'})) {
 1410: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1411: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1412: 	return "/$cdom/$cnum";
 1413:     }
 1414: 
 1415:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1416:     if (exists($courseinfo{'num'})) {
 1417: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1418:     }
 1419: 
 1420:     return undef;
 1421: }
 1422: 
 1423: sub getsection {
 1424:     my ($udom,$unam,$courseid)=@_;
 1425:     my $cachetime=1800;
 1426: 
 1427:     my $hashid="$udom:$unam:$courseid";
 1428:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1429:     if (defined($cached)) { return $result; }
 1430: 
 1431:     my %Pending; 
 1432:     my %Expired;
 1433:     #
 1434:     # Each role can either have not started yet (pending), be active, 
 1435:     #    or have expired.
 1436:     #
 1437:     # If there is an active role, we are done.
 1438:     #
 1439:     # If there is more than one role which has not started yet, 
 1440:     #     choose the one which will start sooner
 1441:     # If there is one role which has not started yet, return it.
 1442:     #
 1443:     # If there is more than one expired role, choose the one which ended last.
 1444:     # If there is a role which has expired, return it.
 1445:     #
 1446:     $courseid = &courseid_to_courseurl($courseid);
 1447:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1448:     foreach my $key (keys(%roleshash)) {
 1449:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1450:         my $section=$1;
 1451:         if ($key eq $courseid.'_st') { $section=''; }
 1452:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1453:         my $now=time;
 1454:         if (defined($end) && $end && ($now > $end)) {
 1455:             $Expired{$end}=$section;
 1456:             next;
 1457:         }
 1458:         if (defined($start) && $start && ($now < $start)) {
 1459:             $Pending{$start}=$section;
 1460:             next;
 1461:         }
 1462:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1463:     }
 1464:     #
 1465:     # Presumedly there will be few matching roles from the above
 1466:     # loop and the sorting time will be negligible.
 1467:     if (scalar(keys(%Pending))) {
 1468:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1469:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1470:     } 
 1471:     if (scalar(keys(%Expired))) {
 1472:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1473:         my $time = pop(@sorted);
 1474:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1475:     }
 1476:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1477: }
 1478: 
 1479: sub save_cache {
 1480:     &purge_remembered();
 1481:     #&Apache::loncommon::validate_page();
 1482:     undef(%env);
 1483:     undef($env_loaded);
 1484: }
 1485: 
 1486: my $to_remember=-1;
 1487: my %remembered;
 1488: my %accessed;
 1489: my $kicks=0;
 1490: my $hits=0;
 1491: sub make_key {
 1492:     my ($name,$id) = @_;
 1493:     if (length($id) > 65 
 1494: 	&& length(&escape($id)) > 200) {
 1495: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1496:     }
 1497:     return &escape($name.':'.$id);
 1498: }
 1499: 
 1500: sub devalidate_cache_new {
 1501:     my ($name,$id,$debug) = @_;
 1502:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1503:     $id=&make_key($name,$id);
 1504:     $memcache->delete($id);
 1505:     delete($remembered{$id});
 1506:     delete($accessed{$id});
 1507: }
 1508: 
 1509: sub is_cached_new {
 1510:     my ($name,$id,$debug) = @_;
 1511:     $id=&make_key($name,$id);
 1512:     if (exists($remembered{$id})) {
 1513: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1514: 	$accessed{$id}=[&gettimeofday()];
 1515: 	$hits++;
 1516: 	return ($remembered{$id},1);
 1517:     }
 1518:     my $value = $memcache->get($id);
 1519:     if (!(defined($value))) {
 1520: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1521: 	return (undef,undef);
 1522:     }
 1523:     if ($value eq '__undef__') {
 1524: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1525: 	$value=undef;
 1526:     }
 1527:     &make_room($id,$value,$debug);
 1528:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1529:     return ($value,1);
 1530: }
 1531: 
 1532: sub do_cache_new {
 1533:     my ($name,$id,$value,$time,$debug) = @_;
 1534:     $id=&make_key($name,$id);
 1535:     my $setvalue=$value;
 1536:     if (!defined($setvalue)) {
 1537: 	$setvalue='__undef__';
 1538:     }
 1539:     if (!defined($time) ) {
 1540: 	$time=600;
 1541:     }
 1542:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1543:     my $result = $memcache->set($id,$setvalue,$time);
 1544:     if (! $result) {
 1545: 	&logthis("caching of id -> $id  failed");
 1546: 	$memcache->disconnect_all();
 1547:     }
 1548:     # need to make a copy of $value
 1549:     &make_room($id,$value,$debug);
 1550:     return $value;
 1551: }
 1552: 
 1553: sub make_room {
 1554:     my ($id,$value,$debug)=@_;
 1555: 
 1556:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1557:                                     : $value;
 1558:     if ($to_remember<0) { return; }
 1559:     $accessed{$id}=[&gettimeofday()];
 1560:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1561:     my $to_kick;
 1562:     my $max_time=0;
 1563:     foreach my $other (keys(%accessed)) {
 1564: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1565: 	    $to_kick=$other;
 1566: 	    $max_time=&tv_interval($accessed{$other});
 1567: 	}
 1568:     }
 1569:     delete($remembered{$to_kick});
 1570:     delete($accessed{$to_kick});
 1571:     $kicks++;
 1572:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1573:     return;
 1574: }
 1575: 
 1576: sub purge_remembered {
 1577:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1578:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1579:     undef(%remembered);
 1580:     undef(%accessed);
 1581: }
 1582: # ------------------------------------- Read an entry from a user's environment
 1583: 
 1584: sub userenvironment {
 1585:     my ($udom,$unam,@what)=@_;
 1586:     my $items;
 1587:     foreach my $item (@what) {
 1588:         $items.=&escape($item).'&';
 1589:     }
 1590:     $items=~s/\&$//;
 1591:     my %returnhash=();
 1592:     my @answer=split(/\&/,
 1593:                 &reply('get:'.$udom.':'.$unam.':environment:'.$items,
 1594:                       &homeserver($unam,$udom)));
 1595:     my $i;
 1596:     for ($i=0;$i<=$#what;$i++) {
 1597: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1598:     }
 1599:     return %returnhash;
 1600: }
 1601: 
 1602: # ---------------------------------------------------------- Get a studentphoto
 1603: sub studentphoto {
 1604:     my ($udom,$unam,$ext) = @_;
 1605:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1606:     if (defined($env{'request.course.id'})) {
 1607:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1608:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1609:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1610:             } else {
 1611:                 my ($result,$perm_reqd)=
 1612: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1613:                 if ($result eq 'ok') {
 1614:                     if (!($perm_reqd eq 'yes')) {
 1615:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1616:                     }
 1617:                 }
 1618:             }
 1619:         }
 1620:     } else {
 1621:         my ($result,$perm_reqd) = 
 1622: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1623:         if ($result eq 'ok') {
 1624:             if (!($perm_reqd eq 'yes')) {
 1625:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1626:             }
 1627:         }
 1628:     }
 1629:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1630: }
 1631: 
 1632: sub retrievestudentphoto {
 1633:     my ($udom,$unam,$ext,$type) = @_;
 1634:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1635:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1636:     if ($ret eq 'ok') {
 1637:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1638:         if ($type eq 'thumbnail') {
 1639:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1640:         }
 1641:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1642:         return $tokenurl;
 1643:     } else {
 1644:         if ($type eq 'thumbnail') {
 1645:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1646:         } else { 
 1647:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1648:         }
 1649:     }
 1650: }
 1651: 
 1652: # -------------------------------------------------------------------- New chat
 1653: 
 1654: sub chatsend {
 1655:     my ($newentry,$anon,$group)=@_;
 1656:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1657:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1658:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1659:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1660: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1661: 		   &escape($newentry)).':'.$group,$chome);
 1662: }
 1663: 
 1664: # ------------------------------------------ Find current version of a resource
 1665: 
 1666: sub getversion {
 1667:     my $fname=&clutter(shift);
 1668:     unless ($fname=~/^\/res\//) { return -1; }
 1669:     return &currentversion(&filelocation('',$fname));
 1670: }
 1671: 
 1672: sub currentversion {
 1673:     my $fname=shift;
 1674:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1675:     if (defined($cached)) { return $result; }
 1676:     my $author=$fname;
 1677:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1678:     my ($udom,$uname)=split(/\//,$author);
 1679:     my $home=homeserver($uname,$udom);
 1680:     if ($home eq 'no_host') { 
 1681:         return -1; 
 1682:     }
 1683:     my $answer=reply("currentversion:$fname",$home);
 1684:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1685: 	return -1;
 1686:     }
 1687:     return &do_cache_new('resversion',$fname,$answer,600);
 1688: }
 1689: 
 1690: # ----------------------------- Subscribe to a resource, return URL if possible
 1691: 
 1692: sub subscribe {
 1693:     my $fname=shift;
 1694:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1695:     $fname=~s/[\n\r]//g;
 1696:     my $author=$fname;
 1697:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1698:     my ($udom,$uname)=split(/\//,$author);
 1699:     my $home=homeserver($uname,$udom);
 1700:     if ($home eq 'no_host') {
 1701:         return 'not_found';
 1702:     }
 1703:     my $answer=reply("sub:$fname",$home);
 1704:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1705: 	$answer.=' by '.$home;
 1706:     }
 1707:     return $answer;
 1708: }
 1709:     
 1710: # -------------------------------------------------------------- Replicate file
 1711: 
 1712: sub repcopy {
 1713:     my $filename=shift;
 1714:     $filename=~s/\/+/\//g;
 1715:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1716:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1717:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1718: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1719: 	return &repcopy_userfile($filename);
 1720:     }
 1721:     $filename=~s/[\n\r]//g;
 1722:     my $transname="$filename.in.transfer";
 1723: # FIXME: this should flock
 1724:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1725:     my $remoteurl=subscribe($filename);
 1726:     if ($remoteurl =~ /^con_lost by/) {
 1727: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1728:            return 'unavailable';
 1729:     } elsif ($remoteurl eq 'not_found') {
 1730: 	   #&logthis("Subscribe returned not_found: $filename");
 1731: 	   return 'not_found';
 1732:     } elsif ($remoteurl =~ /^rejected by/) {
 1733: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1734:            return 'forbidden';
 1735:     } elsif ($remoteurl eq 'directory') {
 1736:            return 'ok';
 1737:     } else {
 1738:         my $author=$filename;
 1739:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1740:         my ($udom,$uname)=split(/\//,$author);
 1741:         my $home=homeserver($uname,$udom);
 1742:         unless ($home eq $perlvar{'lonHostID'}) {
 1743:            my @parts=split(/\//,$filename);
 1744:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1745:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1746:                &logthis("Malconfiguration for replication: $filename");
 1747: 	       return 'bad_request';
 1748:            }
 1749:            my $count;
 1750:            for ($count=5;$count<$#parts;$count++) {
 1751:                $path.="/$parts[$count]";
 1752:                if ((-e $path)!=1) {
 1753: 		   mkdir($path,0777);
 1754:                }
 1755:            }
 1756:            my $ua=new LWP::UserAgent;
 1757:            my $request=new HTTP::Request('GET',"$remoteurl");
 1758:            my $response=$ua->request($request,$transname);
 1759:            if ($response->is_error()) {
 1760: 	       unlink($transname);
 1761:                my $message=$response->status_line;
 1762:                &logthis("<font color=\"blue\">WARNING:"
 1763:                        ." LWP get: $message: $filename</font>");
 1764:                return 'unavailable';
 1765:            } else {
 1766: 	       if ($remoteurl!~/\.meta$/) {
 1767:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1768:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1769:                   if ($mresponse->is_error()) {
 1770: 		      unlink($filename.'.meta');
 1771:                       &logthis(
 1772:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1773:                   }
 1774: 	       }
 1775:                rename($transname,$filename);
 1776:                return 'ok';
 1777:            }
 1778:        }
 1779:     }
 1780: }
 1781: 
 1782: # ------------------------------------------------ Get server side include body
 1783: sub ssi_body {
 1784:     my ($filelink,%form)=@_;
 1785:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1786:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1787:     }
 1788:     my $output='';
 1789:     my $response;
 1790:     if ($filelink=~/^http\:/) {
 1791:        ($output,$response)=&externalssi($filelink);
 1792:     } else {
 1793:        ($output,$response)=&ssi($filelink,%form);
 1794:     }
 1795:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1796:     $output=~s/^.*?\<body[^\>]*\>//si;
 1797:     $output=~s/\<\/body\s*\>.*?$//si;
 1798:     if (wantarray) {
 1799:         return ($output, $response);
 1800:     } else {
 1801:         return $output;
 1802:     }
 1803: }
 1804: 
 1805: # --------------------------------------------------------- Server Side Include
 1806: 
 1807: sub absolute_url {
 1808:     my ($host_name) = @_;
 1809:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1810:     if ($host_name eq '') {
 1811: 	$host_name = $ENV{'SERVER_NAME'};
 1812:     }
 1813:     return $protocol.$host_name;
 1814: }
 1815: 
 1816: #
 1817: #   Server side include.
 1818: # Parameters:
 1819: #  fn     Possibly encrypted resource name/id.
 1820: #  form   Hash that describes how the rendering should be done
 1821: #         and other things.
 1822: # Returns:
 1823: #   Scalar context: The content of the response.
 1824: #   Array context:  2 element list of the content and the full response object.
 1825: #     
 1826: sub ssi {
 1827: 
 1828:     my ($fn,%form)=@_;
 1829:     my $ua=new LWP::UserAgent;
 1830:     my $request;
 1831: 
 1832:     $form{'no_update_last_known'}=1;
 1833:     &Apache::lonenc::check_encrypt(\$fn);
 1834:     if (%form) {
 1835:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1836:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1837:     } else {
 1838:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1839:     }
 1840: 
 1841:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1842:     my $response=$ua->request($request);
 1843: 
 1844:     if (wantarray) {
 1845: 	return ($response->content, $response);
 1846:     } else {
 1847: 	return $response->content;
 1848:     }
 1849: }
 1850: 
 1851: sub externalssi {
 1852:     my ($url)=@_;
 1853:     my $ua=new LWP::UserAgent;
 1854:     my $request=new HTTP::Request('GET',$url);
 1855:     my $response=$ua->request($request);
 1856:     if (wantarray) {
 1857:         return ($response->content, $response);
 1858:     } else {
 1859:         return $response->content;
 1860:     }
 1861: }
 1862: 
 1863: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1864: 
 1865: sub allowuploaded {
 1866:     my ($srcurl,$url)=@_;
 1867:     $url=&clutter(&declutter($url));
 1868:     my $dir=$url;
 1869:     $dir=~s/\/[^\/]+$//;
 1870:     my %httpref=();
 1871:     my $httpurl=&hreflocation('',$url);
 1872:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1873:     &Apache::lonnet::appenv(\%httpref);
 1874: }
 1875: 
 1876: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1877: # input: action, courseID, current domain, intended
 1878: #        path to file, source of file, instruction to parse file for objects,
 1879: #        ref to hash for embedded objects,
 1880: #        ref to hash for codebase of java objects.
 1881: #
 1882: # output: url to file (if action was uploaddoc), 
 1883: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1884: #
 1885: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1886: # course.
 1887: #
 1888: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1889: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1890: #          course's home server.
 1891: #
 1892: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1893: #          be copied from $source (current location) to 
 1894: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1895: #         and will then be copied to
 1896: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1897: #         course's home server.
 1898: #
 1899: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1900: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1901: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1902: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1903: #         in course's home server.
 1904: #
 1905: 
 1906: sub process_coursefile {
 1907:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1908:     my $fetchresult;
 1909:     my $home=&homeserver($docuname,$docudom);
 1910:     if ($action eq 'propagate') {
 1911:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1912: 			     $home);
 1913:     } else {
 1914:         my $fpath = '';
 1915:         my $fname = $file;
 1916:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1917:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1918:         my $filepath = &build_filepath($fpath);
 1919:         if ($action eq 'copy') {
 1920:             if ($source eq '') {
 1921:                 $fetchresult = 'no source file';
 1922:                 return $fetchresult;
 1923:             } else {
 1924:                 my $destination = $filepath.'/'.$fname;
 1925:                 rename($source,$destination);
 1926:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1927:                                  $home);
 1928:             }
 1929:         } elsif ($action eq 'uploaddoc') {
 1930:             open(my $fh,'>'.$filepath.'/'.$fname);
 1931:             print $fh $env{'form.'.$source};
 1932:             close($fh);
 1933:             if ($parser eq 'parse') {
 1934:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 1935:                 unless ($parse_result eq 'ok') {
 1936:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1937:                 }
 1938:             }
 1939:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1940:                                  $home);
 1941:             if ($fetchresult eq 'ok') {
 1942:                 return '/uploaded/'.$fpath.'/'.$fname;
 1943:             } else {
 1944:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1945:                         ' to host '.$home.': '.$fetchresult);
 1946:                 return '/adm/notfound.html';
 1947:             }
 1948:         }
 1949:     }
 1950:     unless ( $fetchresult eq 'ok') {
 1951:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1952:              ' to host '.$home.': '.$fetchresult);
 1953:     }
 1954:     return $fetchresult;
 1955: }
 1956: 
 1957: sub build_filepath {
 1958:     my ($fpath) = @_;
 1959:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1960:     unless ($fpath eq '') {
 1961:         my @parts=split('/',$fpath);
 1962:         foreach my $part (@parts) {
 1963:             $filepath.= '/'.$part;
 1964:             if ((-e $filepath)!=1) {
 1965:                 mkdir($filepath,0777);
 1966:             }
 1967:         }
 1968:     }
 1969:     return $filepath;
 1970: }
 1971: 
 1972: sub store_edited_file {
 1973:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1974:     my $file = $primary_url;
 1975:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1976:     my $fpath = '';
 1977:     my $fname = $file;
 1978:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1979:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1980:     my $filepath = &build_filepath($fpath);
 1981:     open(my $fh,'>'.$filepath.'/'.$fname);
 1982:     print $fh $content;
 1983:     close($fh);
 1984:     my $home=&homeserver($docuname,$docudom);
 1985:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1986: 			  $home);
 1987:     if ($$fetchresult eq 'ok') {
 1988:         return '/uploaded/'.$fpath.'/'.$fname;
 1989:     } else {
 1990:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1991: 		 ' to host '.$home.': '.$$fetchresult);
 1992:         return '/adm/notfound.html';
 1993:     }
 1994: }
 1995: 
 1996: sub clean_filename {
 1997:     my ($fname,$args)=@_;
 1998: # Replace Windows backslashes by forward slashes
 1999:     $fname=~s/\\/\//g;
 2000:     if (!$args->{'keep_path'}) {
 2001:         # Get rid of everything but the actual filename
 2002: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2003:     }
 2004: # Replace spaces by underscores
 2005:     $fname=~s/\s+/\_/g;
 2006: # Replace all other weird characters by nothing
 2007:     $fname=~s{[^/\w\.\-]}{}g;
 2008: # Replace all .\d. sequences with _\d. so they no longer look like version
 2009: # numbers
 2010:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2011:     return $fname;
 2012: }
 2013: 
 2014: # --------------- Take an uploaded file and put it into the userfiles directory
 2015: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2016: #                    the desired filenam is in $env{"form.$formname.filename"}
 2017: #        $coursedoc - if true up to the current course
 2018: #                     if false
 2019: #        $subdir - directory in userfile to store the file into
 2020: #        $parser - instruction to parse file for objects ($parser = parse)    
 2021: #        $allfiles - reference to hash for embedded objects
 2022: #        $codebase - reference to hash for codebase of java objects
 2023: #        $desuname - username for permanent storage of uploaded file
 2024: #        $dsetudom - domain for permanaent storage of uploaded file
 2025: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2026: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2027: # 
 2028: # output: url of file in userspace, or error: <message> 
 2029: #             or /adm/notfound.html if failure to upload occurse
 2030: 
 2031: 
 2032: sub userfileupload {
 2033:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 2034:         $destudom,$thumbwidth,$thumbheight)=@_;
 2035:     if (!defined($subdir)) { $subdir='unknown'; }
 2036:     my $fname=$env{'form.'.$formname.'.filename'};
 2037:     $fname=&clean_filename($fname);
 2038: # See if there is anything left
 2039:     unless ($fname) { return 'error: no uploaded file'; }
 2040:     chop($env{'form.'.$formname});
 2041:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 2042:         my $now = time;
 2043:         my $filepath = 'tmp/helprequests/'.$now;
 2044:         my @parts=split(/\//,$filepath);
 2045:         my $fullpath = $perlvar{'lonDaemons'};
 2046:         for (my $i=0;$i<@parts;$i++) {
 2047:             $fullpath .= '/'.$parts[$i];
 2048:             if ((-e $fullpath)!=1) {
 2049:                 mkdir($fullpath,0777);
 2050:             }
 2051:         }
 2052:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2053:         print $fh $env{'form.'.$formname};
 2054:         close($fh);
 2055:         return $fullpath.'/'.$fname;
 2056:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 2057:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2058:                        '_'.$env{'user.domain'}.'/pending';
 2059:         my @parts=split(/\//,$filepath);
 2060:         my $fullpath = $perlvar{'lonDaemons'};
 2061:         for (my $i=0;$i<@parts;$i++) {
 2062:             $fullpath .= '/'.$parts[$i];
 2063:             if ((-e $fullpath)!=1) {
 2064:                 mkdir($fullpath,0777);
 2065:             }
 2066:         }
 2067:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2068:         print $fh $env{'form.'.$formname};
 2069:         close($fh);
 2070:         return $fullpath.'/'.$fname;
 2071:     }
 2072:     
 2073: # Create the directory if not present
 2074:     $fname="$subdir/$fname";
 2075:     if ($coursedoc) {
 2076: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2077: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2078:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2079:             return &finishuserfileupload($docuname,$docudom,
 2080: 					 $formname,$fname,$parser,$allfiles,
 2081: 					 $codebase,$thumbwidth,$thumbheight);
 2082:         } else {
 2083:             $fname=$env{'form.folder'}.'/'.$fname;
 2084:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2085: 				       $fname,$formname,$parser,
 2086: 				       $allfiles,$codebase);
 2087:         }
 2088:     } elsif (defined($destuname)) {
 2089:         my $docuname=$destuname;
 2090:         my $docudom=$destudom;
 2091: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2092: 				     $parser,$allfiles,$codebase,
 2093:                                      $thumbwidth,$thumbheight);
 2094:         
 2095:     } else {
 2096:         my $docuname=$env{'user.name'};
 2097:         my $docudom=$env{'user.domain'};
 2098:         if (exists($env{'form.group'})) {
 2099:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2100:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2101:         }
 2102: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2103: 				     $parser,$allfiles,$codebase,
 2104:                                      $thumbwidth,$thumbheight);
 2105:     }
 2106: }
 2107: 
 2108: sub finishuserfileupload {
 2109:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2110:         $thumbwidth,$thumbheight) = @_;
 2111:     my $path=$docudom.'/'.$docuname.'/';
 2112:     my $filepath=$perlvar{'lonDocRoot'};
 2113:     my ($fnamepath,$file,$fetchthumb);
 2114:     $file=$fname;
 2115:     if ($fname=~m|/|) {
 2116:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2117: 	$path.=$fnamepath.'/';
 2118:     }
 2119:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2120:     my $count;
 2121:     for ($count=4;$count<=$#parts;$count++) {
 2122:         $filepath.="/$parts[$count]";
 2123:         if ((-e $filepath)!=1) {
 2124: 	    mkdir($filepath,0777);
 2125:         }
 2126:     }
 2127: # Save the file
 2128:     {
 2129: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2130: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2131: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2132: 	    return '/adm/notfound.html';
 2133: 	}
 2134: 	if (!print FH ($env{'form.'.$formname})) {
 2135: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2136: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2137: 	    return '/adm/notfound.html';
 2138: 	}
 2139: 	close(FH);
 2140:     }
 2141:     if ($parser eq 'parse') {
 2142:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
 2143: 						   $codebase);
 2144:         unless ($parse_result eq 'ok') {
 2145:             &logthis('Failed to parse '.$filepath.$file.
 2146: 		     ' for embedded media: '.$parse_result); 
 2147:         }
 2148:     }
 2149:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2150:         my $input = $filepath.'/'.$file;
 2151:         my $output = $filepath.'/'.'tn-'.$file;
 2152:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2153:         system("convert -sample $thumbsize $input $output");
 2154:         if (-e $filepath.'/'.'tn-'.$file) {
 2155:             $fetchthumb  = 1; 
 2156:         }
 2157:     }
 2158:  
 2159: # Notify homeserver to grep it
 2160: #
 2161:     my $docuhome=&homeserver($docuname,$docudom);
 2162:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2163:     if ($fetchresult eq 'ok') {
 2164:         if ($fetchthumb) {
 2165:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2166:             if ($thumbresult ne 'ok') {
 2167:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2168:                          $docuhome.': '.$thumbresult);
 2169:             }
 2170:         }
 2171: #
 2172: # Return the URL to it
 2173:         return '/uploaded/'.$path.$file;
 2174:     } else {
 2175:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2176: 		 ': '.$fetchresult);
 2177:         return '/adm/notfound.html';
 2178:     }
 2179: }
 2180: 
 2181: sub extract_embedded_items {
 2182:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 2183:     my @state = ();
 2184:     my %javafiles = (
 2185:                       codebase => '',
 2186:                       code => '',
 2187:                       archive => ''
 2188:                     );
 2189:     my %mediafiles = (
 2190:                       src => '',
 2191:                       movie => '',
 2192:                      );
 2193:     my $p;
 2194:     if ($content) {
 2195:         $p = HTML::LCParser->new($content);
 2196:     } else {
 2197:         $p = HTML::LCParser->new($fullpath);
 2198:     }
 2199:     while (my $t=$p->get_token()) {
 2200: 	if ($t->[0] eq 'S') {
 2201: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2202: 	    push(@state, $tagname);
 2203:             if (lc($tagname) eq 'allow') {
 2204:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2205:             }
 2206: 	    if (lc($tagname) eq 'img') {
 2207: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2208: 	    }
 2209: 	    if (lc($tagname) eq 'a') {
 2210: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2211: 	    }
 2212:             if (lc($tagname) eq 'script') {
 2213:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2214:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2215:                 } else {
 2216:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2217:                 }
 2218:             }
 2219:             if (lc($tagname) eq 'link') {
 2220:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2221:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2222:                 }
 2223:             }
 2224: 	    if (lc($tagname) eq 'object' ||
 2225: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2226: 		foreach my $item (keys(%javafiles)) {
 2227: 		    $javafiles{$item} = '';
 2228: 		}
 2229: 	    }
 2230: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2231: 		my $name = lc($attr->{'name'});
 2232: 		foreach my $item (keys(%javafiles)) {
 2233: 		    if ($name eq $item) {
 2234: 			$javafiles{$item} = $attr->{'value'};
 2235: 			last;
 2236: 		    }
 2237: 		}
 2238: 		foreach my $item (keys(%mediafiles)) {
 2239: 		    if ($name eq $item) {
 2240: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2241: 			last;
 2242: 		    }
 2243: 		}
 2244: 	    }
 2245: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2246: 		foreach my $item (keys(%javafiles)) {
 2247: 		    if ($attr->{$item}) {
 2248: 			$javafiles{$item} = $attr->{$item};
 2249: 			last;
 2250: 		    }
 2251: 		}
 2252: 		foreach my $item (keys(%mediafiles)) {
 2253: 		    if ($attr->{$item}) {
 2254: 			&add_filetype($allfiles,$attr->{$item},$item);
 2255: 			last;
 2256: 		    }
 2257: 		}
 2258: 	    }
 2259: 	} elsif ($t->[0] eq 'E') {
 2260: 	    my ($tagname) = ($t->[1]);
 2261: 	    if ($javafiles{'codebase'} ne '') {
 2262: 		$javafiles{'codebase'} .= '/';
 2263: 	    }  
 2264: 	    if (lc($tagname) eq 'applet' ||
 2265: 		lc($tagname) eq 'object' ||
 2266: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2267: 		) {
 2268: 		foreach my $item (keys(%javafiles)) {
 2269: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2270: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2271: 			&add_filetype($allfiles,$file,$item);
 2272: 		    }
 2273: 		}
 2274: 	    } 
 2275: 	    pop @state;
 2276: 	}
 2277:     }
 2278:     return 'ok';
 2279: }
 2280: 
 2281: sub add_filetype {
 2282:     my ($allfiles,$file,$type)=@_;
 2283:     if (exists($allfiles->{$file})) {
 2284: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2285: 	    push(@{$allfiles->{$file}}, &escape($type));
 2286: 	}
 2287:     } else {
 2288: 	@{$allfiles->{$file}} = (&escape($type));
 2289:     }
 2290: }
 2291: 
 2292: sub removeuploadedurl {
 2293:     my ($url)=@_;
 2294:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 2295:     return &removeuserfile($uname,$udom,$fname);
 2296: }
 2297: 
 2298: sub removeuserfile {
 2299:     my ($docuname,$docudom,$fname)=@_;
 2300:     my $home=&homeserver($docuname,$docudom);
 2301:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2302:     if ($result eq 'ok') {
 2303:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2304:             my $metafile = $fname.'.meta';
 2305:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2306: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2307:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2308:             my $sqlresult = 
 2309:                 &update_portfolio_table($docuname,$docudom,$file,
 2310:                                         'portfolio_metadata',$group,
 2311:                                         'delete');
 2312:         }
 2313:     }
 2314:     return $result;
 2315: }
 2316: 
 2317: sub mkdiruserfile {
 2318:     my ($docuname,$docudom,$dir)=@_;
 2319:     my $home=&homeserver($docuname,$docudom);
 2320:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2321: }
 2322: 
 2323: sub renameuserfile {
 2324:     my ($docuname,$docudom,$old,$new)=@_;
 2325:     my $home=&homeserver($docuname,$docudom);
 2326:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2327:                         &escape("$old").':'.&escape("$new"),$home);
 2328:     if ($result eq 'ok') {
 2329:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2330:             my $oldmeta = $old.'.meta';
 2331:             my $newmeta = $new.'.meta';
 2332:             my $metaresult = 
 2333:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2334: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2335:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2336:             my $sqlresult = 
 2337:                 &update_portfolio_table($docuname,$docudom,$file,
 2338:                                         'portfolio_metadata',$group,
 2339:                                         'delete');
 2340:         }
 2341:     }
 2342:     return $result;
 2343: }
 2344: 
 2345: # ------------------------------------------------------------------------- Log
 2346: 
 2347: sub log {
 2348:     my ($dom,$nam,$hom,$what)=@_;
 2349:     return critical("log:$dom:$nam:$what",$hom);
 2350: }
 2351: 
 2352: # ------------------------------------------------------------------ Course Log
 2353: #
 2354: # This routine flushes several buffers of non-mission-critical nature
 2355: #
 2356: 
 2357: sub flushcourselogs {
 2358:     &logthis('Flushing log buffers');
 2359: #
 2360: # course logs
 2361: # This is a log of all transactions in a course, which can be used
 2362: # for data mining purposes
 2363: #
 2364: # It also collects the courseid database, which lists last transaction
 2365: # times and course titles for all courseids
 2366: #
 2367:     my %courseidbuffer=();
 2368:     foreach my $crsid (keys(%courselogs)) {
 2369:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2370: 		          &escape($courselogs{$crsid}),
 2371: 		          $coursehombuf{$crsid}) eq 'ok') {
 2372: 	    delete $courselogs{$crsid};
 2373:         } else {
 2374:             &logthis('Failed to flush log buffer for '.$crsid);
 2375:             if (length($courselogs{$crsid})>40000) {
 2376:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2377:                         " exceeded maximum size, deleting.</font>");
 2378:                delete $courselogs{$crsid};
 2379:             }
 2380:         }
 2381:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2382:             'description' => $coursedescrbuf{$crsid},
 2383:             'inst_code'    => $courseinstcodebuf{$crsid},
 2384:             'type'        => $coursetypebuf{$crsid},
 2385:             'owner'       => $courseownerbuf{$crsid},
 2386:         };
 2387:     }
 2388: #
 2389: # Write course id database (reverse lookup) to homeserver of courses 
 2390: # Is used in pickcourse
 2391: #
 2392:     foreach my $crs_home (keys(%courseidbuffer)) {
 2393:         my $response = &courseidput(&host_domain($crs_home),
 2394:                                     $courseidbuffer{$crs_home},
 2395:                                     $crs_home,'timeonly');
 2396:     }
 2397: #
 2398: # File accesses
 2399: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2400: #
 2401:     foreach my $entry (keys(%accesshash)) {
 2402:         if ($entry =~ /___count$/) {
 2403:             my ($dom,$name);
 2404:             ($dom,$name,undef)=
 2405: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2406:             if (! defined($dom) || $dom eq '' || 
 2407:                 ! defined($name) || $name eq '') {
 2408:                 my $cid = $env{'request.course.id'};
 2409:                 $dom  = $env{'request.'.$cid.'.domain'};
 2410:                 $name = $env{'request.'.$cid.'.num'};
 2411:             }
 2412:             my $value = $accesshash{$entry};
 2413:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2414:             my %temphash=($url => $value);
 2415:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2416:             if ($result eq 'ok') {
 2417:                 delete $accesshash{$entry};
 2418:             } elsif ($result eq 'unknown_cmd') {
 2419:                 # Target server has old code running on it.
 2420:                 my %temphash=($entry => $value);
 2421:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2422:                     delete $accesshash{$entry};
 2423:                 }
 2424:             }
 2425:         } else {
 2426:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2427:             my %temphash=($entry => $accesshash{$entry});
 2428:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2429:                 delete $accesshash{$entry};
 2430:             }
 2431:         }
 2432:     }
 2433: #
 2434: # Roles
 2435: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2436: #
 2437:     foreach my $entry (keys(%userrolehash)) {
 2438:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2439: 	    split(/\:/,$entry);
 2440:         if (&Apache::lonnet::put('nohist_userroles',
 2441:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2442:                 $rudom,$runame) eq 'ok') {
 2443: 	    delete $userrolehash{$entry};
 2444:         }
 2445:     }
 2446: #
 2447: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2448: #
 2449:     my %domrolebuffer = ();
 2450:     foreach my $entry (keys %domainrolehash) {
 2451:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2452:         if ($domrolebuffer{$rudom}) {
 2453:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2454:                       '='.&escape($domainrolehash{$entry});
 2455:         } else {
 2456:             $domrolebuffer{$rudom}.=&escape($entry).
 2457:                       '='.&escape($domainrolehash{$entry});
 2458:         }
 2459:         delete $domainrolehash{$entry};
 2460:     }
 2461:     foreach my $dom (keys(%domrolebuffer)) {
 2462: 	my %servers = &get_servers($dom,'library');
 2463: 	foreach my $tryserver (keys(%servers)) {
 2464: 	    unless (&reply('domroleput:'.$dom.':'.
 2465: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2466: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2467: 	    }
 2468:         }
 2469:     }
 2470:     $dumpcount++;
 2471: }
 2472: 
 2473: sub courselog {
 2474:     my $what=shift;
 2475:     $what=time.':'.$what;
 2476:     unless ($env{'request.course.id'}) { return ''; }
 2477:     $coursedombuf{$env{'request.course.id'}}=
 2478:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2479:     $coursenumbuf{$env{'request.course.id'}}=
 2480:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2481:     $coursehombuf{$env{'request.course.id'}}=
 2482:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2483:     $coursedescrbuf{$env{'request.course.id'}}=
 2484:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2485:     $courseinstcodebuf{$env{'request.course.id'}}=
 2486:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2487:     $courseownerbuf{$env{'request.course.id'}}=
 2488:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2489:     $coursetypebuf{$env{'request.course.id'}}=
 2490:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2491:     if (defined $courselogs{$env{'request.course.id'}}) {
 2492: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2493:     } else {
 2494: 	$courselogs{$env{'request.course.id'}}.=$what;
 2495:     }
 2496:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2497: 	&flushcourselogs();
 2498:     }
 2499: }
 2500: 
 2501: sub courseacclog {
 2502:     my $fnsymb=shift;
 2503:     unless ($env{'request.course.id'}) { return ''; }
 2504:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2505:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2506:         $what.=':POST';
 2507:         # FIXME: Probably ought to escape things....
 2508: 	foreach my $key (keys(%env)) {
 2509:             if ($key=~/^form\.(.*)/) {
 2510:                 my $formitem = $1;
 2511:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 2512:                     $what.=':'.$formitem.'='.$env{$key};
 2513:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 2514:                     $what.=':'.$formitem.'='.$env{$key};
 2515:                 }
 2516:             }
 2517:         }
 2518:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2519:         # FIXME: We should not be depending on a form parameter that someone
 2520:         # editing lonsearchcat.pm might change in the future.
 2521:         if ($env{'form.phase'} eq 'course_search') {
 2522:             $what.= ':POST';
 2523:             # FIXME: Probably ought to escape things....
 2524:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2525:                                  'crsdiscuss') {
 2526:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2527:             }
 2528:         }
 2529:     }
 2530:     &courselog($what);
 2531: }
 2532: 
 2533: sub countacc {
 2534:     my $url=&declutter(shift);
 2535:     return if (! defined($url) || $url eq '');
 2536:     unless ($env{'request.course.id'}) { return ''; }
 2537:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2538:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2539:     $accesshash{$key}++;
 2540: }
 2541: 
 2542: sub linklog {
 2543:     my ($from,$to)=@_;
 2544:     $from=&declutter($from);
 2545:     $to=&declutter($to);
 2546:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2547:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2548: }
 2549:   
 2550: sub userrolelog {
 2551:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2552:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2553:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2554:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2555:         ($trole=~/^ta/)) {
 2556:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2557:        $userrolehash
 2558:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2559:                     =$tend.':'.$tstart;
 2560:     }
 2561:     if (($env{'request.role'} =~ /dc\./) &&
 2562: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2563: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2564: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
 2565:        $userrolehash
 2566:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2567:                     =$tend.':'.$tstart;
 2568:     }
 2569:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2570:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2571:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2572:         ($trole=~/^sc/)) {
 2573:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2574:        $domainrolehash
 2575:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2576:                     = $tend.':'.$tstart;
 2577:     }
 2578: }
 2579: 
 2580: sub courserolelog {
 2581:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 2582:     if (($trole eq 'cc') || ($trole eq 'in') ||
 2583:         ($trole eq 'ep') || ($trole eq 'ad') ||
 2584:         ($trole eq 'ta') || ($trole eq 'st') ||
 2585:         ($trole=~/^cr/) || ($trole eq 'gr')) {
 2586:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 2587:             my $cdom = $1;
 2588:             my $cnum = $2;
 2589:             my $sec = $3;
 2590:             my $namespace = 'rolelog';
 2591:             my %storehash = (
 2592:                                role    => $trole,
 2593:                                start   => $tstart,
 2594:                                end     => $tend,
 2595:                                selfenroll => $selfenroll,
 2596:                                context    => $context,
 2597:                             );
 2598:             if ($trole eq 'gr') {
 2599:                 $namespace = 'groupslog';
 2600:                 $storehash{'group'} = $sec;
 2601:             } else {
 2602:                 $storehash{'section'} = $sec;
 2603:             }
 2604:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 2605:         }
 2606:     }
 2607:     return;
 2608: }
 2609: 
 2610: sub get_course_adv_roles {
 2611:     my ($cid,$codes) = @_;
 2612:     $cid=$env{'request.course.id'} unless (defined($cid));
 2613:     my %coursehash=&coursedescription($cid);
 2614:     my %nothide=();
 2615:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2616:         if ($user !~ /:/) {
 2617: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2618:         } else {
 2619:             $nothide{$user}=1;
 2620:         }
 2621:     }
 2622:     my %returnhash=();
 2623:     my %dumphash=
 2624:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2625:     my $now=time;
 2626:     foreach my $entry (keys %dumphash) {
 2627: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2628:         if (($tstart) && ($tstart<0)) { next; }
 2629:         if (($tend) && ($tend<$now)) { next; }
 2630:         if (($tstart) && ($now<$tstart)) { next; }
 2631:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2632: 	if ($username eq '' || $domain eq '') { next; }
 2633: 	if ((&privileged($username,$domain)) && 
 2634: 	    (!$nothide{$username.':'.$domain})) { next; }
 2635: 	if ($role eq 'cr') { next; }
 2636:         if ($codes) {
 2637:             if ($section) { $role .= ':'.$section; }
 2638:             if ($returnhash{$role}) {
 2639:                 $returnhash{$role}.=','.$username.':'.$domain;
 2640:             } else {
 2641:                 $returnhash{$role}=$username.':'.$domain;
 2642:             }
 2643:         } else {
 2644:             my $key=&plaintext($role);
 2645:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 2646:             if ($returnhash{$key}) {
 2647: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2648:             } else {
 2649:                 $returnhash{$key}=$username.':'.$domain;
 2650:             }
 2651:         }
 2652:     }
 2653:     return %returnhash;
 2654: }
 2655: 
 2656: sub get_my_roles {
 2657:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2658:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2659:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2660:     my (%dumphash,%nothide);
 2661:     if ($context eq 'userroles') { 
 2662:         %dumphash = &dump('roles',$udom,$uname);
 2663:     } else {
 2664:         %dumphash=
 2665:             &dump('nohist_userroles',$udom,$uname);
 2666:         if ($hidepriv) {
 2667:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2668:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2669:                 if ($user !~ /:/) {
 2670:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2671:                 } else {
 2672:                     $nothide{$user} = 1;
 2673:                 }
 2674:             }
 2675:         }
 2676:     }
 2677:     my %returnhash=();
 2678:     my $now=time;
 2679:     foreach my $entry (keys(%dumphash)) {
 2680:         my ($role,$tend,$tstart);
 2681:         if ($context eq 'userroles') {
 2682: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2683:         } else {
 2684:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2685:         }
 2686:         if (($tstart) && ($tstart<0)) { next; }
 2687:         my $status = 'active';
 2688:         if (($tend) && ($tend<=$now)) {
 2689:             $status = 'previous';
 2690:         } 
 2691:         if (($tstart) && ($now<$tstart)) {
 2692:             $status = 'future';
 2693:         }
 2694:         if (ref($types) eq 'ARRAY') {
 2695:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2696:                 next;
 2697:             } 
 2698:         } else {
 2699:             if ($status ne 'active') {
 2700:                 next;
 2701:             }
 2702:         }
 2703:         my ($rolecode,$username,$domain,$section,$area);
 2704:         if ($context eq 'userroles') {
 2705:             ($area,$rolecode) = split(/_/,$entry);
 2706:             (undef,$domain,$username,$section) = split(/\//,$area);
 2707:         } else {
 2708:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2709:         }
 2710:         if (ref($roledoms) eq 'ARRAY') {
 2711:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2712:                 next;
 2713:             }
 2714:         }
 2715:         if (ref($roles) eq 'ARRAY') {
 2716:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2717:                 if ($role =~ /^cr\//) {
 2718:                     if (!grep(/^cr$/,@{$roles})) {
 2719:                         next;
 2720:                     }
 2721:                 } else {
 2722:                     next;
 2723:                 }
 2724:             }
 2725:         }
 2726:         if ($hidepriv) {
 2727:             if ((&privileged($username,$domain)) &&
 2728:                 (!$nothide{$username.':'.$domain})) { 
 2729:                 next;
 2730:             }
 2731:         }
 2732:         if ($withsec) {
 2733:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2734:                 $tstart.':'.$tend;
 2735:         } else {
 2736:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2737:         }
 2738:     }
 2739:     return %returnhash;
 2740: }
 2741: 
 2742: # ----------------------------------------------------- Frontpage Announcements
 2743: #
 2744: #
 2745: 
 2746: sub postannounce {
 2747:     my ($server,$text)=@_;
 2748:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2749:     unless ($text=~/\w/) { $text=''; }
 2750:     return &reply('setannounce:'.&escape($text),$server);
 2751: }
 2752: 
 2753: sub getannounce {
 2754: 
 2755:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2756: 	my $announcement='';
 2757: 	while (my $line = <$fh>) { $announcement .= $line; }
 2758: 	close($fh);
 2759: 	if ($announcement=~/\w/) { 
 2760: 	    return 
 2761:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2762:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2763: 	} else {
 2764: 	    return '';
 2765: 	}
 2766:     } else {
 2767: 	return '';
 2768:     }
 2769: }
 2770: 
 2771: # ---------------------------------------------------------- Course ID routines
 2772: # Deal with domain's nohist_courseid.db files
 2773: #
 2774: 
 2775: sub courseidput {
 2776:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2777:     my $outcome;
 2778:     if ($caller eq 'timeonly') {
 2779:         my $cids = '';
 2780:         foreach my $item (keys(%$storehash)) {
 2781:             $cids.=&escape($item).'&';
 2782:         }
 2783:         $cids=~s/\&$//;
 2784:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 2785:                           $coursehome);       
 2786:     } else {
 2787:         my $items = '';
 2788:         foreach my $item (keys(%$storehash)) {
 2789:             $items.= &escape($item).'='.
 2790:                      &freeze_escape($$storehash{$item}).'&';
 2791:         }
 2792:         $items=~s/\&$//;
 2793:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 2794:                           $coursehome);
 2795:     }
 2796:     if ($outcome eq 'unknown_cmd') {
 2797:         my $what;
 2798:         foreach my $cid (keys(%$storehash)) {
 2799:             $what .= &escape($cid).'=';
 2800:             foreach my $item ('description','inst_code','owner','type') {
 2801:                 $what .= &escape($storehash->{$cid}{$item}).':';
 2802:             }
 2803:             $what =~ s/\:$/&/;
 2804:         }
 2805:         $what =~ s/\&$//;  
 2806:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2807:     } else {
 2808:         return $outcome;
 2809:     }
 2810: }
 2811: 
 2812: sub courseiddump {
 2813:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 2814:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 2815:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
 2816:     my $as_hash = 1;
 2817:     my %returnhash;
 2818:     if (!$domfilter) { $domfilter=''; }
 2819:     my %libserv = &all_library();
 2820:     foreach my $tryserver (keys(%libserv)) {
 2821:         if ( (  $hostidflag == 1 
 2822: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2823: 	     || (!defined($hostidflag)) ) {
 2824: 
 2825: 	    if (($domfilter eq '') ||
 2826: 		(&host_domain($tryserver) eq $domfilter)) {
 2827:                 my $rep = 
 2828:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 2829:                          $sincefilter.':'.&escape($descfilter).':'.
 2830:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 2831:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 2832:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 2833:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 2834:                          $showhidden.':'.$caller,$tryserver);
 2835:                 my @pairs=split(/\&/,$rep);
 2836:                 foreach my $item (@pairs) {
 2837:                     my ($key,$value)=split(/\=/,$item,2);
 2838:                     $key = &unescape($key);
 2839:                     next if ($key =~ /^error: 2 /);
 2840:                     my $result = &thaw_unescape($value);
 2841:                     if (ref($result) eq 'HASH') {
 2842:                         $returnhash{$key}=$result;
 2843:                     } else {
 2844:                         my @responses = split(/:/,$value);
 2845:                         my @items = ('description','inst_code','owner','type');
 2846:                         for (my $i=0; $i<@responses; $i++) {
 2847:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 2848:                         }
 2849:                     } 
 2850:                 }
 2851:             }
 2852:         }
 2853:     }
 2854:     return %returnhash;
 2855: }
 2856: 
 2857: # ---------------------------------------------------------- DC e-mail
 2858: 
 2859: sub dcmailput {
 2860:     my ($domain,$msgid,$message,$server)=@_;
 2861:     my $status = &Apache::lonnet::critical(
 2862:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2863:        &escape($message),$server);
 2864:     return $status;
 2865: }
 2866: 
 2867: sub dcmaildump {
 2868:     my ($dom,$startdate,$enddate,$senders) = @_;
 2869:     my %returnhash=();
 2870: 
 2871:     if (defined(&domain($dom,'primary'))) {
 2872:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2873:                                                          &escape($enddate).':';
 2874: 	my @esc_senders=map { &escape($_)} @$senders;
 2875: 	$cmd.=&escape(join('&',@esc_senders));
 2876: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2877:             my ($key,$value) = split(/\=/,$line,2);
 2878:             if (($key) && ($value)) {
 2879:                 $returnhash{&unescape($key)} = &unescape($value);
 2880:             }
 2881:         }
 2882:     }
 2883:     return %returnhash;
 2884: }
 2885: # ---------------------------------------------------------- Domain roles
 2886: 
 2887: sub get_domain_roles {
 2888:     my ($dom,$roles,$startdate,$enddate)=@_;
 2889:     if (undef($startdate) || $startdate eq '') {
 2890:         $startdate = '.';
 2891:     }
 2892:     if (undef($enddate) || $enddate eq '') {
 2893:         $enddate = '.';
 2894:     }
 2895:     my $rolelist;
 2896:     if (ref($roles) eq 'ARRAY') {
 2897:         $rolelist = join(':',@{$roles});
 2898:     }
 2899:     my %personnel = ();
 2900: 
 2901:     my %servers = &get_servers($dom,'library');
 2902:     foreach my $tryserver (keys(%servers)) {
 2903: 	%{$personnel{$tryserver}}=();
 2904: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2905: 					    &escape($startdate).':'.
 2906: 					    &escape($enddate).':'.
 2907: 					    &escape($rolelist), $tryserver))) {
 2908: 	    my ($key,$value) = split(/\=/,$line,2);
 2909: 	    if (($key) && ($value)) {
 2910: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2911: 	    }
 2912: 	}
 2913:     }
 2914:     return %personnel;
 2915: }
 2916: 
 2917: # ----------------------------------------------------------- Check out an item
 2918: 
 2919: sub get_first_access {
 2920:     my ($type,$argsymb)=@_;
 2921:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2922:     if ($argsymb) { $symb=$argsymb; }
 2923:     my ($map,$id,$res)=&decode_symb($symb);
 2924:     if ($type eq 'course') {
 2925: 	$res='course';
 2926:     } elsif ($type eq 'map') {
 2927: 	$res=&symbread($map);
 2928:     } else {
 2929: 	$res=$symb;
 2930:     }
 2931:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2932:     return $times{"$courseid\0$res"};
 2933: }
 2934: 
 2935: sub set_first_access {
 2936:     my ($type)=@_;
 2937:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2938:     my ($map,$id,$res)=&decode_symb($symb);
 2939:     if ($type eq 'course') {
 2940: 	$res='course';
 2941:     } elsif ($type eq 'map') {
 2942: 	$res=&symbread($map);
 2943:     } else {
 2944: 	$res=$symb;
 2945:     }
 2946:     my $firstaccess=&get_first_access($type,$symb);
 2947:     if (!$firstaccess) {
 2948: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2949:     }
 2950:     return 'already_set';
 2951: }
 2952: 
 2953: sub checkout {
 2954:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2955:     my $now=time;
 2956:     my $lonhost=$perlvar{'lonHostID'};
 2957:     my $infostr=&escape(
 2958:                  'CHECKOUTTOKEN&'.
 2959:                  $tuname.'&'.
 2960:                  $tudom.'&'.
 2961:                  $tcrsid.'&'.
 2962:                  $symb.'&'.
 2963: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2964:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2965:     if ($token=~/^error\:/) { 
 2966:         &logthis("<font color=\"blue\">WARNING: ".
 2967:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2968:                  "</font>");
 2969:         return ''; 
 2970:     }
 2971: 
 2972:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2973:     $token=~tr/a-z/A-Z/;
 2974: 
 2975:     my %infohash=('resource.0.outtoken' => $token,
 2976:                   'resource.0.checkouttime' => $now,
 2977:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2978: 
 2979:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2980:        return '';
 2981:     } else {
 2982:         &logthis("<font color=\"blue\">WARNING: ".
 2983:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2984:                  "</font>");
 2985:     }    
 2986: 
 2987:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2988:                          &escape('Checkout '.$infostr.' - '.
 2989:                                                  $token)) ne 'ok') {
 2990: 	return '';
 2991:     } else {
 2992:         &logthis("<font color=\"blue\">WARNING: ".
 2993:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2994:                  "</font>");
 2995:     }
 2996:     return $token;
 2997: }
 2998: 
 2999: # ------------------------------------------------------------ Check in an item
 3000: 
 3001: sub checkin {
 3002:     my $token=shift;
 3003:     my $now=time;
 3004:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 3005:     $lonhost=~tr/A-Z/a-z/;
 3006:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 3007:     $dtoken=~s/\W/\_/g;
 3008:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 3009:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 3010: 
 3011:     unless (($tuname) && ($tudom)) {
 3012:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 3013:         return '';
 3014:     }
 3015:     
 3016:     unless (&allowed('mgr',$tcrsid)) {
 3017:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 3018:                  $env{'user.name'}.' - '.$env{'user.domain'});
 3019:         return '';
 3020:     }
 3021: 
 3022:     my %infohash=('resource.0.intoken' => $token,
 3023:                   'resource.0.checkintime' => $now,
 3024:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 3025: 
 3026:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3027:        return '';
 3028:     }    
 3029: 
 3030:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3031:                          &escape('Checkin - '.$token)) ne 'ok') {
 3032: 	return '';
 3033:     }
 3034: 
 3035:     return ($symb,$tuname,$tudom,$tcrsid);    
 3036: }
 3037: 
 3038: # --------------------------------------------- Set Expire Date for Spreadsheet
 3039: 
 3040: sub expirespread {
 3041:     my ($uname,$udom,$stype,$usymb)=@_;
 3042:     my $cid=$env{'request.course.id'}; 
 3043:     if ($cid) {
 3044:        my $now=time;
 3045:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3046:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3047:                             $env{'course.'.$cid.'.num'}.
 3048: 	        	    ':nohist_expirationdates:'.
 3049:                             &escape($key).'='.$now,
 3050:                             $env{'course.'.$cid.'.home'})
 3051:     }
 3052:     return 'ok';
 3053: }
 3054: 
 3055: # ----------------------------------------------------- Devalidate Spreadsheets
 3056: 
 3057: sub devalidate {
 3058:     my ($symb,$uname,$udom)=@_;
 3059:     my $cid=$env{'request.course.id'}; 
 3060:     if ($cid) {
 3061:         # delete the stored spreadsheets for
 3062:         # - the student level sheet of this user in course's homespace
 3063:         # - the assessment level sheet for this resource 
 3064:         #   for this user in user's homespace
 3065: 	# - current conditional state info
 3066: 	my $key=$uname.':'.$udom.':';
 3067:         my $status=
 3068: 	    &del('nohist_calculatedsheets',
 3069: 		 [$key.'studentcalc:'],
 3070: 		 $env{'course.'.$cid.'.domain'},
 3071: 		 $env{'course.'.$cid.'.num'})
 3072: 		.' '.
 3073: 	    &del('nohist_calculatedsheets_'.$cid,
 3074: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3075:         unless ($status eq 'ok ok') {
 3076:            &logthis('Could not devalidate spreadsheet '.
 3077:                     $uname.' at '.$udom.' for '.
 3078: 		    $symb.': '.$status);
 3079:         }
 3080: 	&delenv('user.state.'.$cid);
 3081:     }
 3082: }
 3083: 
 3084: sub get_scalar {
 3085:     my ($string,$end) = @_;
 3086:     my $value;
 3087:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3088: 	$value = $1;
 3089:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3090: 	$value = $1;
 3091:     }
 3092:     return &unescape($value);
 3093: }
 3094: 
 3095: sub array2str {
 3096:   my (@array) = @_;
 3097:   my $result=&arrayref2str(\@array);
 3098:   $result=~s/^__ARRAY_REF__//;
 3099:   $result=~s/__END_ARRAY_REF__$//;
 3100:   return $result;
 3101: }
 3102: 
 3103: sub arrayref2str {
 3104:   my ($arrayref) = @_;
 3105:   my $result='__ARRAY_REF__';
 3106:   foreach my $elem (@$arrayref) {
 3107:     if(ref($elem) eq 'ARRAY') {
 3108:       $result.=&arrayref2str($elem).'&';
 3109:     } elsif(ref($elem) eq 'HASH') {
 3110:       $result.=&hashref2str($elem).'&';
 3111:     } elsif(ref($elem)) {
 3112:       #print("Got a ref of ".(ref($elem))." skipping.");
 3113:     } else {
 3114:       $result.=&escape($elem).'&';
 3115:     }
 3116:   }
 3117:   $result=~s/\&$//;
 3118:   $result .= '__END_ARRAY_REF__';
 3119:   return $result;
 3120: }
 3121: 
 3122: sub hash2str {
 3123:   my (%hash) = @_;
 3124:   my $result=&hashref2str(\%hash);
 3125:   $result=~s/^__HASH_REF__//;
 3126:   $result=~s/__END_HASH_REF__$//;
 3127:   return $result;
 3128: }
 3129: 
 3130: sub hashref2str {
 3131:   my ($hashref)=@_;
 3132:   my $result='__HASH_REF__';
 3133:   foreach my $key (sort(keys(%$hashref))) {
 3134:     if (ref($key) eq 'ARRAY') {
 3135:       $result.=&arrayref2str($key).'=';
 3136:     } elsif (ref($key) eq 'HASH') {
 3137:       $result.=&hashref2str($key).'=';
 3138:     } elsif (ref($key)) {
 3139:       $result.='=';
 3140:       #print("Got a ref of ".(ref($key))." skipping.");
 3141:     } else {
 3142: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3143:     }
 3144: 
 3145:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3146:       $result.=&arrayref2str($hashref->{$key}).'&';
 3147:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3148:       $result.=&hashref2str($hashref->{$key}).'&';
 3149:     } elsif(ref($hashref->{$key})) {
 3150:        $result.='&';
 3151:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3152:     } else {
 3153:       $result.=&escape($hashref->{$key}).'&';
 3154:     }
 3155:   }
 3156:   $result=~s/\&$//;
 3157:   $result .= '__END_HASH_REF__';
 3158:   return $result;
 3159: }
 3160: 
 3161: sub str2hash {
 3162:     my ($string)=@_;
 3163:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3164:     return %$hash;
 3165: }
 3166: 
 3167: sub str2hashref {
 3168:   my ($string) = @_;
 3169: 
 3170:   my %hash;
 3171: 
 3172:   if($string !~ /^__HASH_REF__/) {
 3173:       if (! ($string eq '' || !defined($string))) {
 3174: 	  $hash{'error'}='Not hash reference';
 3175:       }
 3176:       return (\%hash, $string);
 3177:   }
 3178: 
 3179:   $string =~ s/^__HASH_REF__//;
 3180: 
 3181:   while($string !~ /^__END_HASH_REF__/) {
 3182:       #key
 3183:       my $key='';
 3184:       if($string =~ /^__HASH_REF__/) {
 3185:           ($key, $string)=&str2hashref($string);
 3186:           if(defined($key->{'error'})) {
 3187:               $hash{'error'}='Bad data';
 3188:               return (\%hash, $string);
 3189:           }
 3190:       } elsif($string =~ /^__ARRAY_REF__/) {
 3191:           ($key, $string)=&str2arrayref($string);
 3192:           if($key->[0] eq 'Array reference error') {
 3193:               $hash{'error'}='Bad data';
 3194:               return (\%hash, $string);
 3195:           }
 3196:       } else {
 3197:           $string =~ s/^(.*?)=//;
 3198: 	  $key=&unescape($1);
 3199:       }
 3200:       $string =~ s/^=//;
 3201: 
 3202:       #value
 3203:       my $value='';
 3204:       if($string =~ /^__HASH_REF__/) {
 3205:           ($value, $string)=&str2hashref($string);
 3206:           if(defined($value->{'error'})) {
 3207:               $hash{'error'}='Bad data';
 3208:               return (\%hash, $string);
 3209:           }
 3210:       } elsif($string =~ /^__ARRAY_REF__/) {
 3211:           ($value, $string)=&str2arrayref($string);
 3212:           if($value->[0] eq 'Array reference error') {
 3213:               $hash{'error'}='Bad data';
 3214:               return (\%hash, $string);
 3215:           }
 3216:       } else {
 3217: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3218:       }
 3219:       $string =~ s/^&//;
 3220: 
 3221:       $hash{$key}=$value;
 3222:   }
 3223: 
 3224:   $string =~ s/^__END_HASH_REF__//;
 3225: 
 3226:   return (\%hash, $string);
 3227: }
 3228: 
 3229: sub str2array {
 3230:     my ($string)=@_;
 3231:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3232:     return @$array;
 3233: }
 3234: 
 3235: sub str2arrayref {
 3236:   my ($string) = @_;
 3237:   my @array;
 3238: 
 3239:   if($string !~ /^__ARRAY_REF__/) {
 3240:       if (! ($string eq '' || !defined($string))) {
 3241: 	  $array[0]='Array reference error';
 3242:       }
 3243:       return (\@array, $string);
 3244:   }
 3245: 
 3246:   $string =~ s/^__ARRAY_REF__//;
 3247: 
 3248:   while($string !~ /^__END_ARRAY_REF__/) {
 3249:       my $value='';
 3250:       if($string =~ /^__HASH_REF__/) {
 3251:           ($value, $string)=&str2hashref($string);
 3252:           if(defined($value->{'error'})) {
 3253:               $array[0] ='Array reference error';
 3254:               return (\@array, $string);
 3255:           }
 3256:       } elsif($string =~ /^__ARRAY_REF__/) {
 3257:           ($value, $string)=&str2arrayref($string);
 3258:           if($value->[0] eq 'Array reference error') {
 3259:               $array[0] ='Array reference error';
 3260:               return (\@array, $string);
 3261:           }
 3262:       } else {
 3263: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3264:       }
 3265:       $string =~ s/^&//;
 3266: 
 3267:       push(@array, $value);
 3268:   }
 3269: 
 3270:   $string =~ s/^__END_ARRAY_REF__//;
 3271: 
 3272:   return (\@array, $string);
 3273: }
 3274: 
 3275: # -------------------------------------------------------------------Temp Store
 3276: 
 3277: sub tmpreset {
 3278:   my ($symb,$namespace,$domain,$stuname) = @_;
 3279:   if (!$symb) {
 3280:     $symb=&symbread();
 3281:     if (!$symb) { $symb= $env{'request.url'}; }
 3282:   }
 3283:   $symb=escape($symb);
 3284: 
 3285:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3286:   $namespace=~s/\//\_/g;
 3287:   $namespace=~s/\W//g;
 3288: 
 3289:   if (!$domain) { $domain=$env{'user.domain'}; }
 3290:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3291:   if ($domain eq 'public' && $stuname eq 'public') {
 3292:       $stuname=$ENV{'REMOTE_ADDR'};
 3293:   }
 3294:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3295:   my %hash;
 3296:   if (tie(%hash,'GDBM_File',
 3297: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3298: 	  &GDBM_WRCREAT(),0640)) {
 3299:     foreach my $key (keys %hash) {
 3300:       if ($key=~ /:$symb/) {
 3301: 	delete($hash{$key});
 3302:       }
 3303:     }
 3304:   }
 3305: }
 3306: 
 3307: sub tmpstore {
 3308:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3309: 
 3310:   if (!$symb) {
 3311:     $symb=&symbread();
 3312:     if (!$symb) { $symb= $env{'request.url'}; }
 3313:   }
 3314:   $symb=escape($symb);
 3315: 
 3316:   if (!$namespace) {
 3317:     # I don't think we would ever want to store this for a course.
 3318:     # it seems this will only be used if we don't have a course.
 3319:     #$namespace=$env{'request.course.id'};
 3320:     #if (!$namespace) {
 3321:       $namespace=$env{'request.state'};
 3322:     #}
 3323:   }
 3324:   $namespace=~s/\//\_/g;
 3325:   $namespace=~s/\W//g;
 3326:   if (!$domain) { $domain=$env{'user.domain'}; }
 3327:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3328:   if ($domain eq 'public' && $stuname eq 'public') {
 3329:       $stuname=$ENV{'REMOTE_ADDR'};
 3330:   }
 3331:   my $now=time;
 3332:   my %hash;
 3333:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3334:   if (tie(%hash,'GDBM_File',
 3335: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3336: 	  &GDBM_WRCREAT(),0640)) {
 3337:     $hash{"version:$symb"}++;
 3338:     my $version=$hash{"version:$symb"};
 3339:     my $allkeys=''; 
 3340:     foreach my $key (keys(%$storehash)) {
 3341:       $allkeys.=$key.':';
 3342:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3343:     }
 3344:     $hash{"$version:$symb:timestamp"}=$now;
 3345:     $allkeys.='timestamp';
 3346:     $hash{"$version:keys:$symb"}=$allkeys;
 3347:     if (untie(%hash)) {
 3348:       return 'ok';
 3349:     } else {
 3350:       return "error:$!";
 3351:     }
 3352:   } else {
 3353:     return "error:$!";
 3354:   }
 3355: }
 3356: 
 3357: # -----------------------------------------------------------------Temp Restore
 3358: 
 3359: sub tmprestore {
 3360:   my ($symb,$namespace,$domain,$stuname) = @_;
 3361: 
 3362:   if (!$symb) {
 3363:     $symb=&symbread();
 3364:     if (!$symb) { $symb= $env{'request.url'}; }
 3365:   }
 3366:   $symb=escape($symb);
 3367: 
 3368:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3369: 
 3370:   if (!$domain) { $domain=$env{'user.domain'}; }
 3371:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3372:   if ($domain eq 'public' && $stuname eq 'public') {
 3373:       $stuname=$ENV{'REMOTE_ADDR'};
 3374:   }
 3375:   my %returnhash;
 3376:   $namespace=~s/\//\_/g;
 3377:   $namespace=~s/\W//g;
 3378:   my %hash;
 3379:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3380:   if (tie(%hash,'GDBM_File',
 3381: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3382: 	  &GDBM_READER(),0640)) {
 3383:     my $version=$hash{"version:$symb"};
 3384:     $returnhash{'version'}=$version;
 3385:     my $scope;
 3386:     for ($scope=1;$scope<=$version;$scope++) {
 3387:       my $vkeys=$hash{"$scope:keys:$symb"};
 3388:       my @keys=split(/:/,$vkeys);
 3389:       my $key;
 3390:       $returnhash{"$scope:keys"}=$vkeys;
 3391:       foreach $key (@keys) {
 3392: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3393: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3394:       }
 3395:     }
 3396:     if (!(untie(%hash))) {
 3397:       return "error:$!";
 3398:     }
 3399:   } else {
 3400:     return "error:$!";
 3401:   }
 3402:   return %returnhash;
 3403: }
 3404: 
 3405: # ----------------------------------------------------------------------- Store
 3406: 
 3407: sub store {
 3408:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3409:     my $home='';
 3410: 
 3411:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3412: 
 3413:     $symb=&symbclean($symb);
 3414:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3415: 
 3416:     if (!$domain) { $domain=$env{'user.domain'}; }
 3417:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3418: 
 3419:     &devalidate($symb,$stuname,$domain);
 3420: 
 3421:     $symb=escape($symb);
 3422:     if (!$namespace) { 
 3423:        unless ($namespace=$env{'request.course.id'}) { 
 3424:           return ''; 
 3425:        } 
 3426:     }
 3427:     if (!$home) { $home=$env{'user.home'}; }
 3428: 
 3429:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3430:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3431: 
 3432:     my $namevalue='';
 3433:     foreach my $key (keys(%$storehash)) {
 3434:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3435:     }
 3436:     $namevalue=~s/\&$//;
 3437:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3438:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3439: }
 3440: 
 3441: # -------------------------------------------------------------- Critical Store
 3442: 
 3443: sub cstore {
 3444:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3445:     my $home='';
 3446: 
 3447:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3448: 
 3449:     $symb=&symbclean($symb);
 3450:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3451: 
 3452:     if (!$domain) { $domain=$env{'user.domain'}; }
 3453:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3454: 
 3455:     &devalidate($symb,$stuname,$domain);
 3456: 
 3457:     $symb=escape($symb);
 3458:     if (!$namespace) { 
 3459:        unless ($namespace=$env{'request.course.id'}) { 
 3460:           return ''; 
 3461:        } 
 3462:     }
 3463:     if (!$home) { $home=$env{'user.home'}; }
 3464: 
 3465:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3466:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3467: 
 3468:     my $namevalue='';
 3469:     foreach my $key (keys(%$storehash)) {
 3470:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3471:     }
 3472:     $namevalue=~s/\&$//;
 3473:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3474:     return critical
 3475:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3476: }
 3477: 
 3478: # --------------------------------------------------------------------- Restore
 3479: 
 3480: sub restore {
 3481:     my ($symb,$namespace,$domain,$stuname) = @_;
 3482:     my $home='';
 3483: 
 3484:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3485: 
 3486:     if (!$symb) {
 3487:       unless ($symb=escape(&symbread())) { return ''; }
 3488:     } else {
 3489:       $symb=&escape(&symbclean($symb));
 3490:     }
 3491:     if (!$namespace) { 
 3492:        unless ($namespace=$env{'request.course.id'}) { 
 3493:           return ''; 
 3494:        } 
 3495:     }
 3496:     if (!$domain) { $domain=$env{'user.domain'}; }
 3497:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3498:     if (!$home) { $home=$env{'user.home'}; }
 3499:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3500: 
 3501:     my %returnhash=();
 3502:     foreach my $line (split(/\&/,$answer)) {
 3503: 	my ($name,$value)=split(/\=/,$line);
 3504:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3505:     }
 3506:     my $version;
 3507:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3508:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3509:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3510:        }
 3511:     }
 3512:     return %returnhash;
 3513: }
 3514: 
 3515: # ---------------------------------------------------------- Course Description
 3516: 
 3517: sub coursedescription {
 3518:     my ($courseid,$args)=@_;
 3519:     $courseid=~s/^\///;
 3520:     $courseid=~s/\_/\//g;
 3521:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3522:     my $chome=&homeserver($cnum,$cdomain);
 3523:     my $normalid=$cdomain.'_'.$cnum;
 3524:     # need to always cache even if we get errors otherwise we keep 
 3525:     # trying and trying and trying to get the course description.
 3526:     my %envhash=();
 3527:     my %returnhash=();
 3528:     
 3529:     my $expiretime=600;
 3530:     if ($env{'request.course.id'} eq $normalid) {
 3531: 	$expiretime=120;
 3532:     }
 3533: 
 3534:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3535:     if (!$args->{'freshen_cache'}
 3536: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3537: 	foreach my $key (keys(%env)) {
 3538: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3539: 	    my ($setting) = $1;
 3540: 	    $returnhash{$setting} = $env{$key};
 3541: 	}
 3542: 	return %returnhash;
 3543:     }
 3544: 
 3545:     # get the data agin
 3546:     if (!$args->{'one_time'}) {
 3547: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3548:     }
 3549: 
 3550:     if ($chome ne 'no_host') {
 3551:        %returnhash=&dump('environment',$cdomain,$cnum);
 3552:        if (!exists($returnhash{'con_lost'})) {
 3553:            $returnhash{'home'}= $chome;
 3554: 	   $returnhash{'domain'} = $cdomain;
 3555: 	   $returnhash{'num'} = $cnum;
 3556:            if (!defined($returnhash{'type'})) {
 3557:                $returnhash{'type'} = 'Course';
 3558:            }
 3559:            while (my ($name,$value) = each %returnhash) {
 3560:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3561:            }
 3562:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3563:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3564: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3565:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3566:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3567:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3568:        }
 3569:     }
 3570:     if (!$args->{'one_time'}) {
 3571: 	&appenv(\%envhash);
 3572:     }
 3573:     return %returnhash;
 3574: }
 3575: 
 3576: # -------------------------------------------------See if a user is privileged
 3577: 
 3578: sub privileged {
 3579:     my ($username,$domain)=@_;
 3580:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3581: 			&homeserver($username,$domain));
 3582:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3583:     my $now=time;
 3584:     if ($rolesdump ne '') {
 3585:         foreach my $entry (split(/&/,$rolesdump)) {
 3586: 	    if ($entry!~/^rolesdef_/) {
 3587: 		my ($area,$role)=split(/=/,$entry);
 3588: 		$area=~s/\_\w\w$//;
 3589: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3590: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3591: 		    my $active=1;
 3592: 		    if ($tend) {
 3593: 			if ($tend<$now) { $active=0; }
 3594: 		    }
 3595: 		    if ($tstart) {
 3596: 			if ($tstart>$now) { $active=0; }
 3597: 		    }
 3598: 		    if ($active) { return 1; }
 3599: 		}
 3600: 	    }
 3601: 	}
 3602:     }
 3603:     return 0;
 3604: }
 3605: 
 3606: # -------------------------------------------------------- Get user privileges
 3607: 
 3608: sub rolesinit {
 3609:     my ($domain,$username,$authhost)=@_;
 3610:     my %userroles;
 3611:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3612:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
 3613:     my %allroles=();
 3614:     my %allgroups=();   
 3615:     my $now=time;
 3616:     %userroles = ('user.login.time' => $now);
 3617:     my $group_privs;
 3618: 
 3619:     if ($rolesdump ne '') {
 3620:         foreach my $entry (split(/&/,$rolesdump)) {
 3621: 	  if ($entry!~/^rolesdef_/) {
 3622:             my ($area,$role)=split(/=/,$entry);
 3623: 	    $area=~s/\_\w\w$//;
 3624:             my ($trole,$tend,$tstart,$group_privs);
 3625: 	    if ($role=~/^cr/) { 
 3626: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3627: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3628: 		    ($tend,$tstart)=split('_',$trest);
 3629: 		} else {
 3630: 		    $trole=$role;
 3631: 		}
 3632:             } elsif ($role =~ m|^gr/|) {
 3633:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3634:                 ($trole,$group_privs) = split(/\//,$trole);
 3635:                 $group_privs = &unescape($group_privs);
 3636: 	    } else {
 3637: 		($trole,$tend,$tstart)=split(/_/,$role);
 3638: 	    }
 3639: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3640: 					 $username);
 3641: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3642:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3643:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3644:             if (($area ne '') && ($trole ne '')) {
 3645: 		my $spec=$trole.'.'.$area;
 3646: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3647: 		if ($trole =~ /^cr\//) {
 3648:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3649:                 } elsif ($trole eq 'gr') {
 3650:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3651: 		} else {
 3652:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3653: 		}
 3654:             }
 3655:           }
 3656:         }
 3657:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3658:         $userroles{'user.adv'}    = $adv;
 3659: 	$userroles{'user.author'} = $author;
 3660:         $env{'user.adv'}=$adv;
 3661:     }
 3662:     return \%userroles;  
 3663: }
 3664: 
 3665: sub set_arearole {
 3666:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3667: # log the associated role with the area
 3668:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3669:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3670: }
 3671: 
 3672: sub custom_roleprivs {
 3673:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3674:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3675:     my $homsvr=homeserver($rauthor,$rdomain);
 3676:     if (&hostname($homsvr) ne '') {
 3677:         my ($rdummy,$roledef)=
 3678:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3679:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3680:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3681:             if (defined($syspriv)) {
 3682:                 $$allroles{'cm./'}.=':'.$syspriv;
 3683:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3684:             }
 3685:             if ($tdomain ne '') {
 3686:                 if (defined($dompriv)) {
 3687:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3688:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3689:                 }
 3690:                 if (($trest ne '') && (defined($coursepriv))) {
 3691:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3692:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3693:                 }
 3694:             }
 3695:         }
 3696:     }
 3697: }
 3698: 
 3699: sub group_roleprivs {
 3700:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3701:     my $access = 1;
 3702:     my $now = time;
 3703:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3704:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3705:     if ($access) {
 3706:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3707:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3708:     }
 3709: }
 3710: 
 3711: sub standard_roleprivs {
 3712:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3713:     if (defined($pr{$trole.':s'})) {
 3714:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3715:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3716:     }
 3717:     if ($tdomain ne '') {
 3718:         if (defined($pr{$trole.':d'})) {
 3719:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3720:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3721:         }
 3722:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3723:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3724:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3725:         }
 3726:     }
 3727: }
 3728: 
 3729: sub set_userprivs {
 3730:     my ($userroles,$allroles,$allgroups) = @_; 
 3731:     my $author=0;
 3732:     my $adv=0;
 3733:     my %grouproles = ();
 3734:     if (keys(%{$allgroups}) > 0) {
 3735:         foreach my $role (keys %{$allroles}) {
 3736:             my ($trole,$area,$sec,$extendedarea);
 3737:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3738:                 $trole = $1;
 3739:                 $area = $2;
 3740:                 $sec = $3;
 3741:                 $extendedarea = $area.$sec;
 3742:                 if (exists($$allgroups{$area})) {
 3743:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3744:                         my $spec = $trole.'.'.$extendedarea;
 3745:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3746:                                                 $$allgroups{$area}{$group};
 3747:                     }
 3748:                 }
 3749:             }
 3750:         }
 3751:     }
 3752:     foreach my $group (keys(%grouproles)) {
 3753:         $$allroles{$group} = $grouproles{$group};
 3754:     }
 3755:     foreach my $role (keys(%{$allroles})) {
 3756:         my %thesepriv;
 3757:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3758:         foreach my $item (split(/:/,$$allroles{$role})) {
 3759:             if ($item ne '') {
 3760:                 my ($privilege,$restrictions)=split(/&/,$item);
 3761:                 if ($restrictions eq '') {
 3762:                     $thesepriv{$privilege}='F';
 3763:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3764:                     $thesepriv{$privilege}.=$restrictions;
 3765:                 }
 3766:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3767:             }
 3768:         }
 3769:         my $thesestr='';
 3770:         foreach my $priv (keys(%thesepriv)) {
 3771: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3772: 	}
 3773:         $userroles->{'user.priv.'.$role} = $thesestr;
 3774:     }
 3775:     return ($author,$adv);
 3776: }
 3777: 
 3778: # --------------------------------------------------------------- get interface
 3779: 
 3780: sub get {
 3781:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3782:    my $items='';
 3783:    foreach my $item (@$storearr) {
 3784:        $items.=&escape($item).'&';
 3785:    }
 3786:    $items=~s/\&$//;
 3787:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3788:    if (!$uname) { $uname=$env{'user.name'}; }
 3789:    my $uhome=&homeserver($uname,$udomain);
 3790: 
 3791:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3792:    my @pairs=split(/\&/,$rep);
 3793:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3794:      return @pairs;
 3795:    }
 3796:    my %returnhash=();
 3797:    my $i=0;
 3798:    foreach my $item (@$storearr) {
 3799:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3800:       $i++;
 3801:    }
 3802:    return %returnhash;
 3803: }
 3804: 
 3805: # --------------------------------------------------------------- del interface
 3806: 
 3807: sub del {
 3808:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3809:    my $items='';
 3810:    foreach my $item (@$storearr) {
 3811:        $items.=&escape($item).'&';
 3812:    }
 3813:    $items=~s/\&$//;
 3814:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3815:    if (!$uname) { $uname=$env{'user.name'}; }
 3816:    my $uhome=&homeserver($uname,$udomain);
 3817: 
 3818:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3819: }
 3820: 
 3821: # -------------------------------------------------------------- dump interface
 3822: 
 3823: sub dump {
 3824:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3825:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3826:     if (!$uname) { $uname=$env{'user.name'}; }
 3827:     my $uhome=&homeserver($uname,$udomain);
 3828:     if ($regexp) {
 3829: 	$regexp=&escape($regexp);
 3830:     } else {
 3831: 	$regexp='.';
 3832:     }
 3833:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3834:     my @pairs=split(/\&/,$rep);
 3835:     my %returnhash=();
 3836:     foreach my $item (@pairs) {
 3837: 	my ($key,$value)=split(/=/,$item,2);
 3838: 	$key = &unescape($key);
 3839: 	next if ($key =~ /^error: 2 /);
 3840: 	$returnhash{$key}=&thaw_unescape($value);
 3841:     }
 3842:     return %returnhash;
 3843: }
 3844: 
 3845: # --------------------------------------------------------- dumpstore interface
 3846: 
 3847: sub dumpstore {
 3848:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3849:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3850:    if (!$uname) { $uname=$env{'user.name'}; }
 3851:    my $uhome=&homeserver($uname,$udomain);
 3852:    if ($regexp) {
 3853:        $regexp=&escape($regexp);
 3854:    } else {
 3855:        $regexp='.';
 3856:    }
 3857:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3858:    my @pairs=split(/\&/,$rep);
 3859:    my %returnhash=();
 3860:    foreach my $item (@pairs) {
 3861:        my ($key,$value)=split(/=/,$item,2);
 3862:        next if ($key =~ /^error: 2 /);
 3863:        $returnhash{$key}=&thaw_unescape($value);
 3864:    }
 3865:    return %returnhash;
 3866: }
 3867: 
 3868: # -------------------------------------------------------------- keys interface
 3869: 
 3870: sub getkeys {
 3871:    my ($namespace,$udomain,$uname)=@_;
 3872:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3873:    if (!$uname) { $uname=$env{'user.name'}; }
 3874:    my $uhome=&homeserver($uname,$udomain);
 3875:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3876:    my @keyarray=();
 3877:    foreach my $key (split(/\&/,$rep)) {
 3878:       next if ($key =~ /^error: 2 /);
 3879:       push(@keyarray,&unescape($key));
 3880:    }
 3881:    return @keyarray;
 3882: }
 3883: 
 3884: # --------------------------------------------------------------- currentdump
 3885: sub currentdump {
 3886:    my ($courseid,$sdom,$sname)=@_;
 3887:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3888:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3889:    $sname    = $env{'user.name'}         if (! defined($sname));
 3890:    my $uhome = &homeserver($sname,$sdom);
 3891:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3892:    return if ($rep =~ /^(error:|no_such_host)/);
 3893:    #
 3894:    my %returnhash=();
 3895:    #
 3896:    if ($rep eq "unknown_cmd") { 
 3897:        # an old lond will not know currentdump
 3898:        # Do a dump and make it look like a currentdump
 3899:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3900:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3901:        my %hash = @tmp;
 3902:        @tmp=();
 3903:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3904:    } else {
 3905:        my @pairs=split(/\&/,$rep);
 3906:        foreach my $pair (@pairs) {
 3907:            my ($key,$value)=split(/=/,$pair,2);
 3908:            my ($symb,$param) = split(/:/,$key);
 3909:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3910:                                                         &thaw_unescape($value);
 3911:        }
 3912:    }
 3913:    return %returnhash;
 3914: }
 3915: 
 3916: sub convert_dump_to_currentdump{
 3917:     my %hash = %{shift()};
 3918:     my %returnhash;
 3919:     # Code ripped from lond, essentially.  The only difference
 3920:     # here is the unescaping done by lonnet::dump().  Conceivably
 3921:     # we might run in to problems with parameter names =~ /^v\./
 3922:     while (my ($key,$value) = each(%hash)) {
 3923:         my ($v,$symb,$param) = split(/:/,$key);
 3924: 	$symb  = &unescape($symb);
 3925: 	$param = &unescape($param);
 3926:         next if ($v eq 'version' || $symb eq 'keys');
 3927:         next if (exists($returnhash{$symb}) &&
 3928:                  exists($returnhash{$symb}->{$param}) &&
 3929:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3930:         $returnhash{$symb}->{$param}=$value;
 3931:         $returnhash{$symb}->{'v.'.$param}=$v;
 3932:     }
 3933:     #
 3934:     # Remove all of the keys in the hashes which keep track of
 3935:     # the version of the parameter.
 3936:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3937:         # use a foreach because we are going to delete from the hash.
 3938:         foreach my $key (keys(%$param_hash)) {
 3939:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3940:         }
 3941:     }
 3942:     return \%returnhash;
 3943: }
 3944: 
 3945: # ------------------------------------------------------ critical inc interface
 3946: 
 3947: sub cinc {
 3948:     return &inc(@_,'critical');
 3949: }
 3950: 
 3951: # --------------------------------------------------------------- inc interface
 3952: 
 3953: sub inc {
 3954:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3955:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3956:     if (!$uname) { $uname=$env{'user.name'}; }
 3957:     my $uhome=&homeserver($uname,$udomain);
 3958:     my $items='';
 3959:     if (! ref($store)) {
 3960:         # got a single value, so use that instead
 3961:         $items = &escape($store).'=&';
 3962:     } elsif (ref($store) eq 'SCALAR') {
 3963:         $items = &escape($$store).'=&';        
 3964:     } elsif (ref($store) eq 'ARRAY') {
 3965:         $items = join('=&',map {&escape($_);} @{$store});
 3966:     } elsif (ref($store) eq 'HASH') {
 3967:         while (my($key,$value) = each(%{$store})) {
 3968:             $items.= &escape($key).'='.&escape($value).'&';
 3969:         }
 3970:     }
 3971:     $items=~s/\&$//;
 3972:     if ($critical) {
 3973: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3974:     } else {
 3975: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3976:     }
 3977: }
 3978: 
 3979: # --------------------------------------------------------------- put interface
 3980: 
 3981: sub put {
 3982:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3983:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3984:    if (!$uname) { $uname=$env{'user.name'}; }
 3985:    my $uhome=&homeserver($uname,$udomain);
 3986:    my $items='';
 3987:    foreach my $item (keys(%$storehash)) {
 3988:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3989:    }
 3990:    $items=~s/\&$//;
 3991:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3992: }
 3993: 
 3994: # ------------------------------------------------------------ newput interface
 3995: 
 3996: sub newput {
 3997:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3998:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3999:    if (!$uname) { $uname=$env{'user.name'}; }
 4000:    my $uhome=&homeserver($uname,$udomain);
 4001:    my $items='';
 4002:    foreach my $key (keys(%$storehash)) {
 4003:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4004:    }
 4005:    $items=~s/\&$//;
 4006:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 4007: }
 4008: 
 4009: # ---------------------------------------------------------  putstore interface
 4010: 
 4011: sub putstore {
 4012:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4013:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4014:    if (!$uname) { $uname=$env{'user.name'}; }
 4015:    my $uhome=&homeserver($uname,$udomain);
 4016:    my $items='';
 4017:    foreach my $key (keys(%$storehash)) {
 4018:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 4019:    }
 4020:    $items=~s/\&$//;
 4021:    my $esc_symb=&escape($symb);
 4022:    my $esc_v=&escape($version);
 4023:    my $reply =
 4024:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 4025: 	      $uhome);
 4026:    if ($reply eq 'unknown_cmd') {
 4027:        # gfall back to way things use to be done
 4028:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 4029: 			    $uname);
 4030:    }
 4031:    return $reply;
 4032: }
 4033: 
 4034: sub old_putstore {
 4035:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4036:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4037:     if (!$uname) { $uname=$env{'user.name'}; }
 4038:     my $uhome=&homeserver($uname,$udomain);
 4039:     my %newstorehash;
 4040:     foreach my $item (keys(%$storehash)) {
 4041: 	my $key = $version.':'.&escape($symb).':'.$item;
 4042: 	$newstorehash{$key} = $storehash->{$item};
 4043:     }
 4044:     my $items='';
 4045:     my %allitems = ();
 4046:     foreach my $item (keys(%newstorehash)) {
 4047: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 4048: 	    my $key = $1.':keys:'.$2;
 4049: 	    $allitems{$key} .= $3.':';
 4050: 	}
 4051: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 4052:     }
 4053:     foreach my $item (keys(%allitems)) {
 4054: 	$allitems{$item} =~ s/\:$//;
 4055: 	$items.= $item.'='.$allitems{$item}.'&';
 4056:     }
 4057:     $items=~s/\&$//;
 4058:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4059: }
 4060: 
 4061: # ------------------------------------------------------ critical put interface
 4062: 
 4063: sub cput {
 4064:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4065:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4066:    if (!$uname) { $uname=$env{'user.name'}; }
 4067:    my $uhome=&homeserver($uname,$udomain);
 4068:    my $items='';
 4069:    foreach my $item (keys(%$storehash)) {
 4070:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4071:    }
 4072:    $items=~s/\&$//;
 4073:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 4074: }
 4075: 
 4076: # -------------------------------------------------------------- eget interface
 4077: 
 4078: sub eget {
 4079:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4080:    my $items='';
 4081:    foreach my $item (@$storearr) {
 4082:        $items.=&escape($item).'&';
 4083:    }
 4084:    $items=~s/\&$//;
 4085:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4086:    if (!$uname) { $uname=$env{'user.name'}; }
 4087:    my $uhome=&homeserver($uname,$udomain);
 4088:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 4089:    my @pairs=split(/\&/,$rep);
 4090:    my %returnhash=();
 4091:    my $i=0;
 4092:    foreach my $item (@$storearr) {
 4093:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4094:       $i++;
 4095:    }
 4096:    return %returnhash;
 4097: }
 4098: 
 4099: # ------------------------------------------------------------ tmpput interface
 4100: sub tmpput {
 4101:     my ($storehash,$server,$context)=@_;
 4102:     my $items='';
 4103:     foreach my $item (keys(%$storehash)) {
 4104: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4105:     }
 4106:     $items=~s/\&$//;
 4107:     if (defined($context)) {
 4108:         $items .= ':'.&escape($context);
 4109:     }
 4110:     return &reply("tmpput:$items",$server);
 4111: }
 4112: 
 4113: # ------------------------------------------------------------ tmpget interface
 4114: sub tmpget {
 4115:     my ($token,$server)=@_;
 4116:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4117:     my $rep=&reply("tmpget:$token",$server);
 4118:     my %returnhash;
 4119:     foreach my $item (split(/\&/,$rep)) {
 4120: 	my ($key,$value)=split(/=/,$item);
 4121:         next if ($key =~ /^error: 2 /);
 4122: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 4123:     }
 4124:     return %returnhash;
 4125: }
 4126: 
 4127: # ------------------------------------------------------------ tmpget interface
 4128: sub tmpdel {
 4129:     my ($token,$server)=@_;
 4130:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4131:     return &reply("tmpdel:$token",$server);
 4132: }
 4133: 
 4134: # -------------------------------------------------- portfolio access checking
 4135: 
 4136: sub portfolio_access {
 4137:     my ($requrl) = @_;
 4138:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4139:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4140:     if ($result) {
 4141:         my %setters;
 4142:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4143:             my ($startblock,$endblock) =
 4144:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4145:             if ($startblock && $endblock) {
 4146:                 return 'B';
 4147:             }
 4148:         } else {
 4149:             my ($startblock,$endblock) =
 4150:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4151:             if ($startblock && $endblock) {
 4152:                 return 'B';
 4153:             }
 4154:         }
 4155:     }
 4156:     if ($result eq 'ok') {
 4157:        return 'F';
 4158:     } elsif ($result =~ /^[^:]+:guest_/) {
 4159:        return 'A';
 4160:     }
 4161:     return '';
 4162: }
 4163: 
 4164: sub get_portfolio_access {
 4165:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4166: 
 4167:     if (!ref($access_hash)) {
 4168: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4169: 	my %access_controls = &get_access_controls($current_perms,$group,
 4170: 						   $file_name);
 4171: 	$access_hash = $access_controls{$file_name};
 4172:     }
 4173: 
 4174:     my ($public,$guest,@domains,@users,@courses,@groups);
 4175:     my $now = time;
 4176:     if (ref($access_hash) eq 'HASH') {
 4177:         foreach my $key (keys(%{$access_hash})) {
 4178:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4179:             if ($start > $now) {
 4180:                 next;
 4181:             }
 4182:             if ($end && $end<$now) {
 4183:                 next;
 4184:             }
 4185:             if ($scope eq 'public') {
 4186:                 $public = $key;
 4187:                 last;
 4188:             } elsif ($scope eq 'guest') {
 4189:                 $guest = $key;
 4190:             } elsif ($scope eq 'domains') {
 4191:                 push(@domains,$key);
 4192:             } elsif ($scope eq 'users') {
 4193:                 push(@users,$key);
 4194:             } elsif ($scope eq 'course') {
 4195:                 push(@courses,$key);
 4196:             } elsif ($scope eq 'group') {
 4197:                 push(@groups,$key);
 4198:             }
 4199:         }
 4200:         if ($public) {
 4201:             return 'ok';
 4202:         }
 4203:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4204:             if ($guest) {
 4205:                 return $guest;
 4206:             }
 4207:         } else {
 4208:             if (@domains > 0) {
 4209:                 foreach my $domkey (@domains) {
 4210:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4211:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4212:                             return 'ok';
 4213:                         }
 4214:                     }
 4215:                 }
 4216:             }
 4217:             if (@users > 0) {
 4218:                 foreach my $userkey (@users) {
 4219:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4220:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4221:                             if (ref($item) eq 'HASH') {
 4222:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4223:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4224:                                     return 'ok';
 4225:                                 }
 4226:                             }
 4227:                         }
 4228:                     } 
 4229:                 }
 4230:             }
 4231:             my %roleshash;
 4232:             my @courses_and_groups = @courses;
 4233:             push(@courses_and_groups,@groups); 
 4234:             if (@courses_and_groups > 0) {
 4235:                 my (%allgroups,%allroles); 
 4236:                 my ($start,$end,$role,$sec,$group);
 4237:                 foreach my $envkey (%env) {
 4238:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4239:                         my $cid = $2.'_'.$3; 
 4240:                         if ($1 eq 'gr') {
 4241:                             $group = $4;
 4242:                             $allgroups{$cid}{$group} = $env{$envkey};
 4243:                         } else {
 4244:                             if ($4 eq '') {
 4245:                                 $sec = 'none';
 4246:                             } else {
 4247:                                 $sec = $4;
 4248:                             }
 4249:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4250:                         }
 4251:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4252:                         my $cid = $2.'_'.$3;
 4253:                         if ($4 eq '') {
 4254:                             $sec = 'none';
 4255:                         } else {
 4256:                             $sec = $4;
 4257:                         }
 4258:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4259:                     }
 4260:                 }
 4261:                 if (keys(%allroles) == 0) {
 4262:                     return;
 4263:                 }
 4264:                 foreach my $key (@courses_and_groups) {
 4265:                     my %content = %{$$access_hash{$key}};
 4266:                     my $cnum = $content{'number'};
 4267:                     my $cdom = $content{'domain'};
 4268:                     my $cid = $cdom.'_'.$cnum;
 4269:                     if (!exists($allroles{$cid})) {
 4270:                         next;
 4271:                     }    
 4272:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4273:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4274:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4275:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4276:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4277:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4278:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4279:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4280:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4281:                                         if (grep/^all$/,@sections) {
 4282:                                             return 'ok';
 4283:                                         } else {
 4284:                                             if (grep/^$sec$/,@sections) {
 4285:                                                 return 'ok';
 4286:                                             }
 4287:                                         }
 4288:                                     }
 4289:                                 }
 4290:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4291:                                     if (grep/^none$/,@groups) {
 4292:                                         return 'ok';
 4293:                                     }
 4294:                                 } else {
 4295:                                     if (grep/^all$/,@groups) {
 4296:                                         return 'ok';
 4297:                                     } 
 4298:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4299:                                         if (grep/^$group$/,@groups) {
 4300:                                             return 'ok';
 4301:                                         }
 4302:                                     }
 4303:                                 } 
 4304:                             }
 4305:                         }
 4306:                     }
 4307:                 }
 4308:             }
 4309:             if ($guest) {
 4310:                 return $guest;
 4311:             }
 4312:         }
 4313:     }
 4314:     return;
 4315: }
 4316: 
 4317: sub course_group_datechecker {
 4318:     my ($dates,$now,$status) = @_;
 4319:     my ($start,$end) = split(/\./,$dates);
 4320:     if (!$start && !$end) {
 4321:         return 'ok';
 4322:     }
 4323:     if (grep/^active$/,@{$status}) {
 4324:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4325:             return 'ok';
 4326:         }
 4327:     }
 4328:     if (grep/^previous$/,@{$status}) {
 4329:         if ($end > $now ) {
 4330:             return 'ok';
 4331:         }
 4332:     }
 4333:     if (grep/^future$/,@{$status}) {
 4334:         if ($start > $now) {
 4335:             return 'ok';
 4336:         }
 4337:     }
 4338:     return; 
 4339: }
 4340: 
 4341: sub parse_portfolio_url {
 4342:     my ($url) = @_;
 4343: 
 4344:     my ($type,$udom,$unum,$group,$file_name);
 4345:     
 4346:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4347: 	$type = 1;
 4348:         $udom = $1;
 4349:         $unum = $2;
 4350:         $file_name = $3;
 4351:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4352: 	$type = 2;
 4353:         $udom = $1;
 4354:         $unum = $2;
 4355:         $group = $3;
 4356:         $file_name = $3.'/'.$4;
 4357:     }
 4358:     if (wantarray) {
 4359: 	return ($type,$udom,$unum,$file_name,$group);
 4360:     }
 4361:     return $type;
 4362: }
 4363: 
 4364: sub is_portfolio_url {
 4365:     my ($url) = @_;
 4366:     return scalar(&parse_portfolio_url($url));
 4367: }
 4368: 
 4369: sub is_portfolio_file {
 4370:     my ($file) = @_;
 4371:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4372:         return 1;
 4373:     }
 4374:     return;
 4375: }
 4376: 
 4377: sub usertools_access {
 4378:     my ($uname,$udom,$tool) = @_;
 4379:     my $access;
 4380:     my %tools = (
 4381:                   aboutme   => 1,
 4382:                   blog      => 1,
 4383:                   portfolio => 1,
 4384:                 );
 4385:     return if (!defined($tools{$tool}));
 4386: 
 4387:     if ((!defined($udom)) || (!defined($uname))) {
 4388:         $udom = $env{'user.domain'};
 4389:         $uname = $env{'user.name'};
 4390:     }
 4391: 
 4392:     my $hashid=$uname.':'.$udom;
 4393:     my ($result,$cached) = &is_cached_new('usertools.'.$tool,$hashid);
 4394:     if (defined($cached)) {
 4395:         return $result;
 4396:     }
 4397: 
 4398:     my ($toolstatus,$inststatus);
 4399: 
 4400:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4401:         $toolstatus = $env{'environment.tools.'.$tool};
 4402:         $inststatus = $env{'environment.inststatus'};
 4403:     } else {
 4404:         my %userenv = &userenvironment($udom,$uname,'tools.'.$tool);
 4405:         $toolstatus = $userenv{'tools.'.$tool};
 4406:         $inststatus = $userenv{'inststatus'};
 4407:     }
 4408: 
 4409:     if ($toolstatus ne '') {
 4410:         if ($toolstatus) {
 4411:             $access = 1;
 4412:         } else {
 4413:             $access = 0;
 4414:         }
 4415:         &do_cache_new('usertools.'.$tool,$hashid,$access,600);
 4416:         return $access;
 4417:     }
 4418: 
 4419:     my $is_adv = &is_advanced_user($udom,$uname);
 4420:     my %domdef = &get_domain_defaults($udom);
 4421:     if (ref($domdef{$tool}) eq 'HASH') {
 4422:         if ($is_adv) {
 4423:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 4424:                 if ($domdef{$tool}{'_LC_adv'}) { 
 4425:                     $access = 1;
 4426:                 } else {
 4427:                     $access = 0;
 4428:                 }
 4429:                 &do_cache_new('usertools.'.$tool,$hashid,$access,600);
 4430:                 return $access;
 4431:             }
 4432:         }
 4433:         if ($inststatus ne '') {
 4434:             my ($hasaccess,$hasnoaccess);
 4435:             foreach my $affiliation (split(/:/,$inststatus)) {
 4436:                 if ($domdef{$tool}{$affiliation} ne '') { 
 4437:                     if ($domdef{$tool}{$affiliation}) {
 4438:                         $hasaccess = 1;
 4439:                     } else {
 4440:                         $hasnoaccess = 1;
 4441:                     }
 4442:                 }
 4443:             }
 4444:             if ($hasaccess || $hasnoaccess) {
 4445:                 if ($hasaccess) {
 4446:                     $access = 1;
 4447:                 } elsif ($hasnoaccess) {
 4448:                     $access = 0; 
 4449:                 }
 4450:                 &do_cache_new('usertools.'.$tool,$hashid,$access,600);
 4451:                 return $access;
 4452:             }
 4453:         } else {
 4454:             if ($domdef{$tool}{'default'} ne '') {
 4455:                 if ($domdef{$tool}{'default'}) {
 4456:                     $access = 1;
 4457:                 } elsif ($domdef{$tool}{'default'} == 0) {
 4458:                     $access = 0;
 4459:                 }
 4460:                 &do_cache_new('usertools.'.$tool,$hashid,$access,600);
 4461:                 return $access;
 4462:             }
 4463:         }
 4464:     } else {
 4465:         $access = 1;
 4466:         &do_cache_new('usertools.'.$tool,$hashid,$access,600);
 4467:         return $access;
 4468:     }
 4469: }
 4470: 
 4471: sub is_advanced_user {
 4472:     my ($udom,$uname) = @_;
 4473:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 4474:     my %allroles;
 4475:     my $is_adv;
 4476:     foreach my $role (keys(%roleshash)) {
 4477:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 4478:         my $area = '/'.$tdomain.'/'.$trest;
 4479:         if ($sec ne '') {
 4480:             $area .= '/'.$sec;
 4481:         }
 4482:         if (($area ne '') && ($trole ne '')) {
 4483:             my $spec=$trole.'.'.$area;
 4484:             if ($trole =~ /^cr\//) {
 4485:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4486:             } elsif ($trole ne 'gr') {
 4487:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4488:             }
 4489:         }
 4490:     }
 4491:     foreach my $role (keys(%allroles)) {
 4492:         last if ($is_adv);
 4493:         foreach my $item (split(/:/,$allroles{$role})) {
 4494:             if ($item ne '') {
 4495:                 my ($privilege,$restrictions)=split(/&/,$item);
 4496:                 if ($privilege eq 'adv') {
 4497:                     $is_adv = 1;
 4498:                     last;
 4499:                 }
 4500:             }
 4501:         }
 4502:     }
 4503:     return $is_adv;
 4504: }
 4505: 
 4506: # ---------------------------------------------- Custom access rule evaluation
 4507: 
 4508: sub customaccess {
 4509:     my ($priv,$uri)=@_;
 4510:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4511:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4512:     $udom = &LONCAPA::clean_domain($udom);
 4513:     $ucrs = &LONCAPA::clean_username($ucrs);
 4514:     my $access=0;
 4515:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4516: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4517: 	if ($type eq 'user') {
 4518: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4519: 		my ($tdom,$tuname)=split(m{/},$scope);
 4520: 		if ($tdom) {
 4521: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4522: 		}
 4523: 		if ($tuname) {
 4524: 		    if ($tuname ne $env{'user.name'}) { next; }
 4525: 		}
 4526: 		$access=($effect eq 'allow');
 4527: 		last;
 4528: 	    }
 4529: 	} else {
 4530: 	    if ($role) {
 4531: 		if ($role ne $urole) { next; }
 4532: 	    }
 4533: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4534: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4535: 		if ($tdom) {
 4536: 		    if ($tdom ne $udom) { next; }
 4537: 		}
 4538: 		if ($tcrs) {
 4539: 		    if ($tcrs ne $ucrs) { next; }
 4540: 		}
 4541: 		if ($tsec) {
 4542: 		    if ($tsec ne $usec) { next; }
 4543: 		}
 4544: 		$access=($effect eq 'allow');
 4545: 		last;
 4546: 	    }
 4547: 	    if ($realm eq '' && $role eq '') {
 4548: 		$access=($effect eq 'allow');
 4549: 	    }
 4550: 	}
 4551:     }
 4552:     return $access;
 4553: }
 4554: 
 4555: # ------------------------------------------------- Check for a user privilege
 4556: 
 4557: sub allowed {
 4558:     my ($priv,$uri,$symb,$role)=@_;
 4559:     my $ver_orguri=$uri;
 4560:     $uri=&deversion($uri);
 4561:     my $orguri=$uri;
 4562:     $uri=&declutter($uri);
 4563: 
 4564:     if ($priv eq 'evb') {
 4565: # Evade communication block restrictions for specified role in a course
 4566:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4567:             return $1;
 4568:         } else {
 4569:             return;
 4570:         }
 4571:     }
 4572: 
 4573:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4574: # Free bre access to adm and meta resources
 4575:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4576: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4577: 	&& ($priv eq 'bre')) {
 4578: 	return 'F';
 4579:     }
 4580: 
 4581: # Free bre access to user's own portfolio contents
 4582:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4583:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4584: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4585:         my %setters;
 4586:         my ($startblock,$endblock) = 
 4587:             &Apache::loncommon::blockcheck(\%setters,'port');
 4588:         if ($startblock && $endblock) {
 4589:             return 'B';
 4590:         } else {
 4591:             return 'F';
 4592:         }
 4593:     }
 4594: 
 4595: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4596:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4597:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4598:         if (exists($env{'request.course.id'})) {
 4599:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4600:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4601:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4602:                 my $courseprivid=$env{'request.course.id'};
 4603:                 $courseprivid=~s/\_/\//;
 4604:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4605:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4606:                     return $1; 
 4607:                 } else {
 4608:                     if ($env{'request.course.sec'}) {
 4609:                         $courseprivid.='/'.$env{'request.course.sec'};
 4610:                     }
 4611:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4612:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4613:                         return $2;
 4614:                     }
 4615:                 }
 4616:             }
 4617:         }
 4618:     }
 4619: 
 4620: # Free bre to public access
 4621: 
 4622:     if ($priv eq 'bre') {
 4623:         my $copyright=&metadata($uri,'copyright');
 4624: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4625:            return 'F'; 
 4626:         }
 4627:         if ($copyright eq 'priv') {
 4628:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4629: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4630: 		return '';
 4631:             }
 4632:         }
 4633:         if ($copyright eq 'domain') {
 4634:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4635: 	    unless (($env{'user.domain'} eq $1) ||
 4636:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4637: 		return '';
 4638:             }
 4639:         }
 4640:         if ($env{'request.role'}=~ /li\.\//) {
 4641:             # Library role, so allow browsing of resources in this domain.
 4642:             return 'F';
 4643:         }
 4644:         if ($copyright eq 'custom') {
 4645: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4646:         }
 4647:     }
 4648:     # Domain coordinator is trying to create a course
 4649:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4650:         # uri is the requested domain in this case.
 4651:         # comparison to 'request.role.domain' shows if the user has selected
 4652:         # a role of dc for the domain in question.
 4653:         return 'F' if ($uri eq $env{'request.role.domain'});
 4654:     }
 4655: 
 4656:     my $thisallowed='';
 4657:     my $statecond=0;
 4658:     my $courseprivid='';
 4659: 
 4660: # Course
 4661: 
 4662:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4663:        $thisallowed.=$1;
 4664:     }
 4665: 
 4666: # Domain
 4667: 
 4668:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4669:        =~/\Q$priv\E\&([^\:]*)/) {
 4670:        $thisallowed.=$1;
 4671:     }
 4672: 
 4673: # Course: uri itself is a course
 4674:     my $courseuri=$uri;
 4675:     $courseuri=~s/\_(\d)/\/$1/;
 4676:     $courseuri=~s/^([^\/])/\/$1/;
 4677: 
 4678:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 4679:        =~/\Q$priv\E\&([^\:]*)/) {
 4680:        $thisallowed.=$1;
 4681:     }
 4682: 
 4683: # URI is an uploaded document for this course, default permissions don't matter
 4684: # not allowing 'edit' access (editupload) to uploaded course docs
 4685:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 4686: 	$thisallowed='';
 4687:         my ($match)=&is_on_map($uri);
 4688:         if ($match) {
 4689:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 4690:                   =~/\Q$priv\E\&([^\:]*)/) {
 4691:                 $thisallowed.=$1;
 4692:             }
 4693:         } else {
 4694:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 4695:             if ($refuri) {
 4696:                 if ($refuri =~ m|^/adm/|) {
 4697:                     $thisallowed='F';
 4698:                 } else {
 4699:                     $refuri=&declutter($refuri);
 4700:                     my ($match) = &is_on_map($refuri);
 4701:                     if ($match) {
 4702:                         $thisallowed='F';
 4703:                     }
 4704:                 }
 4705:             }
 4706:         }
 4707:     }
 4708: 
 4709:     if ($priv eq 'bre'
 4710: 	&& $thisallowed ne 'F' 
 4711: 	&& $thisallowed ne '2'
 4712: 	&& &is_portfolio_url($uri)) {
 4713: 	$thisallowed = &portfolio_access($uri);
 4714:     }
 4715:     
 4716: # Full access at system, domain or course-wide level? Exit.
 4717:     if ($thisallowed=~/F/) {
 4718: 	return 'F';
 4719:     }
 4720: 
 4721: # If this is generating or modifying users, exit with special codes
 4722: 
 4723:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4724: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4725: 	    my ($audom,$auname)=split('/',$uri);
 4726: # no author name given, so this just checks on the general right to make a co-author in this domain
 4727: 	    unless ($auname) { return $thisallowed; }
 4728: # an author name is given, so we are about to actually make a co-author for a certain account
 4729: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4730: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 4731: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 4732: 	}
 4733: 	return $thisallowed;
 4734:     }
 4735: #
 4736: # Gathered so far: system, domain and course wide privileges
 4737: #
 4738: # Course: See if uri or referer is an individual resource that is part of 
 4739: # the course
 4740: 
 4741:     if ($env{'request.course.id'}) {
 4742: 
 4743:        $courseprivid=$env{'request.course.id'};
 4744:        if ($env{'request.course.sec'}) {
 4745:           $courseprivid.='/'.$env{'request.course.sec'};
 4746:        }
 4747:        $courseprivid=~s/\_/\//;
 4748:        my $checkreferer=1;
 4749:        my ($match,$cond)=&is_on_map($uri);
 4750:        if ($match) {
 4751:            $statecond=$cond;
 4752:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4753:                =~/\Q$priv\E\&([^\:]*)/) {
 4754:                $thisallowed.=$1;
 4755:                $checkreferer=0;
 4756:            }
 4757:        }
 4758:        
 4759:        if ($checkreferer) {
 4760: 	  my $refuri=$env{'httpref.'.$orguri};
 4761:             unless ($refuri) {
 4762:                 foreach my $key (keys(%env)) {
 4763: 		    if ($key=~/^httpref\..*\*/) {
 4764: 			my $pattern=$key;
 4765:                         $pattern=~s/^httpref\.\/res\///;
 4766:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4767:                         $pattern=~s/\//\\\//g;
 4768:                         if ($orguri=~/$pattern/) {
 4769: 			    $refuri=$env{$key};
 4770:                         }
 4771:                     }
 4772:                 }
 4773:             }
 4774: 
 4775:          if ($refuri) { 
 4776: 	  $refuri=&declutter($refuri);
 4777:           my ($match,$cond)=&is_on_map($refuri);
 4778:             if ($match) {
 4779:               my $refstatecond=$cond;
 4780:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4781:                   =~/\Q$priv\E\&([^\:]*)/) {
 4782:                   $thisallowed.=$1;
 4783:                   $uri=$refuri;
 4784:                   $statecond=$refstatecond;
 4785:               }
 4786:           }
 4787:         }
 4788:        }
 4789:    }
 4790: 
 4791: #
 4792: # Gathered now: all privileges that could apply, and condition number
 4793: # 
 4794: #
 4795: # Full or no access?
 4796: #
 4797: 
 4798:     if ($thisallowed=~/F/) {
 4799: 	return 'F';
 4800:     }
 4801: 
 4802:     unless ($thisallowed) {
 4803:         return '';
 4804:     }
 4805: 
 4806: # Restrictions exist, deal with them
 4807: #
 4808: #   C:according to course preferences
 4809: #   R:according to resource settings
 4810: #   L:unless locked
 4811: #   X:according to user session state
 4812: #
 4813: 
 4814: # Possibly locked functionality, check all courses
 4815: # Locks might take effect only after 10 minutes cache expiration for other
 4816: # courses, and 2 minutes for current course
 4817: 
 4818:     my $envkey;
 4819:     if ($thisallowed=~/L/) {
 4820:         foreach $envkey (keys %env) {
 4821:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 4822:                my $courseid=$2;
 4823:                my $roleid=$1.'.'.$2;
 4824:                $courseid=~s/^\///;
 4825:                my $expiretime=600;
 4826:                if ($env{'request.role'} eq $roleid) {
 4827: 		  $expiretime=120;
 4828:                }
 4829: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 4830:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 4831:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 4832: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 4833:                }
 4834:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4835:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4836: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4837:                        &log($env{'user.domain'},$env{'user.name'},
 4838:                             $env{'user.home'},
 4839:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4840:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4841:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4842: 		       return '';
 4843:                    }
 4844:                }
 4845:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4846:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4847: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4848:                        &log($env{'user.domain'},$env{'user.name'},
 4849:                             $env{'user.home'},
 4850:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4851:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4852:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4853: 		       return '';
 4854:                    }
 4855:                }
 4856: 	   }
 4857:        }
 4858:     }
 4859:    
 4860: #
 4861: # Rest of the restrictions depend on selected course
 4862: #
 4863: 
 4864:     unless ($env{'request.course.id'}) {
 4865: 	if ($thisallowed eq 'A') {
 4866: 	    return 'A';
 4867:         } elsif ($thisallowed eq 'B') {
 4868:             return 'B';
 4869: 	} else {
 4870: 	    return '1';
 4871: 	}
 4872:     }
 4873: 
 4874: #
 4875: # Now user is definitely in a course
 4876: #
 4877: 
 4878: 
 4879: # Course preferences
 4880: 
 4881:    if ($thisallowed=~/C/) {
 4882:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4883:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4884:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4885: 	   =~/\Q$rolecode\E/) {
 4886: 	   if ($priv ne 'pch') { 
 4887: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4888: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4889: 			$env{'request.course.id'});
 4890: 	   }
 4891:            return '';
 4892:        }
 4893: 
 4894:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4895: 	   =~/\Q$unamedom\E/) {
 4896: 	   if ($priv ne 'pch') { 
 4897: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4898: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4899: 			$env{'request.course.id'});
 4900: 	   }
 4901:            return '';
 4902:        }
 4903:    }
 4904: 
 4905: # Resource preferences
 4906: 
 4907:    if ($thisallowed=~/R/) {
 4908:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4909:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4910: 	   if ($priv ne 'pch') { 
 4911: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4912: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4913: 	   }
 4914: 	   return '';
 4915:        }
 4916:    }
 4917: 
 4918: # Restricted by state or randomout?
 4919: 
 4920:    if ($thisallowed=~/X/) {
 4921:       if ($env{'acc.randomout'}) {
 4922: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4923:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4924:             return ''; 
 4925:          }
 4926:       }
 4927:       if (&condval($statecond)) {
 4928: 	 return '2';
 4929:       } else {
 4930:          return '';
 4931:       }
 4932:    }
 4933: 
 4934:     if ($thisallowed eq 'A') {
 4935: 	return 'A';
 4936:     } elsif ($thisallowed eq 'B') {
 4937:         return 'B';
 4938:     }
 4939:    return 'F';
 4940: }
 4941: 
 4942: sub split_uri_for_cond {
 4943:     my $uri=&deversion(&declutter(shift));
 4944:     my @uriparts=split(/\//,$uri);
 4945:     my $filename=pop(@uriparts);
 4946:     my $pathname=join('/',@uriparts);
 4947:     return ($pathname,$filename);
 4948: }
 4949: # --------------------------------------------------- Is a resource on the map?
 4950: 
 4951: sub is_on_map {
 4952:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 4953:     #Trying to find the conditional for the file
 4954:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 4955: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 4956:     if ($match) {
 4957: 	return (1,$1);
 4958:     } else {
 4959: 	return (0,0);
 4960:     }
 4961: }
 4962: 
 4963: # --------------------------------------------------------- Get symb from alias
 4964: 
 4965: sub get_symb_from_alias {
 4966:     my $symb=shift;
 4967:     my ($map,$resid,$url)=&decode_symb($symb);
 4968: # Already is a symb
 4969:     if ($url) { return $symb; }
 4970: # Must be an alias
 4971:     my $aliassymb='';
 4972:     my %bighash;
 4973:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 4974:                             &GDBM_READER(),0640)) {
 4975:         my $rid=$bighash{'mapalias_'.$symb};
 4976: 	if ($rid) {
 4977: 	    my ($mapid,$resid)=split(/\./,$rid);
 4978: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 4979: 				    $resid,$bighash{'src_'.$rid});
 4980: 	}
 4981:         untie %bighash;
 4982:     }
 4983:     return $aliassymb;
 4984: }
 4985: 
 4986: # ----------------------------------------------------------------- Define Role
 4987: 
 4988: sub definerole {
 4989:   if (allowed('mcr','/')) {
 4990:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 4991:     foreach my $role (split(':',$sysrole)) {
 4992: 	my ($crole,$cqual)=split(/\&/,$role);
 4993:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 4994:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 4995: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4996:                return "refused:s:$crole&$cqual"; 
 4997:             }
 4998:         }
 4999:     }
 5000:     foreach my $role (split(':',$domrole)) {
 5001: 	my ($crole,$cqual)=split(/\&/,$role);
 5002:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 5003:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 5004: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 5005:                return "refused:d:$crole&$cqual"; 
 5006:             }
 5007:         }
 5008:     }
 5009:     foreach my $role (split(':',$courole)) {
 5010: 	my ($crole,$cqual)=split(/\&/,$role);
 5011:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 5012:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 5013: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5014:                return "refused:c:$crole&$cqual"; 
 5015:             }
 5016:         }
 5017:     }
 5018:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5019:                 "$env{'user.domain'}:$env{'user.name'}:".
 5020: 	        "rolesdef_$rolename=".
 5021:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 5022:     return reply($command,$env{'user.home'});
 5023:   } else {
 5024:     return 'refused';
 5025:   }
 5026: }
 5027: 
 5028: # ---------------- Make a metadata query against the network of library servers
 5029: 
 5030: sub metadata_query {
 5031:     my ($query,$custom,$customshow,$server_array)=@_;
 5032:     my %rhash;
 5033:     my %libserv = &all_library();
 5034:     my @server_list = (defined($server_array) ? @$server_array
 5035:                                               : keys(%libserv) );
 5036:     for my $server (@server_list) {
 5037: 	unless ($custom or $customshow) {
 5038: 	    my $reply=&reply("querysend:".&escape($query),$server);
 5039: 	    $rhash{$server}=$reply;
 5040: 	}
 5041: 	else {
 5042: 	    my $reply=&reply("querysend:".&escape($query).':'.
 5043: 			     &escape($custom).':'.&escape($customshow),
 5044: 			     $server);
 5045: 	    $rhash{$server}=$reply;
 5046: 	}
 5047:     }
 5048:     return \%rhash;
 5049: }
 5050: 
 5051: # ----------------------------------------- Send log queries and wait for reply
 5052: 
 5053: sub log_query {
 5054:     my ($uname,$udom,$query,%filters)=@_;
 5055:     my $uhome=&homeserver($uname,$udom);
 5056:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 5057:     my $uhost=&hostname($uhome);
 5058:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 5059:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 5060:                        $uhome);
 5061:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 5062:     return get_query_reply($queryid);
 5063: }
 5064: 
 5065: # -------------------------- Update MySQL table for portfolio file
 5066: 
 5067: sub update_portfolio_table {
 5068:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 5069:     if ($group ne '') {
 5070:         $file_name =~s /^\Q$group\E//;
 5071:     }
 5072:     my $homeserver = &homeserver($uname,$udom);
 5073:     my $queryid=
 5074:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 5075:                ':'.&escape($file_name).':'.$action,$homeserver);
 5076:     my $reply = &get_query_reply($queryid);
 5077:     return $reply;
 5078: }
 5079: 
 5080: # -------------------------- Update MySQL allusers table
 5081: 
 5082: sub update_allusers_table {
 5083:     my ($uname,$udom,$names) = @_;
 5084:     my $homeserver = &homeserver($uname,$udom);
 5085:     my $queryid=
 5086:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 5087:                'lastname='.&escape($names->{'lastname'}).'%%'.
 5088:                'firstname='.&escape($names->{'firstname'}).'%%'.
 5089:                'middlename='.&escape($names->{'middlename'}).'%%'.
 5090:                'generation='.&escape($names->{'generation'}).'%%'.
 5091:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 5092:                'id='.&escape($names->{'id'}),$homeserver);
 5093:     my $reply = &get_query_reply($queryid);
 5094:     return $reply;
 5095: }
 5096: 
 5097: # ------- Request retrieval of institutional classlists for course(s)
 5098: 
 5099: sub fetch_enrollment_query {
 5100:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 5101:     my $homeserver;
 5102:     my $maxtries = 1;
 5103:     if ($context eq 'automated') {
 5104:         $homeserver = $perlvar{'lonHostID'};
 5105:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 5106:     } else {
 5107:         $homeserver = &homeserver($cnum,$dom);
 5108:     }
 5109:     my $host=&hostname($homeserver);
 5110:     my $cmd = '';
 5111:     foreach my $affiliate (keys %{$affiliatesref}) {
 5112:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5113:     }
 5114:     $cmd =~ s/%%$//;
 5115:     $cmd = &escape($cmd);
 5116:     my $query = 'fetchenrollment';
 5117:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 5118:     unless ($queryid=~/^\Q$host\E\_/) { 
 5119:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 5120:         return 'error: '.$queryid;
 5121:     }
 5122:     my $reply = &get_query_reply($queryid);
 5123:     my $tries = 1;
 5124:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5125:         $reply = &get_query_reply($queryid);
 5126:         $tries ++;
 5127:     }
 5128:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5129:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5130:     } else {
 5131:         my @responses = split(/:/,$reply);
 5132:         if ($homeserver eq $perlvar{'lonHostID'}) {
 5133:             foreach my $line (@responses) {
 5134:                 my ($key,$value) = split(/=/,$line,2);
 5135:                 $$replyref{$key} = $value;
 5136:             }
 5137:         } else {
 5138:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 5139:             foreach my $line (@responses) {
 5140:                 my ($key,$value) = split(/=/,$line);
 5141:                 $$replyref{$key} = $value;
 5142:                 if ($value > 0) {
 5143:                     foreach my $item (@{$$affiliatesref{$key}}) {
 5144:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 5145:                         my $destname = $pathname.'/'.$filename;
 5146:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 5147:                         if ($xml_classlist =~ /^error/) {
 5148:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 5149:                         } else {
 5150:                             if ( open(FILE,">$destname") ) {
 5151:                                 print FILE &unescape($xml_classlist);
 5152:                                 close(FILE);
 5153:                             } else {
 5154:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 5155:                             }
 5156:                         }
 5157:                     }
 5158:                 }
 5159:             }
 5160:         }
 5161:         return 'ok';
 5162:     }
 5163:     return 'error';
 5164: }
 5165: 
 5166: sub get_query_reply {
 5167:     my $queryid=shift;
 5168:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 5169:     my $reply='';
 5170:     for (1..100) {
 5171: 	sleep 2;
 5172:         if (-e $replyfile.'.end') {
 5173: 	    if (open(my $fh,$replyfile)) {
 5174: 		$reply = join('',<$fh>);
 5175: 		close($fh);
 5176: 	   } else { return 'error: reply_file_error'; }
 5177:            return &unescape($reply);
 5178: 	}
 5179:     }
 5180:     return 'timeout:'.$queryid;
 5181: }
 5182: 
 5183: sub courselog_query {
 5184: #
 5185: # possible filters:
 5186: # url: url or symb
 5187: # username
 5188: # domain
 5189: # action: view, submit, grade
 5190: # start: timestamp
 5191: # end: timestamp
 5192: #
 5193:     my (%filters)=@_;
 5194:     unless ($env{'request.course.id'}) { return 'no_course'; }
 5195:     if ($filters{'url'}) {
 5196: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 5197:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 5198:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 5199:     }
 5200:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5201:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5202:     return &log_query($cname,$cdom,'courselog',%filters);
 5203: }
 5204: 
 5205: sub userlog_query {
 5206: #
 5207: # possible filters:
 5208: # action: log check role
 5209: # start: timestamp
 5210: # end: timestamp
 5211: #
 5212:     my ($uname,$udom,%filters)=@_;
 5213:     return &log_query($uname,$udom,'userlog',%filters);
 5214: }
 5215: 
 5216: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 5217: 
 5218: sub auto_run {
 5219:     my ($cnum,$cdom) = @_;
 5220:     my $response = 0;
 5221:     my $settings;
 5222:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 5223:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5224:         $settings = $domconfig{'autoenroll'};
 5225:         if ($settings->{'run'} eq '1') {
 5226:             $response = 1;
 5227:         }
 5228:     } else {
 5229:         my $homeserver;
 5230:         if (&is_course($cdom,$cnum)) {
 5231:             $homeserver = &homeserver($cnum,$cdom);
 5232:         } else {
 5233:             $homeserver = &domain($cdom,'primary');
 5234:         }
 5235:         if ($homeserver ne 'no_host') {
 5236:             $response = &reply('autorun:'.$cdom,$homeserver);
 5237:         }
 5238:     }
 5239:     return $response;
 5240: }
 5241: 
 5242: sub auto_get_sections {
 5243:     my ($cnum,$cdom,$inst_coursecode) = @_;
 5244:     my $homeserver = &homeserver($cnum,$cdom);
 5245:     my @secs = ();
 5246:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 5247:     unless ($response eq 'refused') {
 5248:         @secs = split(/:/,$response);
 5249:     }
 5250:     return @secs;
 5251: }
 5252: 
 5253: sub auto_new_course {
 5254:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 5255:     my $homeserver = &homeserver($cnum,$cdom);
 5256:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 5257:     return $response;
 5258: }
 5259: 
 5260: sub auto_validate_courseID {
 5261:     my ($cnum,$cdom,$inst_course_id) = @_;
 5262:     my $homeserver = &homeserver($cnum,$cdom);
 5263:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5264:     return $response;
 5265: }
 5266: 
 5267: sub auto_create_password {
 5268:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5269:     my ($homeserver,$response);
 5270:     my $create_passwd = 0;
 5271:     my $authchk = '';
 5272:     if ($udom =~ /^$match_domain$/) {
 5273:         $homeserver = &domain($udom,'primary');
 5274:     }
 5275:     if ($homeserver eq '') {
 5276:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5277:             $homeserver = &homeserver($cnum,$cdom);
 5278:         }
 5279:     }
 5280:     if ($homeserver eq '') {
 5281:         $authchk = 'nodomain';
 5282:     } else {
 5283:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5284:         if ($response eq 'refused') {
 5285:             $authchk = 'refused';
 5286:         } else {
 5287:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5288:         }
 5289:     }
 5290:     return ($authparam,$create_passwd,$authchk);
 5291: }
 5292: 
 5293: sub auto_photo_permission {
 5294:     my ($cnum,$cdom,$students) = @_;
 5295:     my $homeserver = &homeserver($cnum,$cdom);
 5296:     my ($outcome,$perm_reqd,$conditions) = 
 5297: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5298:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5299: 	return (undef,undef);
 5300:     }
 5301:     return ($outcome,$perm_reqd,$conditions);
 5302: }
 5303: 
 5304: sub auto_checkphotos {
 5305:     my ($uname,$udom,$pid) = @_;
 5306:     my $homeserver = &homeserver($uname,$udom);
 5307:     my ($result,$resulttype);
 5308:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5309: 				   &escape($uname).':'.&escape($pid),
 5310: 				   $homeserver));
 5311:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5312: 	return (undef,undef);
 5313:     }
 5314:     if ($outcome) {
 5315:         ($result,$resulttype) = split(/:/,$outcome);
 5316:     } 
 5317:     return ($result,$resulttype);
 5318: }
 5319: 
 5320: sub auto_photochoice {
 5321:     my ($cnum,$cdom) = @_;
 5322:     my $homeserver = &homeserver($cnum,$cdom);
 5323:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5324: 						       &escape($cdom),
 5325: 						       $homeserver)));
 5326:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5327: 	return (undef,undef);
 5328:     }
 5329:     return ($update,$comment);
 5330: }
 5331: 
 5332: sub auto_photoupdate {
 5333:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5334:     my $homeserver = &homeserver($cnum,$dom);
 5335:     my $host=&hostname($homeserver);
 5336:     my $cmd = '';
 5337:     my $maxtries = 1;
 5338:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5339:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5340:     }
 5341:     $cmd =~ s/%%$//;
 5342:     $cmd = &escape($cmd);
 5343:     my $query = 'institutionalphotos';
 5344:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5345:     unless ($queryid=~/^\Q$host\E\_/) {
 5346:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5347:         return 'error: '.$queryid;
 5348:     }
 5349:     my $reply = &get_query_reply($queryid);
 5350:     my $tries = 1;
 5351:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5352:         $reply = &get_query_reply($queryid);
 5353:         $tries ++;
 5354:     }
 5355:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5356:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5357:     } else {
 5358:         my @responses = split(/:/,$reply);
 5359:         my $outcome = shift(@responses); 
 5360:         foreach my $item (@responses) {
 5361:             my ($key,$value) = split(/=/,$item);
 5362:             $$photo{$key} = $value;
 5363:         }
 5364:         return $outcome;
 5365:     }
 5366:     return 'error';
 5367: }
 5368: 
 5369: sub auto_instcode_format {
 5370:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5371: 	$cat_order) = @_;
 5372:     my $courses = '';
 5373:     my @homeservers;
 5374:     if ($caller eq 'global') {
 5375: 	my %servers = &get_servers($codedom,'library');
 5376: 	foreach my $tryserver (keys(%servers)) {
 5377: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5378: 		push(@homeservers,$tryserver);
 5379: 	    }
 5380:         }
 5381:     } else {
 5382:         push(@homeservers,&homeserver($caller,$codedom));
 5383:     }
 5384:     foreach my $code (keys(%{$instcodes})) {
 5385:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5386:     }
 5387:     chop($courses);
 5388:     my $ok_response = 0;
 5389:     my $response;
 5390:     while (@homeservers > 0 && $ok_response == 0) {
 5391:         my $server = shift(@homeservers); 
 5392:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5393:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5394:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5395: 		split(/:/,$response);
 5396:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5397:             push(@{$codetitles},&str2array($codetitles_str));
 5398:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5399:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5400:             $ok_response = 1;
 5401:         }
 5402:     }
 5403:     if ($ok_response) {
 5404:         return 'ok';
 5405:     } else {
 5406:         return $response;
 5407:     }
 5408: }
 5409: 
 5410: sub auto_instcode_defaults {
 5411:     my ($domain,$returnhash,$code_order) = @_;
 5412:     my @homeservers;
 5413: 
 5414:     my %servers = &get_servers($domain,'library');
 5415:     foreach my $tryserver (keys(%servers)) {
 5416: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5417: 	    push(@homeservers,$tryserver);
 5418: 	}
 5419:     }
 5420: 
 5421:     my $response;
 5422:     foreach my $server (@homeservers) {
 5423:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5424:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5425: 	
 5426: 	foreach my $pair (split(/\&/,$response)) {
 5427: 	    my ($name,$value)=split(/\=/,$pair);
 5428: 	    if ($name eq 'code_order') {
 5429: 		@{$code_order} = split(/\&/,&unescape($value));
 5430: 	    } else {
 5431: 		$returnhash->{&unescape($name)}=&unescape($value);
 5432: 	    }
 5433: 	}
 5434: 	return 'ok';
 5435:     }
 5436: 
 5437:     return $response;
 5438: } 
 5439: 
 5440: sub auto_validate_class_sec {
 5441:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5442:     my $homeserver = &homeserver($cnum,$cdom);
 5443:     my $ownerlist;
 5444:     if (ref($owners) eq 'ARRAY') {
 5445:         $ownerlist = join(',',@{$owners});
 5446:     } else {
 5447:         $ownerlist = $owners;
 5448:     }
 5449:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 5450:                         &escape($ownerlist).':'.$cdom,$homeserver);
 5451:     return $response;
 5452: }
 5453: 
 5454: # ------------------------------------------------------- Course Group routines
 5455: 
 5456: sub get_coursegroups {
 5457:     my ($cdom,$cnum,$group,$namespace) = @_;
 5458:     return(&dump($namespace,$cdom,$cnum,$group));
 5459: }
 5460: 
 5461: sub modify_coursegroup {
 5462:     my ($cdom,$cnum,$groupsettings) = @_;
 5463:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 5464: }
 5465: 
 5466: sub toggle_coursegroup_status {
 5467:     my ($cdom,$cnum,$group,$action) = @_;
 5468:     my ($from_namespace,$to_namespace);
 5469:     if ($action eq 'delete') {
 5470:         $from_namespace = 'coursegroups';
 5471:         $to_namespace = 'deleted_groups';
 5472:     } else {
 5473:         $from_namespace = 'deleted_groups';
 5474:         $to_namespace = 'coursegroups';
 5475:     }
 5476:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 5477:     if (my $tmp = &error(%curr_group)) {
 5478:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 5479:         return ('read error',$tmp);
 5480:     } else {
 5481:         my %savedsettings = %curr_group; 
 5482:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 5483:         my $deloutcome;
 5484:         if ($result eq 'ok') {
 5485:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 5486:         } else {
 5487:             return ('write error',$result);
 5488:         }
 5489:         if ($deloutcome eq 'ok') {
 5490:             return 'ok';
 5491:         } else {
 5492:             return ('delete error',$deloutcome);
 5493:         }
 5494:     }
 5495: }
 5496: 
 5497: sub modify_group_roles {
 5498:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 5499:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 5500:     my $role = 'gr/'.&escape($userprivs);
 5501:     my ($uname,$udom) = split(/:/,$user);
 5502:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 5503:     if ($result eq 'ok') {
 5504:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 5505:     }
 5506:     return $result;
 5507: }
 5508: 
 5509: sub modify_coursegroup_membership {
 5510:     my ($cdom,$cnum,$membership) = @_;
 5511:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 5512:     return $result;
 5513: }
 5514: 
 5515: sub get_active_groups {
 5516:     my ($udom,$uname,$cdom,$cnum) = @_;
 5517:     my $now = time;
 5518:     my %groups = ();
 5519:     foreach my $key (keys(%env)) {
 5520:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 5521:             my ($start,$end) = split(/\./,$env{$key});
 5522:             if (($end!=0) && ($end<$now)) { next; }
 5523:             if (($start!=0) && ($start>$now)) { next; }
 5524:             if ($1 eq $cdom && $2 eq $cnum) {
 5525:                 $groups{$3} = $env{$key} ;
 5526:             }
 5527:         }
 5528:     }
 5529:     return %groups;
 5530: }
 5531: 
 5532: sub get_group_membership {
 5533:     my ($cdom,$cnum,$group) = @_;
 5534:     return(&dump('groupmembership',$cdom,$cnum,$group));
 5535: }
 5536: 
 5537: sub get_users_groups {
 5538:     my ($udom,$uname,$courseid) = @_;
 5539:     my @usersgroups;
 5540:     my $cachetime=1800;
 5541: 
 5542:     my $hashid="$udom:$uname:$courseid";
 5543:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 5544:     if (defined($cached)) {
 5545:         @usersgroups = split(/:/,$grouplist);
 5546:     } else {  
 5547:         $grouplist = '';
 5548:         my $courseurl = &courseid_to_courseurl($courseid);
 5549:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 5550:         my $access_end = $env{'course.'.$courseid.
 5551:                               '.default_enrollment_end_date'};
 5552:         my $now = time;
 5553:         foreach my $key (keys(%roleshash)) {
 5554:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 5555:                 my $group = $1;
 5556:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 5557:                     my $start = $2;
 5558:                     my $end = $1;
 5559:                     if ($start == -1) { next; } # deleted from group
 5560:                     if (($start!=0) && ($start>$now)) { next; }
 5561:                     if (($end!=0) && ($end<$now)) {
 5562:                         if ($access_end && $access_end < $now) {
 5563:                             if ($access_end - $end < 86400) {
 5564:                                 push(@usersgroups,$group);
 5565:                             }
 5566:                         }
 5567:                         next;
 5568:                     }
 5569:                     push(@usersgroups,$group);
 5570:                 }
 5571:             }
 5572:         }
 5573:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 5574:         $grouplist = join(':',@usersgroups);
 5575:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 5576:     }
 5577:     return @usersgroups;
 5578: }
 5579: 
 5580: sub devalidate_getgroups_cache {
 5581:     my ($udom,$uname,$cdom,$cnum)=@_;
 5582:     my $courseid = $cdom.'_'.$cnum;
 5583: 
 5584:     my $hashid="$udom:$uname:$courseid";
 5585:     &devalidate_cache_new('getgroups',$hashid);
 5586: }
 5587: 
 5588: # ------------------------------------------------------------------ Plain Text
 5589: 
 5590: sub plaintext {
 5591:     my ($short,$type,$cid) = @_;
 5592:     if ($short =~ /^cr/) {
 5593: 	return (split('/',$short))[-1];
 5594:     }
 5595:     if (!defined($cid)) {
 5596:         $cid = $env{'request.course.id'};
 5597:     }
 5598:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 5599:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 5600:                                           '.plaintext'});
 5601:     }
 5602:     my %rolenames = (
 5603:                       Course => 'std',
 5604:                       Group => 'alt1',
 5605:                     );
 5606:     if (defined($type) && 
 5607:          defined($rolenames{$type}) && 
 5608:          defined($prp{$short}{$rolenames{$type}})) {
 5609:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 5610:     } else {
 5611:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 5612:     }
 5613: }
 5614: 
 5615: # ----------------------------------------------------------------- Assign Role
 5616: 
 5617: sub assignrole {
 5618:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 5619:         $context)=@_;
 5620:     my $mrole;
 5621:     if ($role =~ /^cr\//) {
 5622:         my $cwosec=$url;
 5623:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5624: 	unless (&allowed('ccr',$cwosec)) {
 5625:            &logthis('Refused custom assignrole: '.
 5626:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5627: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 5628:            return 'refused'; 
 5629:         }
 5630:         $mrole='cr';
 5631:     } elsif ($role =~ /^gr\//) {
 5632:         my $cwogrp=$url;
 5633:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 5634:         unless (&allowed('mdg',$cwogrp)) {
 5635:             &logthis('Refused group assignrole: '.
 5636:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5637:                     $env{'user.name'}.' at '.$env{'user.domain'});
 5638:             return 'refused';
 5639:         }
 5640:         $mrole='gr';
 5641:     } else {
 5642:         my $cwosec=$url;
 5643:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5644:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 5645:             my $refused;
 5646:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 5647:                 if (!(&allowed('c'.$role,$url))) {
 5648:                     $refused = 1;
 5649:                 }
 5650:             } else {
 5651:                 $refused = 1;
 5652:             }
 5653:             if ($refused) {
 5654:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5655:                     $refused = '';
 5656:                 } else {
 5657:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 5658:                              ' '.$role.' '.$end.' '.$start.' by '.
 5659: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 5660:                     return 'refused';
 5661:                 }
 5662:             }
 5663:         }
 5664:         $mrole=$role;
 5665:     }
 5666:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5667:                 "$udom:$uname:$url".'_'."$mrole=$role";
 5668:     if ($end) { $command.='_'.$end; }
 5669:     if ($start) {
 5670: 	if ($end) { 
 5671:            $command.='_'.$start; 
 5672:         } else {
 5673:            $command.='_0_'.$start;
 5674:         }
 5675:     }
 5676:     my $origstart = $start;
 5677:     my $origend = $end;
 5678:     my $delflag;
 5679: # actually delete
 5680:     if ($deleteflag) {
 5681: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 5682: # modify command to delete the role
 5683:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 5684:                 "$udom:$uname:$url".'_'."$mrole";
 5685: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 5686: # set start and finish to negative values for userrolelog
 5687:            $start=-1;
 5688:            $end=-1;
 5689:            $delflag = 1;
 5690:         }
 5691:     }
 5692: # send command
 5693:     my $answer=&reply($command,&homeserver($uname,$udom));
 5694: # log new user role if status is ok
 5695:     if ($answer eq 'ok') {
 5696: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 5697: # for course roles, perform group memberships changes triggered by role change.
 5698:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 5699:         unless ($role =~ /^gr/) {
 5700:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 5701:                                              $origstart,$selfenroll,$context);
 5702:         }
 5703:     }
 5704:     return $answer;
 5705: }
 5706: 
 5707: # -------------------------------------------------- Modify user authentication
 5708: # Overrides without validation
 5709: 
 5710: sub modifyuserauth {
 5711:     my ($udom,$uname,$umode,$upass)=@_;
 5712:     my $uhome=&homeserver($uname,$udom);
 5713:     unless (&allowed('mau',$udom)) { return 'refused'; }
 5714:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 5715:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5716:              ' in domain '.$env{'request.role.domain'});  
 5717:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 5718: 		     &escape($upass),$uhome);
 5719:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 5720:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 5721:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5722:     &log($udom,,$uname,$uhome,
 5723:         'Authentication changed by '.$env{'user.domain'}.', '.
 5724:                                      $env{'user.name'}.', '.$umode.
 5725:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5726:     unless ($reply eq 'ok') {
 5727:         &logthis('Authentication mode error: '.$reply);
 5728: 	return 'error: '.$reply;
 5729:     }   
 5730:     return 'ok';
 5731: }
 5732: 
 5733: # --------------------------------------------------------------- Modify a user
 5734: 
 5735: sub modifyuser {
 5736:     my ($udom,    $uname, $uid,
 5737:         $umode,   $upass, $first,
 5738:         $middle,  $last,  $gene,
 5739:         $forceid, $desiredhome, $email, $inststatus)=@_;
 5740:     $udom= &LONCAPA::clean_domain($udom);
 5741:     $uname=&LONCAPA::clean_username($uname);
 5742:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 5743:              $umode.', '.$first.', '.$middle.', '.
 5744: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 5745:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 5746:                                      ' desiredhome not specified'). 
 5747:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5748:              ' in domain '.$env{'request.role.domain'});
 5749:     my $uhome=&homeserver($uname,$udom,'true');
 5750: # ----------------------------------------------------------------- Create User
 5751:     if (($uhome eq 'no_host') && 
 5752: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 5753:         my $unhome='';
 5754:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 5755:             $unhome = $desiredhome;
 5756: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 5757: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 5758:         } else { # load balancing routine for determining $unhome
 5759:             my $loadm=10000000;
 5760: 	    my %servers = &get_servers($udom,'library');
 5761: 	    foreach my $tryserver (keys(%servers)) {
 5762: 		my $answer=reply('load',$tryserver);
 5763: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 5764: 		    $loadm=$answer;
 5765: 		    $unhome=$tryserver;
 5766: 		}
 5767: 	    }
 5768:         }
 5769:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 5770: 	    return 'error: unable to find a home server for '.$uname.
 5771:                    ' in domain '.$udom;
 5772:         }
 5773:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 5774:                          &escape($upass),$unhome);
 5775: 	unless ($reply eq 'ok') {
 5776:             return 'error: '.$reply;
 5777:         }   
 5778:         $uhome=&homeserver($uname,$udom,'true');
 5779:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 5780: 	    return 'error: unable verify users home machine.';
 5781:         }
 5782:     }   # End of creation of new user
 5783: # ---------------------------------------------------------------------- Add ID
 5784:     if ($uid) {
 5785:        $uid=~tr/A-Z/a-z/;
 5786:        my %uidhash=&idrget($udom,$uname);
 5787:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 5788:          && (!$forceid)) {
 5789: 	  unless ($uid eq $uidhash{$uname}) {
 5790: 	      return 'error: user id "'.$uid.'" does not match '.
 5791:                   'current user id "'.$uidhash{$uname}.'".';
 5792:           }
 5793:        } else {
 5794: 	  &idput($udom,($uname => $uid));
 5795:        }
 5796:     }
 5797: # -------------------------------------------------------------- Add names, etc
 5798:     my @tmp=&get('environment',
 5799: 		   ['firstname','middlename','lastname','generation','id',
 5800:                     'permanentemail','inststatus'],
 5801: 		   $udom,$uname);
 5802:     my %names;
 5803:     if ($tmp[0] =~ m/^error:.*/) { 
 5804:         %names=(); 
 5805:     } else {
 5806:         %names = @tmp;
 5807:     }
 5808: #
 5809: # Make sure to not trash student environment if instructor does not bother
 5810: # to supply name and email information
 5811: #
 5812:     if ($first)  { $names{'firstname'}  = $first; }
 5813:     if (defined($middle)) { $names{'middlename'} = $middle; }
 5814:     if ($last)   { $names{'lastname'}   = $last; }
 5815:     if (defined($gene))   { $names{'generation'} = $gene; }
 5816:     if ($email) {
 5817:        $email=~s/[^\w\@\.\-\,]//gs;
 5818:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 5819:     }
 5820:     if ($uid) { $names{'id'}  = $uid; }
 5821:     if (defined($inststatus)) { $names{'inststatus'} = $inststatus; } 
 5822:     my $reply = &put('environment', \%names, $udom,$uname);
 5823:     if ($reply ne 'ok') { return 'error: '.$reply; }
 5824:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 5825:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 5826:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 5827:                  $umode.', '.$first.', '.$middle.', '.
 5828: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
 5829:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 5830:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 5831:     } else {
 5832:         $logmsg .= ' during self creation';
 5833:     }
 5834:     &logthis($logmsg);
 5835:     return 'ok';
 5836: }
 5837: 
 5838: # -------------------------------------------------------------- Modify student
 5839: 
 5840: sub modifystudent {
 5841:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 5842:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 5843:         $selfenroll,$context)=@_;
 5844:     if (!$cid) {
 5845: 	unless ($cid=$env{'request.course.id'}) {
 5846: 	    return 'not_in_class';
 5847: 	}
 5848:     }
 5849: # --------------------------------------------------------------- Make the user
 5850:     my $reply=&modifyuser
 5851: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 5852:          $desiredhome,$email);
 5853:     unless ($reply eq 'ok') { return $reply; }
 5854:     # This will cause &modify_student_enrollment to get the uid from the
 5855:     # students environment
 5856:     $uid = undef if (!$forceid);
 5857:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 5858: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 5859:     return $reply;
 5860: }
 5861: 
 5862: sub modify_student_enrollment {
 5863:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 5864:     my ($cdom,$cnum,$chome);
 5865:     if (!$cid) {
 5866: 	unless ($cid=$env{'request.course.id'}) {
 5867: 	    return 'not_in_class';
 5868: 	}
 5869: 	$cdom=$env{'course.'.$cid.'.domain'};
 5870: 	$cnum=$env{'course.'.$cid.'.num'};
 5871:     } else {
 5872: 	($cdom,$cnum)=split(/_/,$cid);
 5873:     }
 5874:     $chome=$env{'course.'.$cid.'.home'};
 5875:     if (!$chome) {
 5876: 	$chome=&homeserver($cnum,$cdom);
 5877:     }
 5878:     if (!$chome) { return 'unknown_course'; }
 5879:     # Make sure the user exists
 5880:     my $uhome=&homeserver($uname,$udom);
 5881:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5882: 	return 'error: no such user';
 5883:     }
 5884:     # Get student data if we were not given enough information
 5885:     if (!defined($first)  || $first  eq '' || 
 5886:         !defined($last)   || $last   eq '' || 
 5887:         !defined($uid)    || $uid    eq '' || 
 5888:         !defined($middle) || $middle eq '' || 
 5889:         !defined($gene)   || $gene   eq '') {
 5890:         # They did not supply us with enough data to enroll the student, so
 5891:         # we need to pick up more information.
 5892:         my %tmp = &get('environment',
 5893:                        ['firstname','middlename','lastname', 'generation','id']
 5894:                        ,$udom,$uname);
 5895: 
 5896:         #foreach my $key (keys(%tmp)) {
 5897:         #    &logthis("key $key = ".$tmp{$key});
 5898:         #}
 5899:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 5900:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 5901:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 5902:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 5903:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 5904:     }
 5905:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 5906:     my $reply=cput('classlist',
 5907: 		   {"$uname:$udom" => 
 5908: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 5909: 		   $cdom,$cnum);
 5910:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 5911: 	return 'error: '.$reply;
 5912:     } else {
 5913: 	&devalidate_getsection_cache($udom,$uname,$cid);
 5914:     }
 5915:     # Add student role to user
 5916:     my $uurl='/'.$cid;
 5917:     $uurl=~s/\_/\//g;
 5918:     if ($usec) {
 5919: 	$uurl.='/'.$usec;
 5920:     }
 5921:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 5922: }
 5923: 
 5924: sub format_name {
 5925:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 5926:     my $name;
 5927:     if ($first ne 'lastname') {
 5928: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 5929:     } else {
 5930: 	if ($lastname=~/\S/) {
 5931: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 5932: 	    $name=~s/\s+,/,/;
 5933: 	} else {
 5934: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 5935: 	}
 5936:     }
 5937:     $name=~s/^\s+//;
 5938:     $name=~s/\s+$//;
 5939:     $name=~s/\s+/ /g;
 5940:     return $name;
 5941: }
 5942: 
 5943: # ------------------------------------------------- Write to course preferences
 5944: 
 5945: sub writecoursepref {
 5946:     my ($courseid,%prefs)=@_;
 5947:     $courseid=~s/^\///;
 5948:     $courseid=~s/\_/\//g;
 5949:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5950:     my $chome=homeserver($cnum,$cdomain);
 5951:     if (($chome eq '') || ($chome eq 'no_host')) { 
 5952: 	return 'error: no such course';
 5953:     }
 5954:     my $cstring='';
 5955:     foreach my $pref (keys(%prefs)) {
 5956: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 5957:     }
 5958:     $cstring=~s/\&$//;
 5959:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 5960: }
 5961: 
 5962: # ---------------------------------------------------------- Make/modify course
 5963: 
 5964: sub createcourse {
 5965:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 5966:         $course_owner,$crstype)=@_;
 5967:     $url=&declutter($url);
 5968:     my $cid='';
 5969:     unless (&allowed('ccc',$udom)) {
 5970:         return 'refused';
 5971:     }
 5972: # ------------------------------------------------------------------- Create ID
 5973:    my $uname=int(1+rand(9)).
 5974:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 5975:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5976:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5977: # ----------------------------------------------- Make sure that does not exist
 5978:    my $uhome=&homeserver($uname,$udom,'true');
 5979:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5980:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5981:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5982:        $uhome=&homeserver($uname,$udom,'true');       
 5983:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5984:            return 'error: unable to generate unique course-ID';
 5985:        } 
 5986:    }
 5987: # ------------------------------------------------ Check supplied server name
 5988:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 5989:     if (! &is_library($course_server)) {
 5990:         return 'error:bad server name '.$course_server;
 5991:     }
 5992: # ------------------------------------------------------------- Make the course
 5993:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 5994:                       $course_server);
 5995:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 5996:     $uhome=&homeserver($uname,$udom,'true');
 5997:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5998: 	return 'error: no such course';
 5999:     }
 6000: # ----------------------------------------------------------------- Course made
 6001: # log existence
 6002:     my $newcourse = {
 6003:                     $udom.'_'.$uname => {
 6004:                                      description => $description,
 6005:                                      inst_code   => $inst_code,
 6006:                                      owner       => $course_owner,
 6007:                                      type        => $crstype,
 6008:                                                 },
 6009:                     };
 6010:     &courseidput($udom,$newcourse,$uhome,'notime');
 6011: # set toplevel url
 6012:     my $topurl=$url;
 6013:     unless ($nonstandard) {
 6014: # ------------------------------------------ For standard courses, make top url
 6015:         my $mapurl=&clutter($url);
 6016:         if ($mapurl eq '/res/') { $mapurl=''; }
 6017:         $env{'form.initmap'}=(<<ENDINITMAP);
 6018: <map>
 6019: <resource id="1" type="start"></resource>
 6020: <resource id="2" src="$mapurl"></resource>
 6021: <resource id="3" type="finish"></resource>
 6022: <link index="1" from="1" to="2"></link>
 6023: <link index="2" from="2" to="3"></link>
 6024: </map>
 6025: ENDINITMAP
 6026:         $topurl=&declutter(
 6027:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 6028:                           );
 6029:     }
 6030: # ----------------------------------------------------------- Write preferences
 6031:     &writecoursepref($udom.'_'.$uname,
 6032:                      ('description' => $description,
 6033:                       'url'         => $topurl));
 6034:     return '/'.$udom.'/'.$uname;
 6035: }
 6036: 
 6037: sub is_course {
 6038:     my ($cdom,$cnum) = @_;
 6039:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 6040: 				undef,'.');
 6041:     if (exists($courses{$cdom.'_'.$cnum})) {
 6042:         return 1;
 6043:     }
 6044:     return 0;
 6045: }
 6046: 
 6047: # ---------------------------------------------------------- Assign Custom Role
 6048: 
 6049: sub assigncustomrole {
 6050:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 6051:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 6052:                        $end,$start,$deleteflag,$selfenroll,$context);
 6053: }
 6054: 
 6055: # ----------------------------------------------------------------- Revoke Role
 6056: 
 6057: sub revokerole {
 6058:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 6059:     my $now=time;
 6060:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 6061: }
 6062: 
 6063: # ---------------------------------------------------------- Revoke Custom Role
 6064: 
 6065: sub revokecustomrole {
 6066:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 6067:     my $now=time;
 6068:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 6069:            $deleteflag,$selfenroll,$context);
 6070: }
 6071: 
 6072: # ------------------------------------------------------------ Disk usage
 6073: sub diskusage {
 6074:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 6075:     $directorypath =~ s/\/$//;
 6076:     my $listing=&reply('du2:'.&escape($directorypath).':'
 6077:                        .&escape($getpropath).':'.&escape($uname).':'
 6078:                        .&escape($udom),homeserver($uname,$udom));
 6079:     if ($listing eq 'unknown_cmd') {
 6080:         if ($getpropath) {
 6081:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 6082:         }
 6083:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 6084:     }
 6085:     return $listing;
 6086: }
 6087: 
 6088: sub is_locked {
 6089:     my ($file_name, $domain, $user) = @_;
 6090:     my @check;
 6091:     my $is_locked;
 6092:     push @check, $file_name;
 6093:     my %locked = &get('file_permissions',\@check,
 6094: 		      $env{'user.domain'},$env{'user.name'});
 6095:     my ($tmp)=keys(%locked);
 6096:     if ($tmp=~/^error:/) { undef(%locked); }
 6097:     
 6098:     if (ref($locked{$file_name}) eq 'ARRAY') {
 6099:         $is_locked = 'false';
 6100:         foreach my $entry (@{$locked{$file_name}}) {
 6101:            if (ref($entry) eq 'ARRAY') { 
 6102:                $is_locked = 'true';
 6103:                last;
 6104:            }
 6105:        }
 6106:     } else {
 6107:         $is_locked = 'false';
 6108:     }
 6109: }
 6110: 
 6111: sub declutter_portfile {
 6112:     my ($file) = @_;
 6113:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 6114:     return $file;
 6115: }
 6116: 
 6117: # ------------------------------------------------------------- Mark as Read Only
 6118: 
 6119: sub mark_as_readonly {
 6120:     my ($domain,$user,$files,$what) = @_;
 6121:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6122:     my ($tmp)=keys(%current_permissions);
 6123:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6124:     foreach my $file (@{$files}) {
 6125: 	$file = &declutter_portfile($file);
 6126:         push(@{$current_permissions{$file}},$what);
 6127:     }
 6128:     &put('file_permissions',\%current_permissions,$domain,$user);
 6129:     return;
 6130: }
 6131: 
 6132: # ------------------------------------------------------------Save Selected Files
 6133: 
 6134: sub save_selected_files {
 6135:     my ($user, $path, @files) = @_;
 6136:     my $filename = $user."savedfiles";
 6137:     my @other_files = &files_not_in_path($user, $path);
 6138:     open (OUT, '>'.$tmpdir.$filename);
 6139:     foreach my $file (@files) {
 6140:         print (OUT $env{'form.currentpath'}.$file."\n");
 6141:     }
 6142:     foreach my $file (@other_files) {
 6143:         print (OUT $file."\n");
 6144:     }
 6145:     close (OUT);
 6146:     return 'ok';
 6147: }
 6148: 
 6149: sub clear_selected_files {
 6150:     my ($user) = @_;
 6151:     my $filename = $user."savedfiles";
 6152:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6153:     print (OUT undef);
 6154:     close (OUT);
 6155:     return ("ok");    
 6156: }
 6157: 
 6158: sub files_in_path {
 6159:     my ($user, $path) = @_;
 6160:     my $filename = $user."savedfiles";
 6161:     my %return_files;
 6162:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6163:     while (my $line_in = <IN>) {
 6164:         chomp ($line_in);
 6165:         my @paths_and_file = split (m!/!, $line_in);
 6166:         my $file_part = pop (@paths_and_file);
 6167:         my $path_part = join ('/', @paths_and_file);
 6168:         $path_part.='/';
 6169:         my $path_and_file = $path_part.$file_part;
 6170:         if ($path_part eq $path) {
 6171:             $return_files{$file_part}= 'selected';
 6172:         }
 6173:     }
 6174:     close (IN);
 6175:     return (\%return_files);
 6176: }
 6177: 
 6178: # called in portfolio select mode, to show files selected NOT in current directory
 6179: sub files_not_in_path {
 6180:     my ($user, $path) = @_;
 6181:     my $filename = $user."savedfiles";
 6182:     my @return_files;
 6183:     my $path_part;
 6184:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6185:     while (my $line = <IN>) {
 6186:         #ok, I know it's clunky, but I want it to work
 6187:         my @paths_and_file = split(m|/|, $line);
 6188:         my $file_part = pop(@paths_and_file);
 6189:         chomp($file_part);
 6190:         my $path_part = join('/', @paths_and_file);
 6191:         $path_part .= '/';
 6192:         my $path_and_file = $path_part.$file_part;
 6193:         if ($path_part ne $path) {
 6194:             push(@return_files, ($path_and_file));
 6195:         }
 6196:     }
 6197:     close(OUT);
 6198:     return (@return_files);
 6199: }
 6200: 
 6201: #----------------------------------------------Get portfolio file permissions
 6202: 
 6203: sub get_portfile_permissions {
 6204:     my ($domain,$user) = @_;
 6205:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6206:     my ($tmp)=keys(%current_permissions);
 6207:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6208:     return \%current_permissions;
 6209: }
 6210: 
 6211: #---------------------------------------------Get portfolio file access controls
 6212: 
 6213: sub get_access_controls {
 6214:     my ($current_permissions,$group,$file) = @_;
 6215:     my %access;
 6216:     my $real_file = $file;
 6217:     $file =~ s/\.meta$//;
 6218:     if (defined($file)) {
 6219:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 6220:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 6221:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 6222:             }
 6223:         }
 6224:     } else {
 6225:         foreach my $key (keys(%{$current_permissions})) {
 6226:             if ($key =~ /\0accesscontrol$/) {
 6227:                 if (defined($group)) {
 6228:                     if ($key !~ m-^\Q$group\E/-) {
 6229:                         next;
 6230:                     }
 6231:                 }
 6232:                 my ($fullpath) = split(/\0/,$key);
 6233:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 6234:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 6235:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 6236:                     }
 6237:                 }
 6238:             }
 6239:         }
 6240:     }
 6241:     return %access;
 6242: }
 6243: 
 6244: sub modify_access_controls {
 6245:     my ($file_name,$changes,$domain,$user)=@_;
 6246:     my ($outcome,$deloutcome);
 6247:     my %store_permissions;
 6248:     my %new_values;
 6249:     my %new_control;
 6250:     my %translation;
 6251:     my @deletions = ();
 6252:     my $now = time;
 6253:     if (exists($$changes{'activate'})) {
 6254:         if (ref($$changes{'activate'}) eq 'HASH') {
 6255:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 6256:             my $numnew = scalar(@newitems);
 6257:             for (my $i=0; $i<$numnew; $i++) {
 6258:                 my $newkey = $newitems[$i];
 6259:                 my $newid = &Apache::loncommon::get_cgi_id();
 6260:                 if ($newkey =~ /^\d+:/) { 
 6261:                     $newkey =~ s/^(\d+)/$newid/;
 6262:                     $translation{$1} = $newid;
 6263:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 6264:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 6265:                     $translation{$1} = $newid;
 6266:                 }
 6267:                 $new_values{$file_name."\0".$newkey} = 
 6268:                                           $$changes{'activate'}{$newitems[$i]};
 6269:                 $new_control{$newkey} = $now;
 6270:             }
 6271:         }
 6272:     }
 6273:     my %todelete;
 6274:     my %changed_items;
 6275:     foreach my $action ('delete','update') {
 6276:         if (exists($$changes{$action})) {
 6277:             if (ref($$changes{$action}) eq 'HASH') {
 6278:                 foreach my $key (keys(%{$$changes{$action}})) {
 6279:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 6280:                     if ($action eq 'delete') { 
 6281:                         $todelete{$itemnum} = 1;
 6282:                     } else {
 6283:                         $changed_items{$itemnum} = $key;
 6284:                     }
 6285:                 }
 6286:             }
 6287:         }
 6288:     }
 6289:     # get lock on access controls for file.
 6290:     my $lockhash = {
 6291:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 6292:                                                        ':'.$env{'user.domain'},
 6293:                    }; 
 6294:     my $tries = 0;
 6295:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6296:    
 6297:     while (($gotlock ne 'ok') && $tries <3) {
 6298:         $tries ++;
 6299:         sleep 1;
 6300:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6301:     }
 6302:     if ($gotlock eq 'ok') {
 6303:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 6304:         my ($tmp)=keys(%curr_permissions);
 6305:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 6306:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 6307:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 6308:             if (ref($curr_controls) eq 'HASH') {
 6309:                 foreach my $control_item (keys(%{$curr_controls})) {
 6310:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 6311:                     if (defined($todelete{$itemnum})) {
 6312:                         push(@deletions,$file_name."\0".$control_item);
 6313:                     } else {
 6314:                         if (defined($changed_items{$itemnum})) {
 6315:                             $new_control{$changed_items{$itemnum}} = $now;
 6316:                             push(@deletions,$file_name."\0".$control_item);
 6317:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 6318:                         } else {
 6319:                             $new_control{$control_item} = $$curr_controls{$control_item};
 6320:                         }
 6321:                     }
 6322:                 }
 6323:             }
 6324:         }
 6325:         my ($group);
 6326:         if (&is_course($domain,$user)) {
 6327:             ($group,my $file) = split(/\//,$file_name,2);
 6328:         }
 6329:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 6330:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 6331:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 6332:         #  remove lock
 6333:         my @del_lock = ($file_name."\0".'locked_access_records');
 6334:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 6335:         my $sqlresult =
 6336:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 6337:                                     $group);
 6338:     } else {
 6339:         $outcome = "error: could not obtain lockfile\n";  
 6340:     }
 6341:     return ($outcome,$deloutcome,\%new_values,\%translation);
 6342: }
 6343: 
 6344: sub make_public_indefinitely {
 6345:     my ($requrl) = @_;
 6346:     my $now = time;
 6347:     my $action = 'activate';
 6348:     my $aclnum = 0;
 6349:     if (&is_portfolio_url($requrl)) {
 6350:         my (undef,$udom,$unum,$file_name,$group) =
 6351:             &parse_portfolio_url($requrl);
 6352:         my $current_perms = &get_portfile_permissions($udom,$unum);
 6353:         my %access_controls = &get_access_controls($current_perms,
 6354:                                                    $group,$file_name);
 6355:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 6356:             my ($num,$scope,$end,$start) = 
 6357:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6358:             if ($scope eq 'public') {
 6359:                 if ($start <= $now && $end == 0) {
 6360:                     $action = 'none';
 6361:                 } else {
 6362:                     $action = 'update';
 6363:                     $aclnum = $num;
 6364:                 }
 6365:                 last;
 6366:             }
 6367:         }
 6368:         if ($action eq 'none') {
 6369:              return 'ok';
 6370:         } else {
 6371:             my %changes;
 6372:             my $newend = 0;
 6373:             my $newstart = $now;
 6374:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 6375:             $changes{$action}{$newkey} = {
 6376:                 type => 'public',
 6377:                 time => {
 6378:                     start => $newstart,
 6379:                     end   => $newend,
 6380:                 },
 6381:             };
 6382:             my ($outcome,$deloutcome,$new_values,$translation) =
 6383:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 6384:             return $outcome;
 6385:         }
 6386:     } else {
 6387:         return 'invalid';
 6388:     }
 6389: }
 6390: 
 6391: #------------------------------------------------------Get Marked as Read Only
 6392: 
 6393: sub get_marked_as_readonly {
 6394:     my ($domain,$user,$what,$group) = @_;
 6395:     my $current_permissions = &get_portfile_permissions($domain,$user);
 6396:     my @readonly_files;
 6397:     my $cmp1=$what;
 6398:     if (ref($what)) { $cmp1=join('',@{$what}) };
 6399:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6400:         if (defined($group)) {
 6401:             if ($file_name !~ m-^\Q$group\E/-) {
 6402:                 next;
 6403:             }
 6404:         }
 6405:         if (ref($value) eq "ARRAY"){
 6406:             foreach my $stored_what (@{$value}) {
 6407:                 my $cmp2=$stored_what;
 6408:                 if (ref($stored_what) eq 'ARRAY') {
 6409:                     $cmp2=join('',@{$stored_what});
 6410:                 }
 6411:                 if ($cmp1 eq $cmp2) {
 6412:                     push(@readonly_files, $file_name);
 6413:                     last;
 6414:                 } elsif (!defined($what)) {
 6415:                     push(@readonly_files, $file_name);
 6416:                     last;
 6417:                 }
 6418:             }
 6419:         }
 6420:     }
 6421:     return @readonly_files;
 6422: }
 6423: #-----------------------------------------------------------Get Marked as Read Only Hash
 6424: 
 6425: sub get_marked_as_readonly_hash {
 6426:     my ($current_permissions,$group,$what) = @_;
 6427:     my %readonly_files;
 6428:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6429:         if (defined($group)) {
 6430:             if ($file_name !~ m-^\Q$group\E/-) {
 6431:                 next;
 6432:             }
 6433:         }
 6434:         if (ref($value) eq "ARRAY"){
 6435:             foreach my $stored_what (@{$value}) {
 6436:                 if (ref($stored_what) eq 'ARRAY') {
 6437:                     foreach my $lock_descriptor(@{$stored_what}) {
 6438:                         if ($lock_descriptor eq 'graded') {
 6439:                             $readonly_files{$file_name} = 'graded';
 6440:                         } elsif ($lock_descriptor eq 'handback') {
 6441:                             $readonly_files{$file_name} = 'handback';
 6442:                         } else {
 6443:                             if (!exists($readonly_files{$file_name})) {
 6444:                                 $readonly_files{$file_name} = 'locked';
 6445:                             }
 6446:                         }
 6447:                     }
 6448:                 } 
 6449:             }
 6450:         } 
 6451:     }
 6452:     return %readonly_files;
 6453: }
 6454: # ------------------------------------------------------------ Unmark as Read Only
 6455: 
 6456: sub unmark_as_readonly {
 6457:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 6458:     # for portfolio submissions, $what contains [$symb,$crsid] 
 6459:     my ($domain,$user,$what,$file_name,$group) = @_;
 6460:     $file_name = &declutter_portfile($file_name);
 6461:     my $symb_crs = $what;
 6462:     if (ref($what)) { $symb_crs=join('',@$what); }
 6463:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 6464:     my ($tmp)=keys(%current_permissions);
 6465:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6466:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 6467:     foreach my $file (@readonly_files) {
 6468: 	my $clean_file = &declutter_portfile($file);
 6469: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 6470: 	my $current_locks = $current_permissions{$file};
 6471:         my @new_locks;
 6472:         my @del_keys;
 6473:         if (ref($current_locks) eq "ARRAY"){
 6474:             foreach my $locker (@{$current_locks}) {
 6475:                 my $compare=$locker;
 6476:                 if (ref($locker) eq 'ARRAY') {
 6477:                     $compare=join('',@{$locker});
 6478:                     if ($compare ne $symb_crs) {
 6479:                         push(@new_locks, $locker);
 6480:                     }
 6481:                 }
 6482:             }
 6483:             if (scalar(@new_locks) > 0) {
 6484:                 $current_permissions{$file} = \@new_locks;
 6485:             } else {
 6486:                 push(@del_keys, $file);
 6487:                 &del('file_permissions',\@del_keys, $domain, $user);
 6488:                 delete($current_permissions{$file});
 6489:             }
 6490:         }
 6491:     }
 6492:     &put('file_permissions',\%current_permissions,$domain,$user);
 6493:     return;
 6494: }
 6495: 
 6496: # ------------------------------------------------------------ Directory lister
 6497: 
 6498: sub dirlist {
 6499:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 6500:     $uri=~s/^\///;
 6501:     $uri=~s/\/$//;
 6502:     my ($udom, $uname);
 6503:     if ($getuserdir) {
 6504:         $udom = $userdomain;
 6505:         $uname = $username;
 6506:     } else {
 6507:         (undef,$udom,$uname)=split(/\//,$uri);
 6508:         if(defined($userdomain)) {
 6509:             $udom = $userdomain;
 6510:         }
 6511:         if(defined($username)) {
 6512:             $uname = $username;
 6513:         }
 6514:     }
 6515:     my ($dirRoot,$listing,@listing_results);
 6516: 
 6517:     $dirRoot = $perlvar{'lonDocRoot'};
 6518:     if (defined($getpropath)) {
 6519:         $dirRoot = &propath($udom,$uname);
 6520:         $dirRoot =~ s/\/$//;
 6521:     } elsif (defined($getuserdir)) {
 6522:         my $subdir=$uname.'__';
 6523:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 6524:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 6525:                    ."/$udom/$subdir/$uname";
 6526:     } elsif (defined($alternateRoot)) {
 6527:         $dirRoot = $alternateRoot;
 6528:     }
 6529: 
 6530:     if($udom) {
 6531:         if($uname) {
 6532:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 6533:                               .$getuserdir.':'.&escape($dirRoot)
 6534:                               .':'.&escape($uname).':'.&escape($udom),
 6535:                               &homeserver($uname,$udom));
 6536:             if ($listing eq 'unknown_cmd') {
 6537:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 6538:                                   &homeserver($uname,$udom));
 6539:             } else {
 6540:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6541:             }
 6542:             if ($listing eq 'unknown_cmd') {
 6543:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 6544: 				  &homeserver($uname,$udom));
 6545:                 @listing_results = split(/:/,$listing);
 6546:             } else {
 6547:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6548:             }
 6549:             return @listing_results;
 6550:         } elsif(!$alternateRoot) {
 6551:             my %allusers;
 6552: 	    my %servers = &get_servers($udom,'library');
 6553:  	    foreach my $tryserver (keys(%servers)) {
 6554:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 6555:                                   &escape($udom),$tryserver);
 6556:                 if ($listing eq 'unknown_cmd') {
 6557: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 6558: 				      $udom, $tryserver);
 6559:                 } else {
 6560:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 6561:                 }
 6562: 		if ($listing eq 'unknown_cmd') {
 6563: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 6564: 				      $udom, $tryserver);
 6565: 		    @listing_results = split(/:/,$listing);
 6566: 		} else {
 6567: 		    @listing_results =
 6568: 			map { &unescape($_); } split(/:/,$listing);
 6569: 		}
 6570: 		if ($listing_results[0] ne 'no_such_dir' && 
 6571: 		    $listing_results[0] ne 'empty'       &&
 6572: 		    $listing_results[0] ne 'con_lost') {
 6573: 		    foreach my $line (@listing_results) {
 6574: 			my ($entry) = split(/&/,$line,2);
 6575: 			$allusers{$entry} = 1;
 6576: 		    }
 6577: 		}
 6578:             }
 6579:             my $alluserstr='';
 6580:             foreach my $user (sort(keys(%allusers))) {
 6581:                 $alluserstr.=$user.'&user:';
 6582:             }
 6583:             $alluserstr=~s/:$//;
 6584:             return split(/:/,$alluserstr);
 6585:         } else {
 6586:             return ('missing user name');
 6587:         }
 6588:     } elsif(!defined($getpropath)) {
 6589:         my @all_domains = sort(&all_domains());
 6590:         foreach my $domain (@all_domains) {
 6591:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 6592:         }
 6593:         return @all_domains;
 6594:     } else {
 6595:         return ('missing domain');
 6596:     }
 6597: }
 6598: 
 6599: # --------------------------------------------- GetFileTimestamp
 6600: # This function utilizes dirlist and returns the date stamp for
 6601: # when it was last modified.  It will also return an error of -1
 6602: # if an error occurs
 6603: 
 6604: sub GetFileTimestamp {
 6605:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 6606:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 6607:     $studentName   = &LONCAPA::clean_username($studentName);
 6608:     my ($fileStat) = 
 6609:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
 6610:                                  undef,$getuserdir);
 6611:     my @stats = split('&', $fileStat);
 6612:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6613:         # @stats contains first the filename, then the stat output
 6614:         return $stats[10]; # so this is 10 instead of 9.
 6615:     } else {
 6616:         return -1;
 6617:     }
 6618: }
 6619: 
 6620: sub stat_file {
 6621:     my ($uri) = @_;
 6622:     $uri = &clutter_with_no_wrapper($uri);
 6623: 
 6624:     my ($udom,$uname,$file);
 6625:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 6626: 	($udom,$uname,$file) =
 6627: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 6628: 	$file = 'userfiles/'.$file;
 6629:     }
 6630:     if ($uri =~ m-^/res/-) {
 6631: 	($udom,$uname) = 
 6632: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 6633: 	$file = $uri;
 6634:     }
 6635: 
 6636:     if (!$udom || !$uname || !$file) {
 6637: 	# unable to handle the uri
 6638: 	return ();
 6639:     }
 6640:     my $getpropath;
 6641:     if ($file =~ /^userfiles\//) {
 6642:         $getpropath = 1;
 6643:     }
 6644:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
 6645:     my @stats = split('&', $result);
 6646:     
 6647:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6648: 	shift(@stats); #filename is first
 6649: 	return @stats;
 6650:     }
 6651:     return ();
 6652: }
 6653: 
 6654: # -------------------------------------------------------- Value of a Condition
 6655: 
 6656: # gets the value of a specific preevaluated condition
 6657: #    stored in the string  $env{user.state.<cid>}
 6658: # or looks up a condition reference in the bighash and if if hasn't
 6659: # already been evaluated recurses into docondval to get the value of
 6660: # the condition, then memoizing it to 
 6661: #   $env{user.state.<cid>.<condition>}
 6662: sub directcondval {
 6663:     my $number=shift;
 6664:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 6665: 	&Apache::lonuserstate::evalstate();
 6666:     }
 6667:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 6668: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 6669:     } elsif ($number =~ /^_/) {
 6670: 	my $sub_condition;
 6671: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6672: 		&GDBM_READER(),0640)) {
 6673: 	    $sub_condition=$bighash{'conditions'.$number};
 6674: 	    untie(%bighash);
 6675: 	}
 6676: 	my $value = &docondval($sub_condition);
 6677: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 6678: 	return $value;
 6679:     }
 6680:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 6681:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 6682:     } else {
 6683:        return 2;
 6684:     }
 6685: }
 6686: 
 6687: # get the collection of conditions for this resource
 6688: sub condval {
 6689:     my $condidx=shift;
 6690:     my $allpathcond='';
 6691:     foreach my $cond (split(/\|/,$condidx)) {
 6692: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 6693: 	    $allpathcond.=
 6694: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 6695: 	}
 6696:     }
 6697:     $allpathcond=~s/\|$//;
 6698:     return &docondval($allpathcond);
 6699: }
 6700: 
 6701: #evaluates an expression of conditions
 6702: sub docondval {
 6703:     my ($allpathcond) = @_;
 6704:     my $result=0;
 6705:     if ($env{'request.course.id'}
 6706: 	&& defined($allpathcond)) {
 6707: 	my $operand='|';
 6708: 	my @stack;
 6709: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 6710: 	    if ($chunk eq '(') {
 6711: 		push @stack,($operand,$result);
 6712: 	    } elsif ($chunk eq ')') {
 6713: 		my $before=pop @stack;
 6714: 		if (pop @stack eq '&') {
 6715: 		    $result=$result>$before?$before:$result;
 6716: 		} else {
 6717: 		    $result=$result>$before?$result:$before;
 6718: 		}
 6719: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 6720: 		$operand=$chunk;
 6721: 	    } else {
 6722: 		my $new=directcondval($chunk);
 6723: 		if ($operand eq '&') {
 6724: 		    $result=$result>$new?$new:$result;
 6725: 		} else {
 6726: 		    $result=$result>$new?$result:$new;
 6727: 		}
 6728: 	    }
 6729: 	}
 6730:     }
 6731:     return $result;
 6732: }
 6733: 
 6734: # ---------------------------------------------------- Devalidate courseresdata
 6735: 
 6736: sub devalidatecourseresdata {
 6737:     my ($coursenum,$coursedomain)=@_;
 6738:     my $hashid=$coursenum.':'.$coursedomain;
 6739:     &devalidate_cache_new('courseres',$hashid);
 6740: }
 6741: 
 6742: 
 6743: # --------------------------------------------------- Course Resourcedata Query
 6744: #
 6745: #  Parameters:
 6746: #      $coursenum    - Number of the course.
 6747: #      $coursedomain - Domain at which the course was created.
 6748: #  Returns:
 6749: #     A hash of the course parameters along (I think) with timestamps
 6750: #     and version info.
 6751: 
 6752: sub get_courseresdata {
 6753:     my ($coursenum,$coursedomain)=@_;
 6754:     my $coursehom=&homeserver($coursenum,$coursedomain);
 6755:     my $hashid=$coursenum.':'.$coursedomain;
 6756:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 6757:     my %dumpreply;
 6758:     unless (defined($cached)) {
 6759: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 6760: 	$result=\%dumpreply;
 6761: 	my ($tmp) = keys(%dumpreply);
 6762: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6763: 	    &do_cache_new('courseres',$hashid,$result,600);
 6764: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 6765: 	    return $tmp;
 6766: 	} elsif ($tmp =~ /^(error)/) {
 6767: 	    $result=undef;
 6768: 	    &do_cache_new('courseres',$hashid,$result,600);
 6769: 	}
 6770:     }
 6771:     return $result;
 6772: }
 6773: 
 6774: sub devalidateuserresdata {
 6775:     my ($uname,$udom)=@_;
 6776:     my $hashid="$udom:$uname";
 6777:     &devalidate_cache_new('userres',$hashid);
 6778: }
 6779: 
 6780: sub get_userresdata {
 6781:     my ($uname,$udom)=@_;
 6782:     #most student don\'t have any data set, check if there is some data
 6783:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 6784: 
 6785:     my $hashid="$udom:$uname";
 6786:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 6787:     if (!defined($cached)) {
 6788: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 6789: 	$result=\%resourcedata;
 6790: 	&do_cache_new('userres',$hashid,$result,600);
 6791:     }
 6792:     my ($tmp)=keys(%$result);
 6793:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 6794: 	return $result;
 6795:     }
 6796:     #error 2 occurs when the .db doesn't exist
 6797:     if ($tmp!~/error: 2 /) {
 6798: 	&logthis("<font color=\"blue\">WARNING:".
 6799: 		 " Trying to get resource data for ".
 6800: 		 $uname." at ".$udom.": ".
 6801: 		 $tmp."</font>");
 6802:     } elsif ($tmp=~/error: 2 /) {
 6803: 	#&EXT_cache_set($udom,$uname);
 6804: 	&do_cache_new('userres',$hashid,undef,600);
 6805: 	undef($tmp); # not really an error so don't send it back
 6806:     }
 6807:     return $tmp;
 6808: }
 6809: #----------------------------------------------- resdata - return resource data
 6810: #  Purpose:
 6811: #    Return resource data for either users or for a course.
 6812: #  Parameters:
 6813: #     $name      - Course/user name.
 6814: #     $domain    - Name of the domain the user/course is registered on.
 6815: #     $type      - Type of thing $name is (must be 'course' or 'user'
 6816: #     @which     - Array of names of resources desired.
 6817: #  Returns:
 6818: #     The value of the first reasource in @which that is found in the
 6819: #     resource hash.
 6820: #  Exceptional Conditions:
 6821: #     If the $type passed in is not valid (not the string 'course' or 
 6822: #     'user', an undefined  reference is returned.
 6823: #     If none of the resources are found, an undef is returned
 6824: sub resdata {
 6825:     my ($name,$domain,$type,@which)=@_;
 6826:     my $result;
 6827:     if ($type eq 'course') {
 6828: 	$result=&get_courseresdata($name,$domain);
 6829:     } elsif ($type eq 'user') {
 6830: 	$result=&get_userresdata($name,$domain);
 6831:     }
 6832:     if (!ref($result)) { return $result; }    
 6833:     foreach my $item (@which) {
 6834: 	if (defined($result->{$item->[0]})) {
 6835: 	    return [$result->{$item->[0]},$item->[1]];
 6836: 	}
 6837:     }
 6838:     return undef;
 6839: }
 6840: 
 6841: #
 6842: # EXT resource caching routines
 6843: #
 6844: 
 6845: sub clear_EXT_cache_status {
 6846:     &delenv('cache.EXT.');
 6847: }
 6848: 
 6849: sub EXT_cache_status {
 6850:     my ($target_domain,$target_user) = @_;
 6851:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6852:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 6853:         # We know already the user has no data
 6854:         return 1;
 6855:     } else {
 6856:         return 0;
 6857:     }
 6858: }
 6859: 
 6860: sub EXT_cache_set {
 6861:     my ($target_domain,$target_user) = @_;
 6862:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6863:     #&appenv({$cachename => time});
 6864: }
 6865: 
 6866: # --------------------------------------------------------- Value of a Variable
 6867: sub EXT {
 6868: 
 6869:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 6870:     unless ($varname) { return ''; }
 6871:     #get real user name/domain, courseid and symb
 6872:     my $courseid;
 6873:     my $publicuser;
 6874:     if ($symbparm) {
 6875: 	$symbparm=&get_symb_from_alias($symbparm);
 6876:     }
 6877:     if (!($uname && $udom)) {
 6878:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 6879:       if (!$symbparm) {	$symbparm=$cursymb; }
 6880:     } else {
 6881: 	$courseid=$env{'request.course.id'};
 6882:     }
 6883:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 6884:     my $rest;
 6885:     if (defined($therest[0])) {
 6886:        $rest=join('.',@therest);
 6887:     } else {
 6888:        $rest='';
 6889:     }
 6890: 
 6891:     my $qualifierrest=$qualifier;
 6892:     if ($rest) { $qualifierrest.='.'.$rest; }
 6893:     my $spacequalifierrest=$space;
 6894:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 6895:     if ($realm eq 'user') {
 6896: # --------------------------------------------------------------- user.resource
 6897: 	if ($space eq 'resource') {
 6898: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 6899: 		  || defined($Apache::lonhomework::parsing_a_task))
 6900: 		 &&
 6901: 		 ($symbparm eq &symbread()) ) {	
 6902: 		# if we are in the middle of processing the resource the
 6903: 		# get the value we are planning on committing
 6904:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 6905:                     return $Apache::lonhomework::results{$qualifierrest};
 6906:                 } else {
 6907:                     return $Apache::lonhomework::history{$qualifierrest};
 6908:                 }
 6909: 	    } else {
 6910: 		my %restored;
 6911: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 6912: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 6913: 		} else {
 6914: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 6915: 		}
 6916: 		return $restored{$qualifierrest};
 6917: 	    }
 6918: # ----------------------------------------------------------------- user.access
 6919:         } elsif ($space eq 'access') {
 6920: 	    # FIXME - not supporting calls for a specific user
 6921:             return &allowed($qualifier,$rest);
 6922: # ------------------------------------------ user.preferences, user.environment
 6923:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 6924: 	    if (($uname eq $env{'user.name'}) &&
 6925: 		($udom eq $env{'user.domain'})) {
 6926: 		return $env{join('.',('environment',$qualifierrest))};
 6927: 	    } else {
 6928: 		my %returnhash;
 6929: 		if (!$publicuser) {
 6930: 		    %returnhash=&userenvironment($udom,$uname,
 6931: 						 $qualifierrest);
 6932: 		}
 6933: 		return $returnhash{$qualifierrest};
 6934: 	    }
 6935: # ----------------------------------------------------------------- user.course
 6936:         } elsif ($space eq 'course') {
 6937: 	    # FIXME - not supporting calls for a specific user
 6938:             return $env{join('.',('request.course',$qualifier))};
 6939: # ------------------------------------------------------------------- user.role
 6940:         } elsif ($space eq 'role') {
 6941: 	    # FIXME - not supporting calls for a specific user
 6942:             my ($role,$where)=split(/\./,$env{'request.role'});
 6943:             if ($qualifier eq 'value') {
 6944: 		return $role;
 6945:             } elsif ($qualifier eq 'extent') {
 6946:                 return $where;
 6947:             }
 6948: # ----------------------------------------------------------------- user.domain
 6949:         } elsif ($space eq 'domain') {
 6950:             return $udom;
 6951: # ------------------------------------------------------------------- user.name
 6952:         } elsif ($space eq 'name') {
 6953:             return $uname;
 6954: # ---------------------------------------------------- Any other user namespace
 6955:         } else {
 6956: 	    my %reply;
 6957: 	    if (!$publicuser) {
 6958: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 6959: 	    }
 6960: 	    return $reply{$qualifierrest};
 6961:         }
 6962:     } elsif ($realm eq 'query') {
 6963: # ---------------------------------------------- pull stuff out of query string
 6964:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 6965: 						[$spacequalifierrest]);
 6966: 	return $env{'form.'.$spacequalifierrest}; 
 6967:    } elsif ($realm eq 'request') {
 6968: # ------------------------------------------------------------- request.browser
 6969:         if ($space eq 'browser') {
 6970: 	    if ($qualifier eq 'textremote') {
 6971: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 6972: 		    return 1;
 6973: 		} else {
 6974: 		    return 0;
 6975: 		}
 6976: 	    } else {
 6977: 		return $env{'browser.'.$qualifier};
 6978: 	    }
 6979: # ------------------------------------------------------------ request.filename
 6980:         } else {
 6981:             return $env{'request.'.$spacequalifierrest};
 6982:         }
 6983:     } elsif ($realm eq 'course') {
 6984: # ---------------------------------------------------------- course.description
 6985:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 6986:     } elsif ($realm eq 'resource') {
 6987: 
 6988: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 6989: 	    if (!$symbparm) { $symbparm=&symbread(); }
 6990: 	}
 6991: 
 6992: 	if ($space eq 'title') {
 6993: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 6994: 	    return &gettitle($symbparm);
 6995: 	}
 6996: 	
 6997: 	if ($space eq 'map') {
 6998: 	    my ($map) = &decode_symb($symbparm);
 6999: 	    return &symbread($map);
 7000: 	}
 7001: 	if ($space eq 'filename') {
 7002: 	    if ($symbparm) {
 7003: 		return &clutter((&decode_symb($symbparm))[2]);
 7004: 	    }
 7005: 	    return &hreflocation('',$env{'request.filename'});
 7006: 	}
 7007: 
 7008: 	my ($section, $group, @groups);
 7009: 	my ($courselevelm,$courselevel);
 7010: 	if ($symbparm && defined($courseid) && 
 7011: 	    $courseid eq $env{'request.course.id'}) {
 7012: 
 7013: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 7014: 
 7015: # ----------------------------------------------------- Cascading lookup scheme
 7016: 	    my $symbp=$symbparm;
 7017: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 7018: 
 7019: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 7020: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 7021: 
 7022: 	    if (($env{'user.name'} eq $uname) &&
 7023: 		($env{'user.domain'} eq $udom)) {
 7024: 		$section=$env{'request.course.sec'};
 7025:                 @groups = split(/:/,$env{'request.course.groups'});  
 7026:                 @groups=&sort_course_groups($courseid,@groups); 
 7027: 	    } else {
 7028: 		if (! defined($usection)) {
 7029: 		    $section=&getsection($udom,$uname,$courseid);
 7030: 		} else {
 7031: 		    $section = $usection;
 7032: 		}
 7033:                 @groups = &get_users_groups($udom,$uname,$courseid);
 7034: 	    }
 7035: 
 7036: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 7037: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 7038: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 7039: 
 7040: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 7041: 	    my $courselevelr=$courseid.'.'.$symbparm;
 7042: 	    $courselevelm=$courseid.'.'.$mapparm;
 7043: 
 7044: # ----------------------------------------------------------- first, check user
 7045: 
 7046: 	    my $userreply=&resdata($uname,$udom,'user',
 7047: 				       ([$courselevelr,'resource'],
 7048: 					[$courselevelm,'map'     ],
 7049: 					[$courselevel, 'course'  ]));
 7050: 	    if (defined($userreply)) { return &get_reply($userreply); }
 7051: 
 7052: # ------------------------------------------------ second, check some of course
 7053:             my $coursereply;
 7054:             if (@groups > 0) {
 7055:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 7056:                                        $mapparm,$spacequalifierrest);
 7057:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 7058:             }
 7059: 
 7060: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7061: 				  $env{'course.'.$courseid.'.domain'},
 7062: 				  'course',
 7063: 				  ([$seclevelr,   'resource'],
 7064: 				   [$seclevelm,   'map'     ],
 7065: 				   [$seclevel,    'course'  ],
 7066: 				   [$courselevelr,'resource']));
 7067: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7068: 
 7069: # ------------------------------------------------------ third, check map parms
 7070: 	    my %parmhash=();
 7071: 	    my $thisparm='';
 7072: 	    if (tie(%parmhash,'GDBM_File',
 7073: 		    $env{'request.course.fn'}.'_parms.db',
 7074: 		    &GDBM_READER(),0640)) {
 7075: 		$thisparm=$parmhash{$symbparm};
 7076: 		untie(%parmhash);
 7077: 	    }
 7078: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 7079: 	}
 7080: # ------------------------------------------ fourth, look in resource metadata
 7081: 
 7082: 	$spacequalifierrest=~s/\./\_/;
 7083: 	my $filename;
 7084: 	if (!$symbparm) { $symbparm=&symbread(); }
 7085: 	if ($symbparm) {
 7086: 	    $filename=(&decode_symb($symbparm))[2];
 7087: 	} else {
 7088: 	    $filename=$env{'request.filename'};
 7089: 	}
 7090: 	my $metadata=&metadata($filename,$spacequalifierrest);
 7091: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7092: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 7093: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7094: 
 7095: # ---------------------------------------------- fourth, look in rest of course
 7096: 	if ($symbparm && defined($courseid) && 
 7097: 	    $courseid eq $env{'request.course.id'}) {
 7098: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7099: 				     $env{'course.'.$courseid.'.domain'},
 7100: 				     'course',
 7101: 				     ([$courselevelm,'map'   ],
 7102: 				      [$courselevel, 'course']));
 7103: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7104: 	}
 7105: # ------------------------------------------------------------------ Cascade up
 7106: 	unless ($space eq '0') {
 7107: 	    my @parts=split(/_/,$space);
 7108: 	    my $id=pop(@parts);
 7109: 	    my $part=join('_',@parts);
 7110: 	    if ($part eq '') { $part='0'; }
 7111: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 7112: 				 $symbparm,$udom,$uname,$section,1);
 7113: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 7114: 	}
 7115: 	if ($recurse) { return undef; }
 7116: 	my $pack_def=&packages_tab_default($filename,$varname);
 7117: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 7118: # ---------------------------------------------------- Any other user namespace
 7119:     } elsif ($realm eq 'environment') {
 7120: # ----------------------------------------------------------------- environment
 7121: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 7122: 	    return $env{'environment.'.$spacequalifierrest};
 7123: 	} else {
 7124: 	    if ($uname eq 'anonymous' && $udom eq '') {
 7125: 		return '';
 7126: 	    }
 7127: 	    my %returnhash=&userenvironment($udom,$uname,
 7128: 					    $spacequalifierrest);
 7129: 	    return $returnhash{$spacequalifierrest};
 7130: 	}
 7131:     } elsif ($realm eq 'system') {
 7132: # ----------------------------------------------------------------- system.time
 7133: 	if ($space eq 'time') {
 7134: 	    return time;
 7135:         }
 7136:     } elsif ($realm eq 'server') {
 7137: # ----------------------------------------------------------------- system.time
 7138: 	if ($space eq 'name') {
 7139: 	    return $ENV{'SERVER_NAME'};
 7140:         }
 7141:     }
 7142:     return '';
 7143: }
 7144: 
 7145: sub get_reply {
 7146:     my ($reply_value) = @_;
 7147:     if (ref($reply_value) eq 'ARRAY') {
 7148:         if (wantarray) {
 7149: 	    return @$reply_value;
 7150:         }
 7151:         return $reply_value->[0];
 7152:     } else {
 7153:         return $reply_value;
 7154:     }
 7155: }
 7156: 
 7157: sub check_group_parms {
 7158:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 7159:     my @groupitems = ();
 7160:     my $resultitem;
 7161:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 7162:     foreach my $group (@{$groups}) {
 7163:         foreach my $level (@levels) {
 7164:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 7165:              push(@groupitems,[$item,$level->[1]]);
 7166:         }
 7167:     }
 7168:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 7169:                             $env{'course.'.$courseid.'.domain'},
 7170:                                      'course',@groupitems);
 7171:     return $coursereply;
 7172: }
 7173: 
 7174: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 7175:     my ($courseid,@groups) = @_;
 7176:     @groups = sort(@groups);
 7177:     return @groups;
 7178: }
 7179: 
 7180: sub packages_tab_default {
 7181:     my ($uri,$varname)=@_;
 7182:     my (undef,$part,$name)=split(/\./,$varname);
 7183: 
 7184:     my (@extension,@specifics,$do_default);
 7185:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 7186: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 7187: 	if ($pack_type eq 'default') {
 7188: 	    $do_default=1;
 7189: 	} elsif ($pack_type eq 'extension') {
 7190: 	    push(@extension,[$package,$pack_type,$pack_part]);
 7191: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 7192: 	    # only look at packages defaults for packages that this id is
 7193: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 7194: 	}
 7195:     }
 7196:     # first look for a package that matches the requested part id
 7197:     foreach my $package (@specifics) {
 7198: 	my (undef,$pack_type,$pack_part)=@{$package};
 7199: 	next if ($pack_part ne $part);
 7200: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7201: 	    return $packagetab{"$pack_type&$name&default"};
 7202: 	}
 7203:     }
 7204:     # look for any possible matching non extension_ package
 7205:     foreach my $package (@specifics) {
 7206: 	my (undef,$pack_type,$pack_part)=@{$package};
 7207: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7208: 	    return $packagetab{"$pack_type&$name&default"};
 7209: 	}
 7210: 	if ($pack_type eq 'part') { $pack_part='0'; }
 7211: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 7212: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 7213: 	}
 7214:     }
 7215:     # look for any posible extension_ match
 7216:     foreach my $package (@extension) {
 7217: 	my ($package,$pack_type)=@{$package};
 7218: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7219: 	    return $packagetab{"$pack_type&$name&default"};
 7220: 	}
 7221: 	if (defined($packagetab{$package."&$name&default"})) {
 7222: 	    return $packagetab{$package."&$name&default"};
 7223: 	}
 7224:     }
 7225:     # look for a global default setting
 7226:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 7227: 	return $packagetab{"default&$name&default"};
 7228:     }
 7229:     return undef;
 7230: }
 7231: 
 7232: sub add_prefix_and_part {
 7233:     my ($prefix,$part)=@_;
 7234:     my $keyroot;
 7235:     if (defined($prefix) && $prefix !~ /^__/) {
 7236: 	# prefix that has a part already
 7237: 	$keyroot=$prefix;
 7238:     } elsif (defined($prefix)) {
 7239: 	# prefix that is missing a part
 7240: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 7241:     } else {
 7242: 	# no prefix at all
 7243: 	if (defined($part)) { $keyroot='_'.$part; }
 7244:     }
 7245:     return $keyroot;
 7246: }
 7247: 
 7248: # ---------------------------------------------------------------- Get metadata
 7249: 
 7250: my %metaentry;
 7251: sub metadata {
 7252:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 7253:     $uri=&declutter($uri);
 7254:     # if it is a non metadata possible uri return quickly
 7255:     if (($uri eq '') || 
 7256: 	(($uri =~ m|^/*adm/|) && 
 7257: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 7258:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 7259: 	return undef;
 7260:     }
 7261:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 7262: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 7263: 	return undef;
 7264:     }
 7265:     my $filename=$uri;
 7266:     $uri=~s/\.meta$//;
 7267: #
 7268: # Is the metadata already cached?
 7269: # Look at timestamp of caching
 7270: # Everything is cached by the main uri, libraries are never directly cached
 7271: #
 7272:     if (!defined($liburi)) {
 7273: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 7274: 	if (defined($cached)) { return $result->{':'.$what}; }
 7275:     }
 7276:     {
 7277: #
 7278: # Is this a recursive call for a library?
 7279: #
 7280: #	if (! exists($metacache{$uri})) {
 7281: #	    $metacache{$uri}={};
 7282: #	}
 7283: 	my $cachetime = 60*60;
 7284:         if ($liburi) {
 7285: 	    $liburi=&declutter($liburi);
 7286:             $filename=$liburi;
 7287:         } else {
 7288: 	    &devalidate_cache_new('meta',$uri);
 7289: 	    undef(%metaentry);
 7290: 	}
 7291:         my %metathesekeys=();
 7292:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 7293: 	my $metastring;
 7294: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 7295: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 7296: 	    $metastring = 
 7297: 		&Apache::lonnet::ssi_body($which,
 7298: 					  ('grade_target' => 'meta'));
 7299: 	    $cachetime = 1; # only want this cached in the child not long term
 7300: 	} elsif ($uri !~ m -^(editupload)/-) {
 7301: 	    my $file=&filelocation('',&clutter($filename));
 7302: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 7303: 	    $metastring=&getfile($file);
 7304: 	}
 7305:         my $parser=HTML::LCParser->new(\$metastring);
 7306:         my $token;
 7307:         undef %metathesekeys;
 7308:         while ($token=$parser->get_token) {
 7309: 	    if ($token->[0] eq 'S') {
 7310: 		if (defined($token->[2]->{'package'})) {
 7311: #
 7312: # This is a package - get package info
 7313: #
 7314: 		    my $package=$token->[2]->{'package'};
 7315: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7316: 		    if (defined($token->[2]->{'id'})) { 
 7317: 			$keyroot.='_'.$token->[2]->{'id'}; 
 7318: 		    }
 7319: 		    if ($metaentry{':packages'}) {
 7320: 			$metaentry{':packages'}.=','.$package.$keyroot;
 7321: 		    } else {
 7322: 			$metaentry{':packages'}=$package.$keyroot;
 7323: 		    }
 7324: 		    foreach my $pack_entry (keys(%packagetab)) {
 7325: 			my $part=$keyroot;
 7326: 			$part=~s/^\_//;
 7327: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 7328: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 7329: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 7330: 			    # ignore package.tab specified default values
 7331:                             # here &package_tab_default() will fetch those
 7332: 			    if ($subp eq 'default') { next; }
 7333: 			    my $value=$packagetab{$pack_entry};
 7334: 			    my $unikey;
 7335: 			    if ($pack =~ /_0$/) {
 7336: 				$unikey='parameter_0_'.$name;
 7337: 				$part=0;
 7338: 			    } else {
 7339: 				$unikey='parameter'.$keyroot.'_'.$name;
 7340: 			    }
 7341: 			    if ($subp eq 'display') {
 7342: 				$value.=' [Part: '.$part.']';
 7343: 			    }
 7344: 			    $metaentry{':'.$unikey.'.part'}=$part;
 7345: 			    $metathesekeys{$unikey}=1;
 7346: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7347: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 7348: 			    }
 7349: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 7350: 				$metaentry{':'.$unikey}=
 7351: 				    $metaentry{':'.$unikey.'.default'};
 7352: 			    }
 7353: 			}
 7354: 		    }
 7355: 		} else {
 7356: #
 7357: # This is not a package - some other kind of start tag
 7358: #
 7359: 		    my $entry=$token->[1];
 7360: 		    my $unikey;
 7361: 		    if ($entry eq 'import') {
 7362: 			$unikey='';
 7363: 		    } else {
 7364: 			$unikey=$entry;
 7365: 		    }
 7366: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7367: 
 7368: 		    if (defined($token->[2]->{'id'})) { 
 7369: 			$unikey.='_'.$token->[2]->{'id'}; 
 7370: 		    }
 7371: 
 7372: 		    if ($entry eq 'import') {
 7373: #
 7374: # Importing a library here
 7375: #
 7376: 			if ($depthcount<20) {
 7377: 			    my $location=$parser->get_text('/import');
 7378: 			    my $dir=$filename;
 7379: 			    $dir=~s|[^/]*$||;
 7380: 			    $location=&filelocation($dir,$location);
 7381: 			    my $metadata = 
 7382: 				&metadata($uri,'keys', $location,$unikey,
 7383: 					  $depthcount+1);
 7384: 			    foreach my $meta (split(',',$metadata)) {
 7385: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 7386: 				$metathesekeys{$meta}=1;
 7387: 			    }
 7388: 			}
 7389: 		    } else { 
 7390: 			
 7391: 			if (defined($token->[2]->{'name'})) { 
 7392: 			    $unikey.='_'.$token->[2]->{'name'}; 
 7393: 			}
 7394: 			$metathesekeys{$unikey}=1;
 7395: 			foreach my $param (@{$token->[3]}) {
 7396: 			    $metaentry{':'.$unikey.'.'.$param} =
 7397: 				$token->[2]->{$param};
 7398: 			}
 7399: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 7400: 			my $default=$metaentry{':'.$unikey.'.default'};
 7401: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 7402: 		 # only ws inside the tag, and not in default, so use default
 7403: 		 # as value
 7404: 			    $metaentry{':'.$unikey}=$default;
 7405: 			} elsif ( $internaltext =~ /\S/ ) {
 7406: 		  # something interesting inside the tag
 7407: 			    $metaentry{':'.$unikey}=$internaltext;
 7408: 			} else {
 7409: 		  # no interesting values, don't set a default
 7410: 			}
 7411: # end of not-a-package not-a-library import
 7412: 		    }
 7413: # end of not-a-package start tag
 7414: 		}
 7415: # the next is the end of "start tag"
 7416: 	    }
 7417: 	}
 7418: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 7419: 	$extension = lc($extension);
 7420: 	if ($extension eq 'htm') { $extension='html'; }
 7421: 
 7422: 	foreach my $key (keys(%packagetab)) {
 7423: 	    #no specific packages #how's our extension
 7424: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 7425: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 7426: 					 \%metathesekeys);
 7427: 	}
 7428: 
 7429: 	if (!exists($metaentry{':packages'})
 7430: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 7431: 	    foreach my $key (keys(%packagetab)) {
 7432: 		#no specific packages well let's get default then
 7433: 		if ($key!~/^default&/) { next; }
 7434: 		&metadata_create_package_def($uri,$key,'default',
 7435: 					     \%metathesekeys);
 7436: 	    }
 7437: 	}
 7438: # are there custom rights to evaluate
 7439: 	if ($metaentry{':copyright'} eq 'custom') {
 7440: 
 7441:     #
 7442:     # Importing a rights file here
 7443:     #
 7444: 	    unless ($depthcount) {
 7445: 		my $location=$metaentry{':customdistributionfile'};
 7446: 		my $dir=$filename;
 7447: 		$dir=~s|[^/]*$||;
 7448: 		$location=&filelocation($dir,$location);
 7449: 		my $rights_metadata =
 7450: 		    &metadata($uri,'keys',$location,'_rights',
 7451: 			      $depthcount+1);
 7452: 		foreach my $rights (split(',',$rights_metadata)) {
 7453: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 7454: 		    $metathesekeys{$rights}=1;
 7455: 		}
 7456: 	    }
 7457: 	}
 7458: 	# uniqifiy package listing
 7459: 	my %seen;
 7460: 	my @uniq_packages =
 7461: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 7462: 	$metaentry{':packages'} = join(',',@uniq_packages);
 7463: 
 7464: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 7465: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 7466: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 7467: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 7468: # this is the end of "was not already recently cached
 7469:     }
 7470:     return $metaentry{':'.$what};
 7471: }
 7472: 
 7473: sub metadata_create_package_def {
 7474:     my ($uri,$key,$package,$metathesekeys)=@_;
 7475:     my ($pack,$name,$subp)=split(/\&/,$key);
 7476:     if ($subp eq 'default') { next; }
 7477:     
 7478:     if (defined($metaentry{':packages'})) {
 7479: 	$metaentry{':packages'}.=','.$package;
 7480:     } else {
 7481: 	$metaentry{':packages'}=$package;
 7482:     }
 7483:     my $value=$packagetab{$key};
 7484:     my $unikey;
 7485:     $unikey='parameter_0_'.$name;
 7486:     $metaentry{':'.$unikey.'.part'}=0;
 7487:     $$metathesekeys{$unikey}=1;
 7488:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7489: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 7490:     }
 7491:     if (defined($metaentry{':'.$unikey.'.default'})) {
 7492: 	$metaentry{':'.$unikey}=
 7493: 	    $metaentry{':'.$unikey.'.default'};
 7494:     }
 7495: }
 7496: 
 7497: sub metadata_generate_part0 {
 7498:     my ($metadata,$metacache,$uri) = @_;
 7499:     my %allnames;
 7500:     foreach my $metakey (keys(%$metadata)) {
 7501: 	if ($metakey=~/^parameter\_(.*)/) {
 7502: 	  my $part=$$metacache{':'.$metakey.'.part'};
 7503: 	  my $name=$$metacache{':'.$metakey.'.name'};
 7504: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 7505: 	    $allnames{$name}=$part;
 7506: 	  }
 7507: 	}
 7508:     }
 7509:     foreach my $name (keys(%allnames)) {
 7510:       $$metadata{"parameter_0_$name"}=1;
 7511:       my $key=":parameter_0_$name";
 7512:       $$metacache{"$key.part"}='0';
 7513:       $$metacache{"$key.name"}=$name;
 7514:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 7515: 					   $allnames{$name}.'_'.$name.
 7516: 					   '.type'};
 7517:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 7518: 			     '.display'};
 7519:       my $expr='[Part: '.$allnames{$name}.']';
 7520:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 7521:       $$metacache{"$key.display"}=$olddis;
 7522:     }
 7523: }
 7524: 
 7525: # ------------------------------------------------------ Devalidate title cache
 7526: 
 7527: sub devalidate_title_cache {
 7528:     my ($url)=@_;
 7529:     if (!$env{'request.course.id'}) { return; }
 7530:     my $symb=&symbread($url);
 7531:     if (!$symb) { return; }
 7532:     my $key=$env{'request.course.id'}."\0".$symb;
 7533:     &devalidate_cache_new('title',$key);
 7534: }
 7535: 
 7536: # ------------------------------------------------- Get the title of a resource
 7537: 
 7538: sub gettitle {
 7539:     my $urlsymb=shift;
 7540:     my $symb=&symbread($urlsymb);
 7541:     if ($symb) {
 7542: 	my $key=$env{'request.course.id'}."\0".$symb;
 7543: 	my ($result,$cached)=&is_cached_new('title',$key);
 7544: 	if (defined($cached)) { 
 7545: 	    return $result;
 7546: 	}
 7547: 	my ($map,$resid,$url)=&decode_symb($symb);
 7548: 	my $title='';
 7549: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 7550: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 7551: 	} else {
 7552: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7553: 		    &GDBM_READER(),0640)) {
 7554: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 7555: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 7556: 		untie(%bighash);
 7557: 	    }
 7558: 	}
 7559: 	$title=~s/\&colon\;/\:/gs;
 7560: 	if ($title) {
 7561: 	    return &do_cache_new('title',$key,$title,600);
 7562: 	}
 7563: 	$urlsymb=$url;
 7564:     }
 7565:     my $title=&metadata($urlsymb,'title');
 7566:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 7567:     return $title;
 7568: }
 7569: 
 7570: sub get_slot {
 7571:     my ($which,$cnum,$cdom)=@_;
 7572:     if (!$cnum || !$cdom) {
 7573: 	(undef,my $courseid)=&whichuser();
 7574: 	$cdom=$env{'course.'.$courseid.'.domain'};
 7575: 	$cnum=$env{'course.'.$courseid.'.num'};
 7576:     }
 7577:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 7578:     my %slotinfo;
 7579:     if (exists($remembered{$key})) {
 7580: 	$slotinfo{$which} = $remembered{$key};
 7581:     } else {
 7582: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 7583: 	&Apache::lonhomework::showhash(%slotinfo);
 7584: 	my ($tmp)=keys(%slotinfo);
 7585: 	if ($tmp=~/^error:/) { return (); }
 7586: 	$remembered{$key} = $slotinfo{$which};
 7587:     }
 7588:     if (ref($slotinfo{$which}) eq 'HASH') {
 7589: 	return %{$slotinfo{$which}};
 7590:     }
 7591:     return $slotinfo{$which};
 7592: }
 7593: # ------------------------------------------------- Update symbolic store links
 7594: 
 7595: sub symblist {
 7596:     my ($mapname,%newhash)=@_;
 7597:     $mapname=&deversion(&declutter($mapname));
 7598:     my %hash;
 7599:     if (($env{'request.course.fn'}) && (%newhash)) {
 7600:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7601:                       &GDBM_WRCREAT(),0640)) {
 7602: 	    foreach my $url (keys %newhash) {
 7603: 		next if ($url eq 'last_known'
 7604: 			 && $env{'form.no_update_last_known'});
 7605: 		$hash{declutter($url)}=&encode_symb($mapname,
 7606: 						    $newhash{$url}->[1],
 7607: 						    $newhash{$url}->[0]);
 7608:             }
 7609:             if (untie(%hash)) {
 7610: 		return 'ok';
 7611:             }
 7612:         }
 7613:     }
 7614:     return 'error';
 7615: }
 7616: 
 7617: # --------------------------------------------------------------- Verify a symb
 7618: 
 7619: sub symbverify {
 7620:     my ($symb,$thisurl)=@_;
 7621:     my $thisfn=$thisurl;
 7622:     $thisfn=&declutter($thisfn);
 7623: # direct jump to resource in page or to a sequence - will construct own symbs
 7624:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 7625: # check URL part
 7626:     my ($map,$resid,$url)=&decode_symb($symb);
 7627: 
 7628:     unless ($url eq $thisfn) { return 0; }
 7629: 
 7630:     $symb=&symbclean($symb);
 7631:     $thisurl=&deversion($thisurl);
 7632:     $thisfn=&deversion($thisfn);
 7633: 
 7634:     my %bighash;
 7635:     my $okay=0;
 7636: 
 7637:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7638:                             &GDBM_READER(),0640)) {
 7639:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 7640:         unless ($ids) { 
 7641:            $ids=$bighash{'ids_/'.$thisurl};
 7642:         }
 7643:         if ($ids) {
 7644: # ------------------------------------------------------------------- Has ID(s)
 7645: 	    foreach my $id (split(/\,/,$ids)) {
 7646: 	       my ($mapid,$resid)=split(/\./,$id);
 7647:                if (
 7648:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 7649:    eq $symb) { 
 7650: 		   if (($env{'request.role.adv'}) ||
 7651: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 7652: 		       $okay=1; 
 7653: 		   }
 7654: 	       }
 7655: 	   }
 7656:         }
 7657: 	untie(%bighash);
 7658:     }
 7659:     return $okay;
 7660: }
 7661: 
 7662: # --------------------------------------------------------------- Clean-up symb
 7663: 
 7664: sub symbclean {
 7665:     my $symb=shift;
 7666:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7667: # remove version from map
 7668:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 7669: 
 7670: # remove version from URL
 7671:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 7672: 
 7673: # remove wrapper
 7674: 
 7675:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 7676:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 7677:     return $symb;
 7678: }
 7679: 
 7680: # ---------------------------------------------- Split symb to find map and url
 7681: 
 7682: sub encode_symb {
 7683:     my ($map,$resid,$url)=@_;
 7684:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 7685: }
 7686: 
 7687: sub decode_symb {
 7688:     my $symb=shift;
 7689:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7690:     my ($map,$resid,$url)=split(/___/,$symb);
 7691:     return (&fixversion($map),$resid,&fixversion($url));
 7692: }
 7693: 
 7694: sub fixversion {
 7695:     my $fn=shift;
 7696:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 7697:     my %bighash;
 7698:     my $uri=&clutter($fn);
 7699:     my $key=$env{'request.course.id'}.'_'.$uri;
 7700: # is this cached?
 7701:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 7702:     if (defined($cached)) { return $result; }
 7703: # unfortunately not cached, or expired
 7704:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7705: 	    &GDBM_READER(),0640)) {
 7706:  	if ($bighash{'version_'.$uri}) {
 7707:  	    my $version=$bighash{'version_'.$uri};
 7708:  	    unless (($version eq 'mostrecent') || 
 7709: 		    ($version==&getversion($uri))) {
 7710:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 7711:  	    }
 7712:  	}
 7713:  	untie %bighash;
 7714:     }
 7715:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 7716: }
 7717: 
 7718: sub deversion {
 7719:     my $url=shift;
 7720:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 7721:     return $url;
 7722: }
 7723: 
 7724: # ------------------------------------------------------ Return symb list entry
 7725: 
 7726: sub symbread {
 7727:     my ($thisfn,$donotrecurse)=@_;
 7728:     my $cache_str='request.symbread.cached.'.$thisfn;
 7729:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 7730: # no filename provided? try from environment
 7731:     unless ($thisfn) {
 7732:         if ($env{'request.symb'}) {
 7733: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 7734: 	}
 7735: 	$thisfn=$env{'request.filename'};
 7736:     }
 7737:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7738: # is that filename actually a symb? Verify, clean, and return
 7739:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 7740: 	if (&symbverify($thisfn,$1)) {
 7741: 	    return $env{$cache_str}=&symbclean($thisfn);
 7742: 	}
 7743:     }
 7744:     $thisfn=declutter($thisfn);
 7745:     my %hash;
 7746:     my %bighash;
 7747:     my $syval='';
 7748:     if (($env{'request.course.fn'}) && ($thisfn)) {
 7749:         my $targetfn = $thisfn;
 7750:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 7751:             $targetfn = 'adm/wrapper/'.$thisfn;
 7752:         }
 7753: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 7754: 	    $targetfn=$1;
 7755: 	}
 7756:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7757:                       &GDBM_READER(),0640)) {
 7758: 	    $syval=$hash{$targetfn};
 7759:             untie(%hash);
 7760:         }
 7761: # ---------------------------------------------------------- There was an entry
 7762:         if ($syval) {
 7763: 	    #unless ($syval=~/\_\d+$/) {
 7764: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 7765: 		    #&appenv({'request.ambiguous' => $thisfn});
 7766: 		    #return $env{$cache_str}='';
 7767: 		#}    
 7768: 		#$syval.=$1;
 7769: 	    #}
 7770:         } else {
 7771: # ------------------------------------------------------- Was not in symb table
 7772:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7773:                             &GDBM_READER(),0640)) {
 7774: # ---------------------------------------------- Get ID(s) for current resource
 7775:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 7776:               unless ($ids) { 
 7777:                  $ids=$bighash{'ids_/'.$thisfn};
 7778:               }
 7779:               unless ($ids) {
 7780: # alias?
 7781: 		  $ids=$bighash{'mapalias_'.$thisfn};
 7782:               }
 7783:               if ($ids) {
 7784: # ------------------------------------------------------------------- Has ID(s)
 7785:                  my @possibilities=split(/\,/,$ids);
 7786:                  if ($#possibilities==0) {
 7787: # ----------------------------------------------- There is only one possibility
 7788: 		     my ($mapid,$resid)=split(/\./,$ids);
 7789: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7790: 						    $resid,$thisfn);
 7791:                  } elsif (!$donotrecurse) {
 7792: # ------------------------------------------ There is more than one possibility
 7793:                      my $realpossible=0;
 7794:                      foreach my $id (@possibilities) {
 7795: 			 my $file=$bighash{'src_'.$id};
 7796:                          if (&allowed('bre',$file)) {
 7797:          		    my ($mapid,$resid)=split(/\./,$id);
 7798:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 7799: 				$realpossible++;
 7800:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7801: 						    $resid,$thisfn);
 7802:                             }
 7803: 			 }
 7804:                      }
 7805: 		     if ($realpossible!=1) { $syval=''; }
 7806:                  } else {
 7807:                      $syval='';
 7808:                  }
 7809: 	      }
 7810:               untie(%bighash)
 7811:            }
 7812:         }
 7813:         if ($syval) {
 7814: 	    return $env{$cache_str}=$syval;
 7815:         }
 7816:     }
 7817:     &appenv({'request.ambiguous' => $thisfn});
 7818:     return $env{$cache_str}='';
 7819: }
 7820: 
 7821: # ---------------------------------------------------------- Return random seed
 7822: 
 7823: sub numval {
 7824:     my $txt=shift;
 7825:     $txt=~tr/A-J/0-9/;
 7826:     $txt=~tr/a-j/0-9/;
 7827:     $txt=~tr/K-T/0-9/;
 7828:     $txt=~tr/k-t/0-9/;
 7829:     $txt=~tr/U-Z/0-5/;
 7830:     $txt=~tr/u-z/0-5/;
 7831:     $txt=~s/\D//g;
 7832:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 7833:     return int($txt);
 7834: }
 7835: 
 7836: sub numval2 {
 7837:     my $txt=shift;
 7838:     $txt=~tr/A-J/0-9/;
 7839:     $txt=~tr/a-j/0-9/;
 7840:     $txt=~tr/K-T/0-9/;
 7841:     $txt=~tr/k-t/0-9/;
 7842:     $txt=~tr/U-Z/0-5/;
 7843:     $txt=~tr/u-z/0-5/;
 7844:     $txt=~s/\D//g;
 7845:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7846:     my $total;
 7847:     foreach my $val (@txts) { $total+=$val; }
 7848:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 7849:     return int($total);
 7850: }
 7851: 
 7852: sub numval3 {
 7853:     use integer;
 7854:     my $txt=shift;
 7855:     $txt=~tr/A-J/0-9/;
 7856:     $txt=~tr/a-j/0-9/;
 7857:     $txt=~tr/K-T/0-9/;
 7858:     $txt=~tr/k-t/0-9/;
 7859:     $txt=~tr/U-Z/0-5/;
 7860:     $txt=~tr/u-z/0-5/;
 7861:     $txt=~s/\D//g;
 7862:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7863:     my $total;
 7864:     foreach my $val (@txts) { $total+=$val; }
 7865:     if ($_64bit) { $total=(($total<<32)>>32); }
 7866:     return $total;
 7867: }
 7868: 
 7869: sub digest {
 7870:     my ($data)=@_;
 7871:     my $digest=&Digest::MD5::md5($data);
 7872:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 7873:     my ($e,$f);
 7874:     {
 7875:         use integer;
 7876:         $e=($a+$b);
 7877:         $f=($c+$d);
 7878:         if ($_64bit) {
 7879:             $e=(($e<<32)>>32);
 7880:             $f=(($f<<32)>>32);
 7881:         }
 7882:     }
 7883:     if (wantarray) {
 7884: 	return ($e,$f);
 7885:     } else {
 7886: 	my $g;
 7887: 	{
 7888: 	    use integer;
 7889: 	    $g=($e+$f);
 7890: 	    if ($_64bit) {
 7891: 		$g=(($g<<32)>>32);
 7892: 	    }
 7893: 	}
 7894: 	return $g;
 7895:     }
 7896: }
 7897: 
 7898: sub latest_rnd_algorithm_id {
 7899:     return '64bit5';
 7900: }
 7901: 
 7902: sub get_rand_alg {
 7903:     my ($courseid)=@_;
 7904:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 7905:     if ($courseid) {
 7906: 	return $env{"course.$courseid.rndseed"};
 7907:     }
 7908:     return &latest_rnd_algorithm_id();
 7909: }
 7910: 
 7911: sub validCODE {
 7912:     my ($CODE)=@_;
 7913:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 7914:     return 0;
 7915: }
 7916: 
 7917: sub getCODE {
 7918:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 7919:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 7920: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 7921: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 7922: 	return $Apache::lonhomework::history{'resource.CODE'};
 7923:     }
 7924:     return undef;
 7925: }
 7926: 
 7927: sub rndseed {
 7928:     my ($symb,$courseid,$domain,$username)=@_;
 7929:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 7930:     if (!defined($symb)) {
 7931: 	unless ($symb=$wsymb) { return time; }
 7932:     }
 7933:     if (!$courseid) { $courseid=$wcourseid; }
 7934:     if (!$domain) { $domain=$wdomain; }
 7935:     if (!$username) { $username=$wusername }
 7936:     my $which=&get_rand_alg();
 7937: 
 7938:     if (defined(&getCODE())) {
 7939: 	if ($which eq '64bit5') {
 7940: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 7941: 	} elsif ($which eq '64bit4') {
 7942: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 7943: 	} else {
 7944: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 7945: 	}
 7946:     } elsif ($which eq '64bit5') {
 7947: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 7948:     } elsif ($which eq '64bit4') {
 7949: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 7950:     } elsif ($which eq '64bit3') {
 7951: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 7952:     } elsif ($which eq '64bit2') {
 7953: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 7954:     } elsif ($which eq '64bit') {
 7955: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 7956:     }
 7957:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 7958: }
 7959: 
 7960: sub rndseed_32bit {
 7961:     my ($symb,$courseid,$domain,$username)=@_;
 7962:     {
 7963: 	use integer;
 7964: 	my $symbchck=unpack("%32C*",$symb) << 27;
 7965: 	my $symbseed=numval($symb) << 22;
 7966: 	my $namechck=unpack("%32C*",$username) << 17;
 7967: 	my $nameseed=numval($username) << 12;
 7968: 	my $domainseed=unpack("%32C*",$domain) << 7;
 7969: 	my $courseseed=unpack("%32C*",$courseid);
 7970: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 7971: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7972: 	#&logthis("rndseed :$num:$symb");
 7973: 	if ($_64bit) { $num=(($num<<32)>>32); }
 7974: 	return $num;
 7975:     }
 7976: }
 7977: 
 7978: sub rndseed_64bit {
 7979:     my ($symb,$courseid,$domain,$username)=@_;
 7980:     {
 7981: 	use integer;
 7982: 	my $symbchck=unpack("%32S*",$symb) << 21;
 7983: 	my $symbseed=numval($symb) << 10;
 7984: 	my $namechck=unpack("%32S*",$username);
 7985: 	
 7986: 	my $nameseed=numval($username) << 21;
 7987: 	my $domainseed=unpack("%32S*",$domain) << 10;
 7988: 	my $courseseed=unpack("%32S*",$courseid);
 7989: 	
 7990: 	my $num1=$symbchck+$symbseed+$namechck;
 7991: 	my $num2=$nameseed+$domainseed+$courseseed;
 7992: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7993: 	#&logthis("rndseed :$num:$symb");
 7994: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7995: 	return "$num1,$num2";
 7996:     }
 7997: }
 7998: 
 7999: sub rndseed_64bit2 {
 8000:     my ($symb,$courseid,$domain,$username)=@_;
 8001:     {
 8002: 	use integer;
 8003: 	# strings need to be an even # of cahracters long, it it is odd the
 8004:         # last characters gets thrown away
 8005: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8006: 	my $symbseed=numval($symb) << 10;
 8007: 	my $namechck=unpack("%32S*",$username.' ');
 8008: 	
 8009: 	my $nameseed=numval($username) << 21;
 8010: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8011: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8012: 	
 8013: 	my $num1=$symbchck+$symbseed+$namechck;
 8014: 	my $num2=$nameseed+$domainseed+$courseseed;
 8015: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8016: 	#&logthis("rndseed :$num:$symb");
 8017: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8018: 	return "$num1,$num2";
 8019:     }
 8020: }
 8021: 
 8022: sub rndseed_64bit3 {
 8023:     my ($symb,$courseid,$domain,$username)=@_;
 8024:     {
 8025: 	use integer;
 8026: 	# strings need to be an even # of cahracters long, it it is odd the
 8027:         # last characters gets thrown away
 8028: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8029: 	my $symbseed=numval2($symb) << 10;
 8030: 	my $namechck=unpack("%32S*",$username.' ');
 8031: 	
 8032: 	my $nameseed=numval2($username) << 21;
 8033: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8034: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8035: 	
 8036: 	my $num1=$symbchck+$symbseed+$namechck;
 8037: 	my $num2=$nameseed+$domainseed+$courseseed;
 8038: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8039: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8040: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8041: 	
 8042: 	return "$num1:$num2";
 8043:     }
 8044: }
 8045: 
 8046: sub rndseed_64bit4 {
 8047:     my ($symb,$courseid,$domain,$username)=@_;
 8048:     {
 8049: 	use integer;
 8050: 	# strings need to be an even # of cahracters long, it it is odd the
 8051:         # last characters gets thrown away
 8052: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8053: 	my $symbseed=numval3($symb) << 10;
 8054: 	my $namechck=unpack("%32S*",$username.' ');
 8055: 	
 8056: 	my $nameseed=numval3($username) << 21;
 8057: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8058: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8059: 	
 8060: 	my $num1=$symbchck+$symbseed+$namechck;
 8061: 	my $num2=$nameseed+$domainseed+$courseseed;
 8062: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8063: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8064: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8065: 	
 8066: 	return "$num1:$num2";
 8067:     }
 8068: }
 8069: 
 8070: sub rndseed_64bit5 {
 8071:     my ($symb,$courseid,$domain,$username)=@_;
 8072:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 8073:     return "$num1:$num2";
 8074: }
 8075: 
 8076: sub rndseed_CODE_64bit {
 8077:     my ($symb,$courseid,$domain,$username)=@_;
 8078:     {
 8079: 	use integer;
 8080: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8081: 	my $symbseed=numval2($symb);
 8082: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8083: 	my $CODEseed=numval(&getCODE());
 8084: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8085: 	my $num1=$symbseed+$CODEchck;
 8086: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8087: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8088: 	#&logthis("rndseed :$num1:$num2:$symb");
 8089: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8090: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8091: 	return "$num1:$num2";
 8092:     }
 8093: }
 8094: 
 8095: sub rndseed_CODE_64bit4 {
 8096:     my ($symb,$courseid,$domain,$username)=@_;
 8097:     {
 8098: 	use integer;
 8099: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8100: 	my $symbseed=numval3($symb);
 8101: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8102: 	my $CODEseed=numval3(&getCODE());
 8103: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8104: 	my $num1=$symbseed+$CODEchck;
 8105: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8106: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8107: 	#&logthis("rndseed :$num1:$num2:$symb");
 8108: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8109: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8110: 	return "$num1:$num2";
 8111:     }
 8112: }
 8113: 
 8114: sub rndseed_CODE_64bit5 {
 8115:     my ($symb,$courseid,$domain,$username)=@_;
 8116:     my $code = &getCODE();
 8117:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 8118:     return "$num1:$num2";
 8119: }
 8120: 
 8121: sub setup_random_from_rndseed {
 8122:     my ($rndseed)=@_;
 8123:     if ($rndseed =~/([,:])/) {
 8124: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 8125: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 8126:     } else {
 8127: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 8128:     }
 8129: }
 8130: 
 8131: sub latest_receipt_algorithm_id {
 8132:     return 'receipt3';
 8133: }
 8134: 
 8135: sub recunique {
 8136:     my $fucourseid=shift;
 8137:     my $unique;
 8138:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 8139: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8140: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 8141:     } else {
 8142: 	$unique=$perlvar{'lonReceipt'};
 8143:     }
 8144:     return unpack("%32C*",$unique);
 8145: }
 8146: 
 8147: sub recprefix {
 8148:     my $fucourseid=shift;
 8149:     my $prefix;
 8150:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 8151: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8152: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 8153:     } else {
 8154: 	$prefix=$perlvar{'lonHostID'};
 8155:     }
 8156:     return unpack("%32C*",$prefix);
 8157: }
 8158: 
 8159: sub ireceipt {
 8160:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 8161: 
 8162:     my $return =&recprefix($fucourseid).'-';
 8163: 
 8164:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 8165: 	$env{'request.state'} eq 'construct') {
 8166: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 8167: 	return $return;
 8168:     }
 8169: 
 8170:     my $cuname=unpack("%32C*",$funame);
 8171:     my $cudom=unpack("%32C*",$fudom);
 8172:     my $cucourseid=unpack("%32C*",$fucourseid);
 8173:     my $cusymb=unpack("%32C*",$fusymb);
 8174:     my $cunique=&recunique($fucourseid);
 8175:     my $cpart=unpack("%32S*",$part);
 8176:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 8177: 
 8178: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 8179: 			       
 8180: 	$return.= ($cunique%$cuname+
 8181: 		   $cunique%$cudom+
 8182: 		   $cusymb%$cuname+
 8183: 		   $cusymb%$cudom+
 8184: 		   $cucourseid%$cuname+
 8185: 		   $cucourseid%$cudom+
 8186: 		   $cpart%$cuname+
 8187: 		   $cpart%$cudom);
 8188:     } else {
 8189: 	$return.= ($cunique%$cuname+
 8190: 		   $cunique%$cudom+
 8191: 		   $cusymb%$cuname+
 8192: 		   $cusymb%$cudom+
 8193: 		   $cucourseid%$cuname+
 8194: 		   $cucourseid%$cudom);
 8195:     }
 8196:     return $return;
 8197: }
 8198: 
 8199: sub receipt {
 8200:     my ($part)=@_;
 8201:     my ($symb,$courseid,$domain,$name) = &whichuser();
 8202:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 8203: }
 8204: 
 8205: sub whichuser {
 8206:     my ($passedsymb)=@_;
 8207:     my ($symb,$courseid,$domain,$name,$publicuser);
 8208:     if (defined($env{'form.grade_symb'})) {
 8209: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 8210: 	my $allowed=&allowed('vgr',$tmp_courseid);
 8211: 	if (!$allowed &&
 8212: 	    exists($env{'request.course.sec'}) &&
 8213: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 8214: 	    $allowed=&allowed('vgr',$tmp_courseid.
 8215: 			      '/'.$env{'request.course.sec'});
 8216: 	}
 8217: 	if ($allowed) {
 8218: 	    ($symb)=&get_env_multiple('form.grade_symb');
 8219: 	    $courseid=$tmp_courseid;
 8220: 	    ($domain)=&get_env_multiple('form.grade_domain');
 8221: 	    ($name)=&get_env_multiple('form.grade_username');
 8222: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 8223: 	}
 8224:     }
 8225:     if (!$passedsymb) {
 8226: 	$symb=&symbread();
 8227:     } else {
 8228: 	$symb=$passedsymb;
 8229:     }
 8230:     $courseid=$env{'request.course.id'};
 8231:     $domain=$env{'user.domain'};
 8232:     $name=$env{'user.name'};
 8233:     if ($name eq 'public' && $domain eq 'public') {
 8234: 	if (!defined($env{'form.username'})) {
 8235: 	    $env{'form.username'}.=time.rand(10000000);
 8236: 	}
 8237: 	$name.=$env{'form.username'};
 8238:     }
 8239:     return ($symb,$courseid,$domain,$name,$publicuser);
 8240: 
 8241: }
 8242: 
 8243: # ------------------------------------------------------------ Serves up a file
 8244: # returns either the contents of the file or 
 8245: # -1 if the file doesn't exist
 8246: #
 8247: # if the target is a file that was uploaded via DOCS, 
 8248: # a check will be made to see if a current copy exists on the local server,
 8249: # if it does this will be served, otherwise a copy will be retrieved from
 8250: # the home server for the course and stored in /home/httpd/html/userfiles on
 8251: # the local server.   
 8252: 
 8253: sub getfile {
 8254:     my ($file) = @_;
 8255:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8256:     &repcopy($file);
 8257:     return &readfile($file);
 8258: }
 8259: 
 8260: sub repcopy_userfile {
 8261:     my ($file)=@_;
 8262:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8263:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 8264:     my ($cdom,$cnum,$filename) = 
 8265: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 8266:     my $uri="/uploaded/$cdom/$cnum/$filename";
 8267:     if (-e "$file") {
 8268: # we already have a local copy, check it out
 8269: 	my @fileinfo = stat($file);
 8270: 	my $rtncode;
 8271: 	my $info;
 8272: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 8273: 	if ($lwpresp ne 'ok') {
 8274: # there is no such file anymore, even though we had a local copy
 8275: 	    if ($rtncode eq '404') {
 8276: 		unlink($file);
 8277: 	    }
 8278: 	    return -1;
 8279: 	}
 8280: 	if ($info < $fileinfo[9]) {
 8281: # nice, the file we have is up-to-date, just say okay
 8282: 	    return 'ok';
 8283: 	} else {
 8284: # the file is outdated, get rid of it
 8285: 	    unlink($file);
 8286: 	}
 8287:     }
 8288: # one way or the other, at this point, we don't have the file
 8289: # construct the correct path for the file
 8290:     my @parts = ($cdom,$cnum); 
 8291:     if ($filename =~ m|^(.+)/[^/]+$|) {
 8292: 	push @parts, split(/\//,$1);
 8293:     }
 8294:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 8295:     foreach my $part (@parts) {
 8296: 	$path .= '/'.$part;
 8297: 	if (!-e $path) {
 8298: 	    mkdir($path,0770);
 8299: 	}
 8300:     }
 8301: # now the path exists for sure
 8302: # get a user agent
 8303:     my $ua=new LWP::UserAgent;
 8304:     my $transferfile=$file.'.in.transfer';
 8305: # FIXME: this should flock
 8306:     if (-e $transferfile) { return 'ok'; }
 8307:     my $request;
 8308:     $uri=~s/^\///;
 8309:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
 8310:     my $response=$ua->request($request,$transferfile);
 8311: # did it work?
 8312:     if ($response->is_error()) {
 8313: 	unlink($transferfile);
 8314: 	&logthis("Userfile repcopy failed for $uri");
 8315: 	return -1;
 8316:     }
 8317: # worked, rename the transfer file
 8318:     rename($transferfile,$file);
 8319:     return 'ok';
 8320: }
 8321: 
 8322: sub tokenwrapper {
 8323:     my $uri=shift;
 8324:     $uri=~s|^http\://([^/]+)||;
 8325:     $uri=~s|^/||;
 8326:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 8327:     my $token=$1;
 8328:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 8329:     if ($udom && $uname && $file) {
 8330: 	$file=~s|(\?\.*)*$||;
 8331:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 8332:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
 8333:                (($uri=~/\?/)?'&':'?').'token='.$token.
 8334:                                '&tokenissued='.$perlvar{'lonHostID'};
 8335:     } else {
 8336:         return '/adm/notfound.html';
 8337:     }
 8338: }
 8339: 
 8340: # call with reqtype HEAD: get last modification time
 8341: # call with reqtype GET: get the file contents
 8342: # Do not call this with reqtype GET for large files! It loads everything into memory
 8343: #
 8344: sub getuploaded {
 8345:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 8346:     $uri=~s/^\///;
 8347:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
 8348:     my $ua=new LWP::UserAgent;
 8349:     my $request=new HTTP::Request($reqtype,$uri);
 8350:     my $response=$ua->request($request);
 8351:     $$rtncode = $response->code;
 8352:     if (! $response->is_success()) {
 8353: 	return 'failed';
 8354:     }      
 8355:     if ($reqtype eq 'HEAD') {
 8356: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 8357:     } elsif ($reqtype eq 'GET') {
 8358: 	$$info = $response->content;
 8359:     }
 8360:     return 'ok';
 8361: }
 8362: 
 8363: sub readfile {
 8364:     my $file = shift;
 8365:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 8366:     my $fh;
 8367:     open($fh,"<$file");
 8368:     my $a='';
 8369:     while (my $line = <$fh>) { $a .= $line; }
 8370:     return $a;
 8371: }
 8372: 
 8373: sub filelocation {
 8374:     my ($dir,$file) = @_;
 8375:     my $location;
 8376:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 8377: 
 8378:     if ($file =~ m-^/adm/-) {
 8379: 	$file=~s-^/adm/wrapper/-/-;
 8380: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8381:     }
 8382: 
 8383:     if ($file=~m:^/~:) { # is a contruction space reference
 8384:         $location = $file;
 8385:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 8386:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 8387: 	# is a correct contruction space reference
 8388:         $location = $file;
 8389:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
 8390:         $location = $file;
 8391:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 8392:         my ($udom,$uname,$filename)=
 8393:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 8394:         my $home=&homeserver($uname,$udom);
 8395:         my $is_me=0;
 8396:         my @ids=&current_machine_ids();
 8397:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 8398:         if ($is_me) {
 8399:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
 8400:         } else {
 8401:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 8402:   	      $udom.'/'.$uname.'/'.$filename;
 8403:         }
 8404:     } elsif ($file =~ m-^/adm/-) {
 8405: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 8406:     } else {
 8407:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8408:         $file=~s:^/res/:/:;
 8409:         if ( !( $file =~ m:^/:) ) {
 8410:             $location = $dir. '/'.$file;
 8411:         } else {
 8412:             $location = '/home/httpd/html/res'.$file;
 8413:         }
 8414:     }
 8415:     $location=~s://+:/:g; # remove duplicate /
 8416:     while ($location=~m{/\.\./}) {
 8417: 	if ($location =~ m{/[^/]+/\.\./}) {
 8418: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 8419: 	} else {
 8420: 	    $location=~ s{/\.\./}{/}g;
 8421: 	}
 8422:     } #remove dir/..
 8423:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 8424:     return $location;
 8425: }
 8426: 
 8427: sub hreflocation {
 8428:     my ($dir,$file)=@_;
 8429:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 8430: 	$file=filelocation($dir,$file);
 8431:     } elsif ($file=~m-^/adm/-) {
 8432: 	$file=~s-^/adm/wrapper/-/-;
 8433: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8434:     }
 8435:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 8436: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 8437:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 8438: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 8439:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 8440: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 8441: 	    -/uploaded/$1/$2/-x;
 8442:     }
 8443:     if ($file=~ m{^/userfiles/}) {
 8444: 	$file =~ s{^/userfiles/}{/uploaded/};
 8445:     }
 8446:     return $file;
 8447: }
 8448: 
 8449: sub current_machine_domains {
 8450:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 8451: }
 8452: 
 8453: sub machine_domains {
 8454:     my ($hostname) = @_;
 8455:     my @domains;
 8456:     my %hostname = &all_hostnames();
 8457:     while( my($id, $name) = each(%hostname)) {
 8458: #	&logthis("-$id-$name-$hostname-");
 8459: 	if ($hostname eq $name) {
 8460: 	    push(@domains,&host_domain($id));
 8461: 	}
 8462:     }
 8463:     return @domains;
 8464: }
 8465: 
 8466: sub current_machine_ids {
 8467:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 8468: }
 8469: 
 8470: sub machine_ids {
 8471:     my ($hostname) = @_;
 8472:     $hostname ||= &hostname($perlvar{'lonHostID'});
 8473:     my @ids;
 8474:     my %name_to_host = &all_names();
 8475:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 8476: 	return @{ $name_to_host{$hostname} };
 8477:     }
 8478:     return;
 8479: }
 8480: 
 8481: sub additional_machine_domains {
 8482:     my @domains;
 8483:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 8484:     while( my $line = <$fh>) {
 8485:         $line =~ s/\s//g;
 8486:         push(@domains,$line);
 8487:     }
 8488:     return @domains;
 8489: }
 8490: 
 8491: sub default_login_domain {
 8492:     my $domain = $perlvar{'lonDefDomain'};
 8493:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 8494:     foreach my $posdom (&current_machine_domains(),
 8495:                         &additional_machine_domains()) {
 8496:         if (lc($posdom) eq lc($testdomain)) {
 8497:             $domain=$posdom;
 8498:             last;
 8499:         }
 8500:     }
 8501:     return $domain;
 8502: }
 8503: 
 8504: # ------------------------------------------------------------- Declutters URLs
 8505: 
 8506: sub declutter {
 8507:     my $thisfn=shift;
 8508:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8509:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8510:     $thisfn=~s/^\///;
 8511:     $thisfn=~s|^adm/wrapper/||;
 8512:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 8513:     $thisfn=~s/^res\///;
 8514:     $thisfn=~s/\?.+$//;
 8515:     return $thisfn;
 8516: }
 8517: 
 8518: # ------------------------------------------------------------- Clutter up URLs
 8519: 
 8520: sub clutter {
 8521:     my $thisfn='/'.&declutter(shift);
 8522:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 8523: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 8524:        $thisfn='/res'.$thisfn; 
 8525:     }
 8526:     if ($thisfn !~m|/adm|) {
 8527: 	if ($thisfn =~ m|/ext/|) {
 8528: 	    $thisfn='/adm/wrapper'.$thisfn;
 8529: 	} else {
 8530: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 8531: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 8532: 	    if ($embstyle eq 'ssi'
 8533: 		|| ($embstyle eq 'hdn')
 8534: 		|| ($embstyle eq 'rat')
 8535: 		|| ($embstyle eq 'prv')
 8536: 		|| ($embstyle eq 'ign')) {
 8537: 		#do nothing with these
 8538: 	    } elsif (($embstyle eq 'img') 
 8539: 		|| ($embstyle eq 'emb')
 8540: 		|| ($embstyle eq 'wrp')) {
 8541: 		$thisfn='/adm/wrapper'.$thisfn;
 8542: 	    } elsif ($embstyle eq 'unk'
 8543: 		     && $thisfn!~/\.(sequence|page)$/) {
 8544: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 8545: 	    } else {
 8546: #		&logthis("Got a blank emb style");
 8547: 	    }
 8548: 	}
 8549:     }
 8550:     return $thisfn;
 8551: }
 8552: 
 8553: sub clutter_with_no_wrapper {
 8554:     my $uri = &clutter(shift);
 8555:     if ($uri =~ m-^/adm/-) {
 8556: 	$uri =~ s-^/adm/wrapper/-/-;
 8557: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 8558:     }
 8559:     return $uri;
 8560: }
 8561: 
 8562: sub freeze_escape {
 8563:     my ($value)=@_;
 8564:     if (ref($value)) {
 8565: 	$value=&nfreeze($value);
 8566: 	return '__FROZEN__'.&escape($value);
 8567:     }
 8568:     return &escape($value);
 8569: }
 8570: 
 8571: 
 8572: sub thaw_unescape {
 8573:     my ($value)=@_;
 8574:     if ($value =~ /^__FROZEN__/) {
 8575: 	substr($value,0,10,undef);
 8576: 	$value=&unescape($value);
 8577: 	return &thaw($value);
 8578:     }
 8579:     return &unescape($value);
 8580: }
 8581: 
 8582: sub correct_line_ends {
 8583:     my ($result)=@_;
 8584:     $$result =~s/\r\n/\n/mg;
 8585:     $$result =~s/\r/\n/mg;
 8586: }
 8587: # ================================================================ Main Program
 8588: 
 8589: sub goodbye {
 8590:    &logthis("Starting Shut down");
 8591: #not converted to using infrastruture and probably shouldn't be
 8592:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 8593: #converted
 8594: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 8595:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 8596: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 8597: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 8598: #1.1 only
 8599: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 8600: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 8601: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 8602: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 8603:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 8604:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 8605:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 8606:    &flushcourselogs();
 8607:    &logthis("Shutting down");
 8608: }
 8609: 
 8610: sub get_dns {
 8611:     my ($url,$func,$ignore_cache) = @_;
 8612:     if (!$ignore_cache) {
 8613: 	my ($content,$cached)=
 8614: 	    &Apache::lonnet::is_cached_new('dns',$url);
 8615: 	if ($cached) {
 8616: 	    &$func($content);
 8617: 	    return;
 8618: 	}
 8619:     }
 8620: 
 8621:     my %alldns;
 8622:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8623:     foreach my $dns (<$config>) {
 8624: 	next if ($dns !~ /^\^(\S*)/x);
 8625: 	$alldns{$1} = 1;
 8626:     }
 8627:     while (%alldns) {
 8628: 	my ($dns) = keys(%alldns);
 8629: 	delete($alldns{$dns});
 8630: 	my $ua=new LWP::UserAgent;
 8631: 	my $request=new HTTP::Request('GET',"http://$dns$url");
 8632: 	my $response=$ua->request($request);
 8633: 	next if ($response->is_error());
 8634: 	my @content = split("\n",$response->content);
 8635: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 8636: 	&$func(\@content);
 8637: 	return;
 8638:     }
 8639:     close($config);
 8640:     my $which = (split('/',$url))[3];
 8641:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 8642:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 8643:     my @content = <$config>;
 8644:     &$func(\@content);
 8645:     return;
 8646: }
 8647: # ------------------------------------------------------------ Read domain file
 8648: {
 8649:     my $loaded;
 8650:     my %domain;
 8651: 
 8652:     sub parse_domain_tab {
 8653: 	my ($lines) = @_;
 8654: 	foreach my $line (@$lines) {
 8655: 	    next if ($line =~ /^(\#|\s*$ )/x);
 8656: 
 8657: 	    chomp($line);
 8658: 	    my ($name,@elements) = split(/:/,$line,9);
 8659: 	    my %this_domain;
 8660: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 8661: 			       'lang_def', 'city', 'longi', 'lati',
 8662: 			       'primary') {
 8663: 		$this_domain{$field} = shift(@elements);
 8664: 	    }
 8665: 	    $domain{$name} = \%this_domain;
 8666: 	}
 8667:     }
 8668: 
 8669:     sub reset_domain_info {
 8670: 	undef($loaded);
 8671: 	undef(%domain);
 8672:     }
 8673: 
 8674:     sub load_domain_tab {
 8675: 	my ($ignore_cache) = @_;
 8676: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 8677: 	my $fh;
 8678: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 8679: 	    my @lines = <$fh>;
 8680: 	    &parse_domain_tab(\@lines);
 8681: 	}
 8682: 	close($fh);
 8683: 	$loaded = 1;
 8684:     }
 8685: 
 8686:     sub domain {
 8687: 	&load_domain_tab() if (!$loaded);
 8688: 
 8689: 	my ($name,$what) = @_;
 8690: 	return if ( !exists($domain{$name}) );
 8691: 
 8692: 	if (!$what) {
 8693: 	    return $domain{$name}{'description'};
 8694: 	}
 8695: 	return $domain{$name}{$what};
 8696:     }
 8697: 
 8698:     sub domain_info {
 8699:         &load_domain_tab() if (!$loaded);
 8700:         return %domain;
 8701:     }
 8702: 
 8703: }
 8704: 
 8705: 
 8706: # ------------------------------------------------------------- Read hosts file
 8707: {
 8708:     my %hostname;
 8709:     my %hostdom;
 8710:     my %libserv;
 8711:     my $loaded;
 8712:     my %name_to_host;
 8713: 
 8714:     sub parse_hosts_tab {
 8715: 	my ($file) = @_;
 8716: 	foreach my $configline (@$file) {
 8717: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 8718: 	    next if ($configline =~ /^\^/);
 8719: 	    chomp($configline);
 8720: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
 8721: 	    $name=~s/\s//g;
 8722: 	    if ($id && $domain && $role && $name) {
 8723: 		$hostname{$id}=$name;
 8724: 		push(@{$name_to_host{$name}}, $id);
 8725: 		$hostdom{$id}=$domain;
 8726: 		if ($role eq 'library') { $libserv{$id}=$name; }
 8727:                 if (defined($protocol)) {
 8728:                     if ($protocol eq 'https') {
 8729:                         $protocol{$id} = $protocol;
 8730:                     } else {
 8731:                         $protocol{$id} = 'http'; 
 8732:                     }
 8733:                 } else {
 8734:                     $protocol{$id} = 'http';
 8735:                 }
 8736: 	    }
 8737: 	}
 8738:     }
 8739:     
 8740:     sub reset_hosts_info {
 8741: 	&purge_remembered();
 8742: 	&reset_domain_info();
 8743: 	&reset_hosts_ip_info();
 8744: 	undef(%name_to_host);
 8745: 	undef(%hostname);
 8746: 	undef(%hostdom);
 8747: 	undef(%libserv);
 8748: 	undef($loaded);
 8749:     }
 8750: 
 8751:     sub load_hosts_tab {
 8752: 	my ($ignore_cache) = @_;
 8753: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 8754: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8755: 	my @config = <$config>;
 8756: 	&parse_hosts_tab(\@config);
 8757: 	close($config);
 8758: 	$loaded=1;
 8759:     }
 8760: 
 8761:     sub hostname {
 8762: 	&load_hosts_tab() if (!$loaded);
 8763: 
 8764: 	my ($lonid) = @_;
 8765: 	return $hostname{$lonid};
 8766:     }
 8767: 
 8768:     sub all_hostnames {
 8769: 	&load_hosts_tab() if (!$loaded);
 8770: 
 8771: 	return %hostname;
 8772:     }
 8773: 
 8774:     sub all_names {
 8775: 	&load_hosts_tab() if (!$loaded);
 8776: 
 8777: 	return %name_to_host;
 8778:     }
 8779: 
 8780:     sub all_host_domain {
 8781:         &load_hosts_tab() if (!$loaded);
 8782:         return %hostdom;
 8783:     }
 8784: 
 8785:     sub is_library {
 8786: 	&load_hosts_tab() if (!$loaded);
 8787: 
 8788: 	return exists($libserv{$_[0]});
 8789:     }
 8790: 
 8791:     sub all_library {
 8792: 	&load_hosts_tab() if (!$loaded);
 8793: 
 8794: 	return %libserv;
 8795:     }
 8796: 
 8797:     sub get_servers {
 8798: 	&load_hosts_tab() if (!$loaded);
 8799: 
 8800: 	my ($domain,$type) = @_;
 8801: 	my %possible_hosts = ($type eq 'library') ? %libserv
 8802: 	                                          : %hostname;
 8803: 	my %result;
 8804: 	if (ref($domain) eq 'ARRAY') {
 8805: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8806: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 8807: 		    $result{$host} = $hostname;
 8808: 		}
 8809: 	    }
 8810: 	} else {
 8811: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8812: 		if ($hostdom{$host} eq $domain) {
 8813: 		    $result{$host} = $hostname;
 8814: 		}
 8815: 	    }
 8816: 	}
 8817: 	return %result;
 8818:     }
 8819: 
 8820:     sub host_domain {
 8821: 	&load_hosts_tab() if (!$loaded);
 8822: 
 8823: 	my ($lonid) = @_;
 8824: 	return $hostdom{$lonid};
 8825:     }
 8826: 
 8827:     sub all_domains {
 8828: 	&load_hosts_tab() if (!$loaded);
 8829: 
 8830: 	my %seen;
 8831: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 8832: 	return @uniq;
 8833:     }
 8834: }
 8835: 
 8836: { 
 8837:     my %iphost;
 8838:     my %name_to_ip;
 8839:     my %lonid_to_ip;
 8840: 
 8841:     sub get_hosts_from_ip {
 8842: 	my ($ip) = @_;
 8843: 	my %iphosts = &get_iphost();
 8844: 	if (ref($iphosts{$ip})) {
 8845: 	    return @{$iphosts{$ip}};
 8846: 	}
 8847: 	return;
 8848:     }
 8849:     
 8850:     sub reset_hosts_ip_info {
 8851: 	undef(%iphost);
 8852: 	undef(%name_to_ip);
 8853: 	undef(%lonid_to_ip);
 8854:     }
 8855: 
 8856:     sub get_host_ip {
 8857: 	my ($lonid) = @_;
 8858: 	if (exists($lonid_to_ip{$lonid})) {
 8859: 	    return $lonid_to_ip{$lonid};
 8860: 	}
 8861: 	my $name=&hostname($lonid);
 8862:    	my $ip = gethostbyname($name);
 8863: 	return if (!$ip || length($ip) ne 4);
 8864: 	$ip=inet_ntoa($ip);
 8865: 	$name_to_ip{$name}   = $ip;
 8866: 	$lonid_to_ip{$lonid} = $ip;
 8867: 	return $ip;
 8868:     }
 8869:     
 8870:     sub get_iphost {
 8871: 	my ($ignore_cache) = @_;
 8872: 
 8873: 	if (!$ignore_cache) {
 8874: 	    if (%iphost) {
 8875: 		return %iphost;
 8876: 	    }
 8877: 	    my ($ip_info,$cached)=
 8878: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 8879: 	    if ($cached) {
 8880: 		%iphost      = %{$ip_info->[0]};
 8881: 		%name_to_ip  = %{$ip_info->[1]};
 8882: 		%lonid_to_ip = %{$ip_info->[2]};
 8883: 		return %iphost;
 8884: 	    }
 8885: 	}
 8886: 
 8887: 	# get yesterday's info for fallback
 8888: 	my %old_name_to_ip;
 8889: 	my ($ip_info,$cached)=
 8890: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 8891: 	if ($cached) {
 8892: 	    %old_name_to_ip = %{$ip_info->[1]};
 8893: 	}
 8894: 
 8895: 	my %name_to_host = &all_names();
 8896: 	foreach my $name (keys(%name_to_host)) {
 8897: 	    my $ip;
 8898: 	    if (!exists($name_to_ip{$name})) {
 8899: 		$ip = gethostbyname($name);
 8900: 		if (!$ip || length($ip) ne 4) {
 8901: 		    if (defined($old_name_to_ip{$name})) {
 8902: 			$ip = $old_name_to_ip{$name};
 8903: 			&logthis("Can't find $name defaulting to old $ip");
 8904: 		    } else {
 8905: 			&logthis("Name $name no IP found");
 8906: 			next;
 8907: 		    }
 8908: 		} else {
 8909: 		    $ip=inet_ntoa($ip);
 8910: 		}
 8911: 		$name_to_ip{$name} = $ip;
 8912: 	    } else {
 8913: 		$ip = $name_to_ip{$name};
 8914: 	    }
 8915: 	    foreach my $id (@{ $name_to_host{$name} }) {
 8916: 		$lonid_to_ip{$id} = $ip;
 8917: 	    }
 8918: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 8919: 	}
 8920: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 8921: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 8922: 				      48*60*60);
 8923: 
 8924: 	return %iphost;
 8925:     }
 8926: }
 8927: 
 8928: BEGIN {
 8929: 
 8930: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 8931:     unless ($readit) {
 8932: {
 8933:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 8934:     %perlvar = (%perlvar,%{$configvars});
 8935: }
 8936: 
 8937: 
 8938: # ------------------------------------------------------ Read spare server file
 8939: {
 8940:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 8941: 
 8942:     while (my $configline=<$config>) {
 8943:        chomp($configline);
 8944:        if ($configline) {
 8945: 	   my ($host,$type) = split(':',$configline,2);
 8946: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 8947: 	   push(@{ $spareid{$type} }, $host);
 8948:        }
 8949:     }
 8950:     close($config);
 8951: }
 8952: # ------------------------------------------------------------ Read permissions
 8953: {
 8954:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 8955: 
 8956:     while (my $configline=<$config>) {
 8957: 	chomp($configline);
 8958: 	if ($configline) {
 8959: 	    my ($role,$perm)=split(/ /,$configline);
 8960: 	    if ($perm ne '') { $pr{$role}=$perm; }
 8961: 	}
 8962:     }
 8963:     close($config);
 8964: }
 8965: 
 8966: # -------------------------------------------- Read plain texts for permissions
 8967: {
 8968:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 8969: 
 8970:     while (my $configline=<$config>) {
 8971: 	chomp($configline);
 8972: 	if ($configline) {
 8973: 	    my ($short,@plain)=split(/:/,$configline);
 8974:             %{$prp{$short}} = ();
 8975: 	    if (@plain > 0) {
 8976:                 $prp{$short}{'std'} = $plain[0];
 8977:                 for (my $i=1; $i<@plain; $i++) {
 8978:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 8979:                 }
 8980:             }
 8981: 	}
 8982:     }
 8983:     close($config);
 8984: }
 8985: 
 8986: # ---------------------------------------------------------- Read package table
 8987: {
 8988:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 8989: 
 8990:     while (my $configline=<$config>) {
 8991: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 8992: 	chomp($configline);
 8993: 	my ($short,$plain)=split(/:/,$configline);
 8994: 	my ($pack,$name)=split(/\&/,$short);
 8995: 	if ($plain ne '') {
 8996: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 8997: 	    $packagetab{$short}=$plain; 
 8998: 	}
 8999:     }
 9000:     close($config);
 9001: }
 9002: 
 9003: # ------------- set up temporary directory
 9004: {
 9005:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 9006: 
 9007: }
 9008: 
 9009: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 9010: 				'compress_threshold'=> 20_000,
 9011:  			        });
 9012: 
 9013: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 9014: $dumpcount=0;
 9015: $locknum=0;
 9016: 
 9017: &logtouch();
 9018: &logthis('<font color="yellow">INFO: Read configuration</font>');
 9019: $readit=1;
 9020:     {
 9021: 	use integer;
 9022: 	my $test=(2**32)+1;
 9023: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 9024: 	&logthis(" Detected 64bit platform ($_64bit)");
 9025:     }
 9026: }
 9027: }
 9028: 
 9029: 1;
 9030: __END__
 9031: 
 9032: =pod
 9033: 
 9034: =head1 NAME
 9035: 
 9036: Apache::lonnet - Subroutines to ask questions about things in the network.
 9037: 
 9038: =head1 SYNOPSIS
 9039: 
 9040: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 9041: 
 9042:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 9043: 
 9044: Common parameters:
 9045: 
 9046: =over 4
 9047: 
 9048: =item *
 9049: 
 9050: $uname : an internal username (if $cname expecting a course Id specifically)
 9051: 
 9052: =item *
 9053: 
 9054: $udom : a domain (if $cdom expecting a course's domain specifically)
 9055: 
 9056: =item *
 9057: 
 9058: $symb : a resource instance identifier
 9059: 
 9060: =item *
 9061: 
 9062: $namespace : the name of a .db file that contains the data needed or
 9063: being set.
 9064: 
 9065: =back
 9066: 
 9067: =head1 OVERVIEW
 9068: 
 9069: lonnet provides subroutines which interact with the
 9070: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 9071: about classes, users, and resources.
 9072: 
 9073: For many of these objects you can also use this to store data about
 9074: them or modify them in various ways.
 9075: 
 9076: =head2 Symbs
 9077: 
 9078: To identify a specific instance of a resource, LON-CAPA uses symbols
 9079: or "symbs"X<symb>. These identifiers are built from the URL of the
 9080: map, the resource number of the resource in the map, and the URL of
 9081: the resource itself. The latter is somewhat redundant, but might help
 9082: if maps change.
 9083: 
 9084: An example is
 9085: 
 9086:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 9087: 
 9088: The respective map entry is
 9089: 
 9090:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 9091:   title="Problem 2">
 9092:  </resource>
 9093: 
 9094: Symbs are used by the random number generator, as well as to store and
 9095: restore data specific to a certain instance of for example a problem.
 9096: 
 9097: =head2 Storing And Retrieving Data
 9098: 
 9099: X<store()>X<cstore()>X<restore()>Three of the most important functions
 9100: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 9101: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 9102: is is the non-critical message twin of cstore. These functions are for
 9103: handlers to store a perl hash to a user's permanent data space in an
 9104: easy manner, and to retrieve it again on another call. It is expected
 9105: that a handler would use this once at the beginning to retrieve data,
 9106: and then again once at the end to send only the new data back.
 9107: 
 9108: The data is stored in the user's data directory on the user's
 9109: homeserver under the ID of the course.
 9110: 
 9111: The hash that is returned by restore will have all of the previous
 9112: value for all of the elements of the hash.
 9113: 
 9114: Example:
 9115: 
 9116:  #creating a hash
 9117:  my %hash;
 9118:  $hash{'foo'}='bar';
 9119: 
 9120:  #storing it
 9121:  &Apache::lonnet::cstore(\%hash);
 9122: 
 9123:  #changing a value
 9124:  $hash{'foo'}='notbar';
 9125: 
 9126:  #adding a new value
 9127:  $hash{'bar'}='foo';
 9128:  &Apache::lonnet::cstore(\%hash);
 9129: 
 9130:  #retrieving the hash
 9131:  my %history=&Apache::lonnet::restore();
 9132: 
 9133:  #print the hash
 9134:  foreach my $key (sort(keys(%history))) {
 9135:    print("\%history{$key} = $history{$key}");
 9136:  }
 9137: 
 9138: Will print out:
 9139: 
 9140:  %history{1:foo} = bar
 9141:  %history{1:keys} = foo:timestamp
 9142:  %history{1:timestamp} = 990455579
 9143:  %history{2:bar} = foo
 9144:  %history{2:foo} = notbar
 9145:  %history{2:keys} = foo:bar:timestamp
 9146:  %history{2:timestamp} = 990455580
 9147:  %history{bar} = foo
 9148:  %history{foo} = notbar
 9149:  %history{timestamp} = 990455580
 9150:  %history{version} = 2
 9151: 
 9152: Note that the special hash entries C<keys>, C<version> and
 9153: C<timestamp> were added to the hash. C<version> will be equal to the
 9154: total number of versions of the data that have been stored. The
 9155: C<timestamp> attribute will be the UNIX time the hash was
 9156: stored. C<keys> is available in every historical section to list which
 9157: keys were added or changed at a specific historical revision of a
 9158: hash.
 9159: 
 9160: B<Warning>: do not store the hash that restore returns directly. This
 9161: will cause a mess since it will restore the historical keys as if the
 9162: were new keys. I.E. 1:foo will become 1:1:foo etc.
 9163: 
 9164: Calling convention:
 9165: 
 9166:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 9167:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 9168: 
 9169: For more detailed information, see lonnet specific documentation.
 9170: 
 9171: =head1 RETURN MESSAGES
 9172: 
 9173: =over 4
 9174: 
 9175: =item * B<con_lost>: unable to contact remote host
 9176: 
 9177: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 9178: when the connection is brought back up
 9179: 
 9180: =item * B<con_failed>: unable to contact remote host and unable to save message
 9181: for later delivery
 9182: 
 9183: =item * B<error:>: an error a occurred, a description of the error follows the :
 9184: 
 9185: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 9186: that was requested
 9187: 
 9188: =back
 9189: 
 9190: =head1 PUBLIC SUBROUTINES
 9191: 
 9192: =head2 Session Environment Functions
 9193: 
 9194: =over 4
 9195: 
 9196: =item * 
 9197: X<appenv()>
 9198: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
 9199: the user envirnoment file, and will be restored for each access this
 9200: user makes during this session, also modifies the %env for the current
 9201: process. Optional rolesarrayref - if defined contains a reference to an array
 9202: of roles which are exempt from the restriction on modifying user.role entries 
 9203: in the user's environment.db and in %env.    
 9204: 
 9205: =item *
 9206: X<delenv()>
 9207: B<delenv($regexp)>: removes all items from the session
 9208: environment file that matches the regular expression in $regexp. The
 9209: values are also delted from the current processes %env.
 9210: 
 9211: =item * get_env_multiple($name) 
 9212: 
 9213: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9214: values may be defined and end up as an array ref.
 9215: 
 9216: returns an array of values
 9217: 
 9218: =back
 9219: 
 9220: =head2 User Information
 9221: 
 9222: =over 4
 9223: 
 9224: =item *
 9225: X<queryauthenticate()>
 9226: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 9227: authentication scheme
 9228: 
 9229: =item *
 9230: X<authenticate()>
 9231: B<authenticate($uname,$upass,$udom)>: try to
 9232: authenticate user from domain's lib servers (first use the current
 9233: one). C<$upass> should be the users password.
 9234: 
 9235: =item *
 9236: X<homeserver()>
 9237: B<homeserver($uname,$udom)>: find the server which has
 9238: the user's directory and files (there must be only one), this caches
 9239: the answer, and also caches if there is a borken connection.
 9240: 
 9241: =item *
 9242: X<idget()>
 9243: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 9244: (IDs are a unique resource in a domain, there must be only 1 ID per
 9245: username, and only 1 username per ID in a specific domain) (returns
 9246: hash: id=>name,id=>name)
 9247: 
 9248: =item *
 9249: X<idrget()>
 9250: B<idrget($udom,@unames)>: find the IDs behind a list of
 9251: usernames (returns hash: name=>id,name=>id)
 9252: 
 9253: =item *
 9254: X<idput()>
 9255: B<idput($udom,%ids)>: store away a list of names and associated IDs
 9256: 
 9257: =item *
 9258: X<rolesinit()>
 9259: B<rolesinit($udom,$username,$authhost)>: get user privileges
 9260: 
 9261: =item *
 9262: X<getsection()>
 9263: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 9264: course $cname, return section name/number or '' for "not in course"
 9265: and '-1' for "no section"
 9266: 
 9267: =item *
 9268: X<userenvironment()>
 9269: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 9270: passed in @what from the requested user's environment, returns a hash
 9271: 
 9272: =item * 
 9273: X<userlog_query()>
 9274: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 9275: activity.log file. %filters defines filters applied when parsing the
 9276: log file. These can be start or end timestamps, or the type of action
 9277: - log to look for Login or Logout events, check for Checkin or
 9278: Checkout, role for role selection. The response is in the form
 9279: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 9280: escaped strings of the action recorded in the activity.log file.
 9281: 
 9282: =back
 9283: 
 9284: =head2 User Roles
 9285: 
 9286: =over 4
 9287: 
 9288: =item *
 9289: 
 9290: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 9291:  F: full access
 9292:  U,I,K: authentication modes (cxx only)
 9293:  '': forbidden
 9294:  1: user needs to choose course
 9295:  2: browse allowed
 9296:  A: passphrase authentication needed
 9297: 
 9298: =item *
 9299: 
 9300: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 9301: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 9302: and course level
 9303: 
 9304: =item *
 9305: 
 9306: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 9307: explanation of a user role term
 9308: 
 9309: =item *
 9310: 
 9311: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
 9312: All arguments are optional. Returns a hash of a roles, either for
 9313: co-author/assistant author roles for a user's Construction Space
 9314: (default), or if $context is 'userroles', roles for the user himself,
 9315: In the hash, keys are set to colon-separated $uname,$udom,$role, and
 9316: (optionally) if $withsec is true, a fourth colon-separated item - $section.
 9317: For each key, value is set to colon-separated start and end times for
 9318: the role.  If no username and domain are specified, will default to
 9319: current user/domain. Types, roles, and roledoms are references to arrays
 9320: of role statuses (active, future or previous), roles 
 9321: (e.g., cc,in, st etc.) and domains of the roles which can be used
 9322: to restrict the list of roles reported. If no array ref is 
 9323: provided for types, will default to return only active roles.
 9324: 
 9325: =back
 9326: 
 9327: =head2 User Modification
 9328: 
 9329: =over 4
 9330: 
 9331: =item *
 9332: 
 9333: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
 9334: user for the level given by URL.  Optional start and end dates (leave empty
 9335: string or zero for "no date")
 9336: 
 9337: =item *
 9338: 
 9339: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 9340: change a users, password, possible return values are: ok,
 9341: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 9342: refused
 9343: 
 9344: =item *
 9345: 
 9346: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 9347: 
 9348: =item *
 9349: 
 9350: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
 9351:            $forceid,$desiredhome,$email,$inststatus) : 
 9352: modify user
 9353: 
 9354: =item *
 9355: 
 9356: modifystudent
 9357: 
 9358: modify a student's enrollment and identification information.
 9359: The course id is resolved based on the current users environment.  
 9360: This means the envoking user must be a course coordinator or otherwise
 9361: associated with a course.
 9362: 
 9363: This call is essentially a wrapper for lonnet::modifyuser and
 9364: lonnet::modify_student_enrollment
 9365: 
 9366: Inputs: 
 9367: 
 9368: =over 4
 9369: 
 9370: =item B<$udom> Student's loncapa domain
 9371: 
 9372: =item B<$uname> Student's loncapa login name
 9373: 
 9374: =item B<$uid> Student/Employee ID
 9375: 
 9376: =item B<$umode> Student's authentication mode
 9377: 
 9378: =item B<$upass> Student's password
 9379: 
 9380: =item B<$first> Student's first name
 9381: 
 9382: =item B<$middle> Student's middle name
 9383: 
 9384: =item B<$last> Student's last name
 9385: 
 9386: =item B<$gene> Student's generation
 9387: 
 9388: =item B<$usec> Student's section in course
 9389: 
 9390: =item B<$end> Unix time of the roles expiration
 9391: 
 9392: =item B<$start> Unix time of the roles start date
 9393: 
 9394: =item B<$forceid> If defined, allow $uid to be changed
 9395: 
 9396: =item B<$desiredhome> server to use as home server for student
 9397: 
 9398: =item B<$email> Student's permanent e-mail address
 9399: 
 9400: =item B<$type> Type of enrollment (auto or manual)
 9401: 
 9402: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
 9403: 
 9404: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
 9405: 
 9406: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
 9407: 
 9408: =item B<$context> role change context (shown in User Management Logs display in a course)
 9409: 
 9410: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
 9411: 
 9412: =back
 9413: 
 9414: =item *
 9415: 
 9416: modify_student_enrollment
 9417: 
 9418: Change a students enrollment status in a class.  The environment variable
 9419: 'role.request.course' must be defined for this function to proceed.
 9420: 
 9421: Inputs:
 9422: 
 9423: =over 4
 9424: 
 9425: =item $udom, students domain
 9426: 
 9427: =item $uname, students name
 9428: 
 9429: =item $uid, students user id
 9430: 
 9431: =item $first, students first name
 9432: 
 9433: =item $middle
 9434: 
 9435: =item $last
 9436: 
 9437: =item $gene
 9438: 
 9439: =item $usec
 9440: 
 9441: =item $end
 9442: 
 9443: =item $start
 9444: 
 9445: =item $type
 9446: 
 9447: =item $locktype
 9448: 
 9449: =item $cid
 9450: 
 9451: =item $selfenroll
 9452: 
 9453: =item $context
 9454: 
 9455: =back
 9456: 
 9457: 
 9458: =item *
 9459: 
 9460: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 9461: custom role; give a custom role to a user for the level given by URL.  Specify
 9462: name and domain of role author, and role name
 9463: 
 9464: =item *
 9465: 
 9466: revokerole($udom,$uname,$url,$role) : revoke a role for url
 9467: 
 9468: =item *
 9469: 
 9470: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 9471: 
 9472: =back
 9473: 
 9474: =head2 Course Infomation
 9475: 
 9476: =over 4
 9477: 
 9478: =item *
 9479: 
 9480: coursedescription($courseid) : returns a hash of information about the
 9481: specified course id, including all environment settings for the
 9482: course, the description of the course will be in the hash under the
 9483: key 'description'
 9484: 
 9485: =item *
 9486: 
 9487: resdata($name,$domain,$type,@which) : request for current parameter
 9488: setting for a specific $type, where $type is either 'course' or 'user',
 9489: @what should be a list of parameters to ask about. This routine caches
 9490: answers for 5 minutes.
 9491: 
 9492: =item *
 9493: 
 9494: get_courseresdata($courseid, $domain) : dump the entire course resource
 9495: data base, returning a hash that is keyed by the resource name and has
 9496: values that are the resource value.  I believe that the timestamps and
 9497: versions are also returned.
 9498: 
 9499: 
 9500: =back
 9501: 
 9502: =head2 Course Modification
 9503: 
 9504: =over 4
 9505: 
 9506: =item *
 9507: 
 9508: writecoursepref($courseid,%prefs) : write preferences (environment
 9509: database) for a course
 9510: 
 9511: =item *
 9512: 
 9513: createcourse($udom,$description,$url) : make/modify course
 9514: 
 9515: =back
 9516: 
 9517: =head2 Resource Subroutines
 9518: 
 9519: =over 4
 9520: 
 9521: =item *
 9522: 
 9523: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 9524: 
 9525: =item *
 9526: 
 9527: repcopy($filename) : subscribes to the requested file, and attempts to
 9528: replicate from the owning library server, Might return
 9529: 'unavailable', 'not_found', 'forbidden', 'ok', or
 9530: 'bad_request', also attempts to grab the metadata for the
 9531: resource. Expects the local filesystem pathname
 9532: (/home/httpd/html/res/....)
 9533: 
 9534: =back
 9535: 
 9536: =head2 Resource Information
 9537: 
 9538: =over 4
 9539: 
 9540: =item *
 9541: 
 9542: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 9543: a vairety of different possible values, $varname should be a request
 9544: string, and the other parameters can be used to specify who and what
 9545: one is asking about.
 9546: 
 9547: Possible values for $varname are environment.lastname (or other item
 9548: from the envirnment hash), user.name (or someother aspect about the
 9549: user), resource.0.maxtries (or some other part and parameter of a
 9550: resource)
 9551: 
 9552: =item *
 9553: 
 9554: directcondval($number) : get current value of a condition; reads from a state
 9555: string
 9556: 
 9557: =item *
 9558: 
 9559: condval($condidx) : value of condition index based on state
 9560: 
 9561: =item *
 9562: 
 9563: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 9564: resource's metadata, $what should be either a specific key, or either
 9565: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 9566: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 9567: 
 9568: this function automatically caches all requests
 9569: 
 9570: =item *
 9571: 
 9572: metadata_query($query,$custom,$customshow) : make a metadata query against the
 9573: network of library servers; returns file handle of where SQL and regex results
 9574: will be stored for query
 9575: 
 9576: =item *
 9577: 
 9578: symbread($filename) : return symbolic list entry (filename argument optional);
 9579: returns the data handle
 9580: 
 9581: =item *
 9582: 
 9583: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 9584: a possible symb for the URL in $thisfn, and if is an encryypted
 9585: resource that the user accessed using /enc/ returns a 1 on success, 0
 9586: on failure, user must be in a course, as it assumes the existance of
 9587: the course initial hash, and uses $env('request.course.id'}
 9588: 
 9589: 
 9590: =item *
 9591: 
 9592: symbclean($symb) : removes versions numbers from a symb, returns the
 9593: cleaned symb
 9594: 
 9595: =item *
 9596: 
 9597: is_on_map($uri) : checks if the $uri is somewhere on the current
 9598: course map, user must be in a course for it to work.
 9599: 
 9600: =item *
 9601: 
 9602: numval($salt) : return random seed value (addend for rndseed)
 9603: 
 9604: =item *
 9605: 
 9606: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 9607: a random seed, all arguments are optional, if they aren't sent it uses the
 9608: environment to derive them. Note: if symb isn't sent and it can't get one
 9609: from &symbread it will use the current time as its return value
 9610: 
 9611: =item *
 9612: 
 9613: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 9614: unfakeable, receipt
 9615: 
 9616: =item *
 9617: 
 9618: receipt() : API to ireceipt working off of env values; given out to users
 9619: 
 9620: =item *
 9621: 
 9622: countacc($url) : count the number of accesses to a given URL
 9623: 
 9624: =item *
 9625: 
 9626: 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
 9627: 
 9628: =item *
 9629: 
 9630: 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)
 9631: 
 9632: =item *
 9633: 
 9634: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 9635: 
 9636: =item *
 9637: 
 9638: devalidate($symb) : devalidate temporary spreadsheet calculations,
 9639: forcing spreadsheet to reevaluate the resource scores next time.
 9640: 
 9641: =back
 9642: 
 9643: =head2 Storing/Retreiving Data
 9644: 
 9645: =over 4
 9646: 
 9647: =item *
 9648: 
 9649: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 9650: for this url; hashref needs to be given and should be a \%hashname; the
 9651: remaining args aren't required and if they aren't passed or are '' they will
 9652: be derived from the env
 9653: 
 9654: =item *
 9655: 
 9656: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 9657: uses critical subroutine
 9658: 
 9659: =item *
 9660: 
 9661: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 9662: all args are optional
 9663: 
 9664: =item *
 9665: 
 9666: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 9667: dumps the complete (or key matching regexp) namespace into a hash
 9668: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 9669: normally &store()ed into
 9670: 
 9671: $range should be either an integer '100' (give me the first 100
 9672:                                            matching records)
 9673:               or be  two integers sperated by a - with no spaces
 9674:                  '30-50' (give me the 30th through the 50th matching
 9675:                           records)
 9676: 
 9677: 
 9678: =item *
 9679: 
 9680: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 9681: replaces a &store() version of data with a replacement set of data
 9682: for a particular resource in a namespace passed in the $storehash hash 
 9683: reference
 9684: 
 9685: =item *
 9686: 
 9687: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 9688: works very similar to store/cstore, but all data is stored in a
 9689: temporary location and can be reset using tmpreset, $storehash should
 9690: be a hash reference, returns nothing on success
 9691: 
 9692: =item *
 9693: 
 9694: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 9695: similar to restore, but all data is stored in a temporary location and
 9696: can be reset using tmpreset. Returns a hash of values on success,
 9697: error string otherwise.
 9698: 
 9699: =item *
 9700: 
 9701: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 9702: deltes all keys for $symb form the temporary storage hash.
 9703: 
 9704: =item *
 9705: 
 9706: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9707: reference filled in from namesp ($udom and $uname are optional)
 9708: 
 9709: =item *
 9710: 
 9711: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 9712: namesp ($udom and $uname are optional)
 9713: 
 9714: =item *
 9715: 
 9716: dump($namespace,$udom,$uname,$regexp,$range) : 
 9717: dumps the complete (or key matching regexp) namespace into a hash
 9718: ($udom, $uname, $regexp, $range are optional)
 9719: 
 9720: $range should be either an integer '100' (give me the first 100
 9721:                                            matching records)
 9722:               or be  two integers sperated by a - with no spaces
 9723:                  '30-50' (give me the 30th through the 50th matching
 9724:                           records)
 9725: =item *
 9726: 
 9727: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 9728: $store can be a scalar, an array reference, or if the amount to be 
 9729: incremented is > 1, a hash reference.
 9730: 
 9731: ($udom and $uname are optional)
 9732: 
 9733: =item *
 9734: 
 9735: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 9736: ($udom and $uname are optional)
 9737: 
 9738: =item *
 9739: 
 9740: cput($namespace,$storehash,$udom,$uname) : critical put
 9741: ($udom and $uname are optional)
 9742: 
 9743: =item *
 9744: 
 9745: newput($namespace,$storehash,$udom,$uname) :
 9746: 
 9747: Attempts to store the items in the $storehash, but only if they don't
 9748: currently exist, if this succeeds you can be certain that you have 
 9749: successfully created a new key value pair in the $namespace db.
 9750: 
 9751: 
 9752: Args:
 9753:  $namespace: name of database to store values to
 9754:  $storehash: hashref to store to the db
 9755:  $udom: (optional) domain of user containing the db
 9756:  $uname: (optional) name of user caontaining the db
 9757: 
 9758: Returns:
 9759:  'ok' -> succeeded in storing all keys of $storehash
 9760:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 9761:                         least <key> already existed in the db (other
 9762:                         requested keys may also already exist)
 9763:  'error: <msg>' -> unable to tie the DB or other error occurred
 9764:  'con_lost' -> unable to contact request server
 9765:  'refused' -> action was not allowed by remote machine
 9766: 
 9767: 
 9768: =item *
 9769: 
 9770: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9771: reference filled in from namesp (encrypts the return communication)
 9772: ($udom and $uname are optional)
 9773: 
 9774: =item *
 9775: 
 9776: log($udom,$name,$home,$message) : write to permanent log for user; use
 9777: critical subroutine
 9778: 
 9779: =item *
 9780: 
 9781: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
 9782: array reference filled in from namespace found in domain level on either
 9783: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
 9784: 
 9785: =item *
 9786: 
 9787: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
 9788: domain level either on specified domain server ($uhome) or primary domain 
 9789: server ($udom and $uhome are optional)
 9790: 
 9791: =item * 
 9792: 
 9793: get_domain_defaults($target_domain) : returns hash with defaults for
 9794: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
 9795: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
 9796: or localauth), initial password or a kerberos realm, language (e.g., en-us).
 9797: Values are retrieved from cache (if current), or from domain's configuration.db
 9798: (if available), or lastly from values in lonTabs/dns_domain,tab, 
 9799: or lonTabs/domain.tab. 
 9800: 
 9801: %domdefaults = &get_auth_defaults($target_domain);
 9802: 
 9803: =back
 9804: 
 9805: =head2 Network Status Functions
 9806: 
 9807: =over 4
 9808: 
 9809: =item *
 9810: 
 9811: dirlist($uri) : return directory list based on URI
 9812: 
 9813: =item *
 9814: 
 9815: spareserver() : find server with least workload from spare.tab
 9816: 
 9817: =back
 9818: 
 9819: =head2 Apache Request
 9820: 
 9821: =over 4
 9822: 
 9823: =item *
 9824: 
 9825: ssi($url,%hash) : server side include, does a complete request cycle on url to
 9826: localhost, posts hash
 9827: 
 9828: =back
 9829: 
 9830: =head2 Data to String to Data
 9831: 
 9832: =over 4
 9833: 
 9834: =item *
 9835: 
 9836: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 9837: and '&' separators, supports elements that are arrayrefs and hashrefs
 9838: 
 9839: =item *
 9840: 
 9841: hashref2str($hashref) : convert a hashref into a string complete with
 9842: escaping and '=' and '&' separators, supports elements that are
 9843: arrayrefs and hashrefs
 9844: 
 9845: =item *
 9846: 
 9847: arrayref2str($arrayref) : convert an arrayref into a string complete
 9848: with escaping and '&' separators, supports elements that are arrayrefs
 9849: and hashrefs
 9850: 
 9851: =item *
 9852: 
 9853: str2hash($string) : convert string to hash using unescaping and
 9854: splitting on '=' and '&', supports elements that are arrayrefs and
 9855: hashrefs
 9856: 
 9857: =item *
 9858: 
 9859: str2array($string) : convert string to hash using unescaping and
 9860: splitting on '&', supports elements that are arrayrefs and hashrefs
 9861: 
 9862: =back
 9863: 
 9864: =head2 Logging Routines
 9865: 
 9866: =over 4
 9867: 
 9868: These routines allow one to make log messages in the lonnet.log and
 9869: lonnet.perm logfiles.
 9870: 
 9871: =item *
 9872: 
 9873: logtouch() : make sure the logfile, lonnet.log, exists
 9874: 
 9875: =item *
 9876: 
 9877: logthis() : append message to the normal lonnet.log file, it gets
 9878: preiodically rolled over and deleted.
 9879: 
 9880: =item *
 9881: 
 9882: logperm() : append a permanent message to lonnet.perm.log, this log
 9883: file never gets deleted by any automated portion of the system, only
 9884: messages of critical importance should go in here.
 9885: 
 9886: =back
 9887: 
 9888: =head2 General File Helper Routines
 9889: 
 9890: =over 4
 9891: 
 9892: =item *
 9893: 
 9894: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 9895: (a) files in /uploaded
 9896:   (i) If a local copy of the file exists - 
 9897:       compares modification date of local copy with last-modified date for 
 9898:       definitive version stored on home server for course. If local copy is 
 9899:       stale, requests a new version from the home server and stores it. 
 9900:       If the original has been removed from the home server, then local copy 
 9901:       is unlinked.
 9902:   (ii) If local copy does not exist -
 9903:       requests the file from the home server and stores it. 
 9904:   
 9905:   If $caller is 'uploadrep':  
 9906:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 9907:     for request for files originally uploaded via DOCS. 
 9908:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 9909:   
 9910:   Otherwise:
 9911:      This indicates a call from the content generation phase of the request.
 9912:      -  returns the entire contents of the file or -1.
 9913:      
 9914: (b) files in /res
 9915:    - returns the entire contents of a file or -1; 
 9916:    it properly subscribes to and replicates the file if neccessary.
 9917: 
 9918: 
 9919: =item *
 9920: 
 9921: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 9922:                   reference
 9923: 
 9924: returns either a stat() list of data about the file or an empty list
 9925: if the file doesn't exist or couldn't find out about it (connection
 9926: problems or user unknown)
 9927: 
 9928: =item *
 9929: 
 9930: filelocation($dir,$file) : returns file system location of a file
 9931: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 9932: directory that relative $file lookups are to looked in ($dir of /a/dir
 9933: and a file of ../bob will become /a/bob)
 9934: 
 9935: =item *
 9936: 
 9937: hreflocation($dir,$file) : returns file system location or a URL; same as
 9938: filelocation except for hrefs
 9939: 
 9940: =item *
 9941: 
 9942: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 9943: 
 9944: =back
 9945: 
 9946: =head2 Usererfile file routines (/uploaded*)
 9947: 
 9948: =over 4
 9949: 
 9950: =item *
 9951: 
 9952: userfileupload(): main rotine for putting a file in a user or course's
 9953:                   filespace, arguments are,
 9954: 
 9955:  formname - required - this is the name of the element in $env where the
 9956:            filename, and the contents of the file to create/modifed exist
 9957:            the filename is in $env{'form.'.$formname.'.filename'} and the
 9958:            contents of the file is located in $env{'form.'.$formname}
 9959:  coursedoc - if true, store the file in the course of the active role
 9960:              of the current user
 9961:  subdir - required - subdirectory to put the file in under ../userfiles/
 9962:          if undefined, it will be placed in "unknown"
 9963: 
 9964:  (This routine calls clean_filename() to remove any dangerous
 9965:  characters from the filename, and then calls finuserfileupload() to
 9966:  complete the transaction)
 9967: 
 9968:  returns either the url of the uploaded file (/uploaded/....) if successful
 9969:  and /adm/notfound.html if unsuccessful
 9970: 
 9971: =item *
 9972: 
 9973: clean_filename(): routine for cleaing a filename up for storage in
 9974:                  userfile space, argument is:
 9975: 
 9976:  filename - proposed filename
 9977: 
 9978: returns: the new clean filename
 9979: 
 9980: =item *
 9981: 
 9982: finishuserfileupload(): routine that creaes and sends the file to
 9983: userspace, probably shouldn't be called directly
 9984: 
 9985:   docuname: username or courseid of destination for the file
 9986:   docudom: domain of user/course of destination for the file
 9987:   formname: same as for userfileupload()
 9988:   fname: filename (inculding subdirectories) for the file
 9989: 
 9990:  returns either the url of the uploaded file (/uploaded/....) if successful
 9991:  and /adm/notfound.html if unsuccessful
 9992: 
 9993: =item *
 9994: 
 9995: renameuserfile(): renames an existing userfile to a new name
 9996: 
 9997:   Args:
 9998:    docuname: username or courseid of destination for the file
 9999:    docudom: domain of user/course of destination for the file
10000:    old: current file name (including any subdirs under userfiles)
10001:    new: desired file name (including any subdirs under userfiles)
10002: 
10003: =item *
10004: 
10005: mkdiruserfile(): creates a directory is a userfiles dir
10006: 
10007:   Args:
10008:    docuname: username or courseid of destination for the file
10009:    docudom: domain of user/course of destination for the file
10010:    dir: dir to create (including any subdirs under userfiles)
10011: 
10012: =item *
10013: 
10014: removeuserfile(): removes a file that exists in userfiles
10015: 
10016:   Args:
10017:    docuname: username or courseid of destination for the file
10018:    docudom: domain of user/course of destination for the file
10019:    fname: filname to delete (including any subdirs under userfiles)
10020: 
10021: =item *
10022: 
10023: removeuploadedurl(): convience function for removeuserfile()
10024: 
10025:   Args:
10026:    url:  a full /uploaded/... url to delete
10027: 
10028: =item * 
10029: 
10030: get_portfile_permissions():
10031:   Args:
10032:     domain: domain of user or course contain the portfolio files
10033:     user: name of user or num of course contain the portfolio files
10034:   Returns:
10035:     hashref of a dump of the proper file_permissions.db
10036:    
10037: 
10038: =item * 
10039: 
10040: get_access_controls():
10041: 
10042: Args:
10043:   current_permissions: the hash ref returned from get_portfile_permissions()
10044:   group: (optional) the group you want the files associated with
10045:   file: (optional) the file you want access info on
10046: 
10047: Returns:
10048:     a hash (keys are file names) of hashes containing
10049:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10050:         values are XML containing access control settings (see below) 
10051: 
10052: Internal notes:
10053: 
10054:  access controls are stored in file_permissions.db as key=value pairs.
10055:     key -> path to file/file_name\0uniqueID:scope_end_start
10056:         where scope -> public,guest,course,group,domains or users.
10057:               end -> UNIX time for end of access (0 -> no end date)
10058:               start -> UNIX time for start of access
10059: 
10060:     value -> XML description of access control
10061:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10062:             <start></start>
10063:             <end></end>
10064: 
10065:             <password></password>  for scope type = guest
10066: 
10067:             <domain></domain>     for scope type = course or group
10068:             <number></number>
10069:             <roles id="">
10070:              <role></role>
10071:              <access></access>
10072:              <section></section>
10073:              <group></group>
10074:             </roles>
10075: 
10076:             <dom></dom>         for scope type = domains
10077: 
10078:             <users>             for scope type = users
10079:              <user>
10080:               <uname></uname>
10081:               <udom></udom>
10082:              </user>
10083:             </users>
10084:            </scope> 
10085:               
10086:  Access data is also aggregated for each file in an additional key=value pair:
10087:  key -> path to file/file_name\0accesscontrol 
10088:  value -> reference to hash
10089:           hash contains key = value pairs
10090:           where key = uniqueID:scope_end_start
10091:                 value = UNIX time record was last updated
10092: 
10093:           Used to improve speed of look-ups of access controls for each file.  
10094:  
10095:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10096: 
10097: modify_access_controls():
10098: 
10099: Modifies access controls for a portfolio file
10100: Args
10101: 1. file name
10102: 2. reference to hash of required changes,
10103: 3. domain
10104: 4. username
10105:   where domain,username are the domain of the portfolio owner 
10106:   (either a user or a course) 
10107: 
10108: Returns:
10109: 1. result of additions or updates ('ok' or 'error', with error message). 
10110: 2. result of deletions ('ok' or 'error', with error message).
10111: 3. reference to hash of any new or updated access controls.
10112: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10113:    key = integer (inbound ID)
10114:    value = uniqueID  
10115: 
10116: =back
10117: 
10118: =head2 HTTP Helper Routines
10119: 
10120: =over 4
10121: 
10122: =item *
10123: 
10124: escape() : unpack non-word characters into CGI-compatible hex codes
10125: 
10126: =item *
10127: 
10128: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10129: 
10130: =back
10131: 
10132: =head1 PRIVATE SUBROUTINES
10133: 
10134: =head2 Underlying communication routines (Shouldn't call)
10135: 
10136: =over 4
10137: 
10138: =item *
10139: 
10140: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10141: 
10142: =item *
10143: 
10144: reply() : uses subreply to send a message to remote machine, logs all failures
10145: 
10146: =item *
10147: 
10148: critical() : passes a critical message to another server; if cannot
10149: get through then place message in connection buffer directory and
10150: returns con_delayed, if incapable of saving message, returns
10151: con_failed
10152: 
10153: =item *
10154: 
10155: reconlonc() : tries to reconnect lonc client processes.
10156: 
10157: =back
10158: 
10159: =head2 Resource Access Logging
10160: 
10161: =over 4
10162: 
10163: =item *
10164: 
10165: flushcourselogs() : flush (save) buffer logs and access logs
10166: 
10167: =item *
10168: 
10169: courselog($what) : save message for course in hash
10170: 
10171: =item *
10172: 
10173: courseacclog($what) : save message for course using &courselog().  Perform
10174: special processing for specific resource types (problems, exams, quizzes, etc).
10175: 
10176: =item *
10177: 
10178: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10179: as a PerlChildExitHandler
10180: 
10181: =back
10182: 
10183: =head2 Other
10184: 
10185: =over 4
10186: 
10187: =item *
10188: 
10189: symblist($mapname,%newhash) : update symbolic storage links
10190: 
10191: =back
10192: 
10193: =cut
10194: 

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