File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.982: download - view: text, annotated - select for diffs
Fri Jan 2 22:45:43 2009 UTC (15 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Adding domain defaults for timezone_def and datelocale_def to cached %domdefaults.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.982 2009/01/02 22:45:43 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use LWP::UserAgent();
   75: use HTTP::Date;
   76: use Image::Magick;
   77: 
   78: # use Date::Parse;
   79: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   80:             $_64bit %env %protocol);
   81: 
   82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   85:     %courseownerbuf, %coursetypebuf,$locknum);
   86: 
   87: use IO::Socket;
   88: use GDBM_File;
   89: use HTML::LCParser;
   90: use Fcntl qw(:flock);
   91: use Storable qw(thaw nfreeze);
   92: use Time::HiRes qw( gettimeofday tv_interval );
   93: use Cache::Memcached;
   94: use Digest::MD5;
   95: use Math::Random;
   96: use LONCAPA qw(:DEFAULT :match);
   97: use LONCAPA::Configuration;
   98: 
   99: my $readit;
  100: my $max_connection_retries = 10;     # Or some such value.
  101: 
  102: my $upload_photo_form = 0; #Variable to check  when user upload a photo 0=not 1=true
  103: 
  104: require Exporter;
  105: 
  106: our @ISA = qw (Exporter);
  107: our @EXPORT = qw(%env);
  108: 
  109: 
  110: # --------------------------------------------------------------------- Logging
  111: {
  112:     my $logid;
  113:     sub instructor_log {
  114: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  115:         if (($cnum eq '') || ($cdom eq '')) {
  116:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  117:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  118:         }
  119: 	$logid++;
  120:         my $now = time();
  121: 	my $id=$now.'00000'.$$.'00000'.$logid;
  122: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  123: 				    { $id => {
  124: 					'exe_uname' => $env{'user.name'},
  125: 					'exe_udom'  => $env{'user.domain'},
  126: 					'exe_time'  => $now,
  127: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  128: 					'delflag'   => $delflag,
  129: 					'logentry'  => $storehash,
  130: 					'uname'     => $uname,
  131: 					'udom'      => $udom,
  132: 				    }
  133: 				  },$cdom,$cnum);
  134:     }
  135: }
  136: 
  137: sub logtouch {
  138:     my $execdir=$perlvar{'lonDaemons'};
  139:     unless (-e "$execdir/logs/lonnet.log") {	
  140: 	open(my $fh,">>$execdir/logs/lonnet.log");
  141: 	close $fh;
  142:     }
  143:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  144:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  145: }
  146: 
  147: sub logthis {
  148:     my $message=shift;
  149:     my $execdir=$perlvar{'lonDaemons'};
  150:     my $now=time;
  151:     my $local=localtime($now);
  152:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  153: 	print $fh "$local ($$): $message\n";
  154: 	close($fh);
  155:     }
  156:     return 1;
  157: }
  158: 
  159: sub logperm {
  160:     my $message=shift;
  161:     my $execdir=$perlvar{'lonDaemons'};
  162:     my $now=time;
  163:     my $local=localtime($now);
  164:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  165: 	print $fh "$now:$message:$local\n";
  166: 	close($fh);
  167:     }
  168:     return 1;
  169: }
  170: 
  171: sub create_connection {
  172:     my ($hostname,$lonid) = @_;
  173:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  174: 				     Type    => SOCK_STREAM,
  175: 				     Timeout => 10);
  176:     return 0 if (!$client);
  177:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  178:     my $result = <$client>;
  179:     chomp($result);
  180:     return 1 if ($result eq 'done');
  181:     return 0;
  182: }
  183: 
  184: 
  185: # -------------------------------------------------- Non-critical communication
  186: sub subreply {
  187:     my ($cmd,$server)=@_;
  188:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  189:     #
  190:     #  With loncnew process trimming, there's a timing hole between lonc server
  191:     #  process exit and the master server picking up the listen on the AF_UNIX
  192:     #  socket.  In that time interval, a lock file will exist:
  193: 
  194:     my $lockfile=$peerfile.".lock";
  195:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  196: 	sleep(1);
  197:     }
  198:     # At this point, either a loncnew parent is listening or an old lonc
  199:     # or loncnew child is listening so we can connect or everything's dead.
  200:     #
  201:     #   We'll give the connection a few tries before abandoning it.  If
  202:     #   connection is not possible, we'll con_lost back to the client.
  203:     #   
  204:     my $client;
  205:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  206: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  207: 				      Type    => SOCK_STREAM,
  208: 				      Timeout => 10);
  209: 	if ($client) {
  210: 	    last;		# Connected!
  211: 	} else {
  212: 	    &create_connection(&hostname($server),$server);
  213: 	}
  214:         sleep(1);		# Try again later if failed connection.
  215:     }
  216:     my $answer;
  217:     if ($client) {
  218: 	print $client "sethost:$server:$cmd\n";
  219: 	$answer=<$client>;
  220: 	if (!$answer) { $answer="con_lost"; }
  221: 	chomp($answer);
  222:     } else {
  223: 	$answer = 'con_lost';	# Failed connection.
  224:     }
  225:     return $answer;
  226: }
  227: 
  228: sub reply {
  229:     my ($cmd,$server)=@_;
  230:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  231:     my $answer=subreply($cmd,$server);
  232:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  233:        &logthis("<font color=\"blue\">WARNING:".
  234:                 " $cmd to $server returned $answer</font>");
  235:     }
  236:     return $answer;
  237: }
  238: 
  239: # ----------------------------------------------------------- Send USR1 to lonc
  240: 
  241: sub reconlonc {
  242:     my ($lonid) = @_;
  243:     my $hostname = &hostname($lonid);
  244:     if ($lonid) {
  245: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  246: 	if ($hostname && -e $peerfile) {
  247: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  248: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  249: 					     Type    => SOCK_STREAM,
  250: 					     Timeout => 10);
  251: 	    if ($client) {
  252: 		print $client ("reset_retries\n");
  253: 		my $answer=<$client>;
  254: 		#reset just this one.
  255: 	    }
  256: 	}
  257: 	return;
  258:     }
  259: 
  260:     &logthis("Trying to reconnect lonc");
  261:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  262:     if (open(my $fh,"<$loncfile")) {
  263: 	my $loncpid=<$fh>;
  264:         chomp($loncpid);
  265:         if (kill 0 => $loncpid) {
  266: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  267:             kill USR1 => $loncpid;
  268:             sleep 1;
  269:          } else {
  270: 	    &logthis(
  271:                "<font color=\"blue\">WARNING:".
  272:                " lonc at pid $loncpid not responding, giving up</font>");
  273:         }
  274:     } else {
  275: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  276:     }
  277: }
  278: 
  279: # ------------------------------------------------------ Critical communication
  280: 
  281: sub critical {
  282:     my ($cmd,$server)=@_;
  283:     unless (&hostname($server)) {
  284:         &logthis("<font color=\"blue\">WARNING:".
  285:                " Critical message to unknown server ($server)</font>");
  286:         return 'no_such_host';
  287:     }
  288:     my $answer=reply($cmd,$server);
  289:     if ($answer eq 'con_lost') {
  290: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  291: 	my $answer=reply($cmd,$server);
  292:         if ($answer eq 'con_lost') {
  293:             my $now=time;
  294:             my $middlename=$cmd;
  295:             $middlename=substr($middlename,0,16);
  296:             $middlename=~s/\W//g;
  297:             my $dfilename=
  298:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  299:             $dumpcount++;
  300:             {
  301: 		my $dfh;
  302: 		if (open($dfh,">$dfilename")) {
  303: 		    print $dfh "$cmd\n"; 
  304: 		    close($dfh);
  305: 		}
  306:             }
  307:             sleep 2;
  308:             my $wcmd='';
  309:             {
  310: 		my $dfh;
  311: 		if (open($dfh,"<$dfilename")) {
  312: 		    $wcmd=<$dfh>; 
  313: 		    close($dfh);
  314: 		}
  315:             }
  316:             chomp($wcmd);
  317:             if ($wcmd eq $cmd) {
  318: 		&logthis("<font color=\"blue\">WARNING: ".
  319:                          "Connection buffer $dfilename: $cmd</font>");
  320:                 &logperm("D:$server:$cmd");
  321: 	        return 'con_delayed';
  322:             } else {
  323:                 &logthis("<font color=\"red\">CRITICAL:"
  324:                         ." Critical connection failed: $server $cmd</font>");
  325:                 &logperm("F:$server:$cmd");
  326:                 return 'con_failed';
  327:             }
  328:         }
  329:     }
  330:     return $answer;
  331: }
  332: 
  333: # ------------------------------------------- check if return value is an error
  334: 
  335: sub error {
  336:     my ($result) = @_;
  337:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  338: 	if ($2 == 2) { return undef; }
  339: 	return $1;
  340:     }
  341:     return undef;
  342: }
  343: 
  344: sub convert_and_load_session_env {
  345:     my ($lonidsdir,$handle)=@_;
  346:     my @profile;
  347:     {
  348: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  349: 	if (!$opened) {
  350: 	    return 0;
  351: 	}
  352: 	flock($idf,LOCK_SH);
  353: 	@profile=<$idf>;
  354: 	close($idf);
  355:     }
  356:     my %temp_env;
  357:     foreach my $line (@profile) {
  358: 	if ($line !~ m/=/) {
  359: 	    return 0;
  360: 	}
  361: 	chomp($line);
  362: 	my ($envname,$envvalue)=split(/=/,$line,2);
  363: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  364:     }
  365:     unlink("$lonidsdir/$handle.id");
  366:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  367: 	    0640)) {
  368: 	%disk_env = %temp_env;
  369: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  370: 	untie(%disk_env);
  371:     }
  372:     return 1;
  373: }
  374: 
  375: # ------------------------------------------- Transfer profile into environment
  376: my $env_loaded;
  377: sub transfer_profile_to_env {
  378:     my ($lonidsdir,$handle,$force_transfer) = @_;
  379:     if (!$force_transfer && $env_loaded) { return; } 
  380: 
  381:     if (!defined($lonidsdir)) {
  382: 	$lonidsdir = $perlvar{'lonIDsDir'};
  383:     }
  384:     if (!defined($handle)) {
  385:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  386:     }
  387: 
  388:     my $convert;
  389:     {
  390:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  391: 	if (!$opened) {
  392: 	    return;
  393: 	}
  394: 	flock($idf,LOCK_SH);
  395: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  396: 		&GDBM_READER(),0640)) {
  397: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  398: 	    untie(%disk_env);
  399: 	} else {
  400: 	    $convert = 1;
  401: 	}
  402:     }
  403:     if ($convert) {
  404: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  405: 	    &logthis("Failed to load session, or convert session.");
  406: 	}
  407:     }
  408: 
  409:     my %remove;
  410:     while ( my $envname = each(%env) ) {
  411:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  412:             if ($time < time-300) {
  413:                 $remove{$key}++;
  414:             }
  415:         }
  416:     }
  417: 
  418:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  419:     $env_loaded=1;
  420:     foreach my $expired_key (keys(%remove)) {
  421:         &delenv($expired_key);
  422:     }
  423: }
  424: 
  425: # ---------------------------------------------------- Check for valid session 
  426: sub check_for_valid_session {
  427:     my ($r) = @_;
  428:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  429:     my $lonid=$cookies{'lonID'};
  430:     return undef if (!$lonid);
  431: 
  432:     my $handle=&LONCAPA::clean_handle($lonid->value);
  433:     my $lonidsdir=$r->dir_config('lonIDsDir');
  434:     return undef if (!-e "$lonidsdir/$handle.id");
  435: 
  436:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  437:     return undef if (!$opened);
  438: 
  439:     flock($idf,LOCK_SH);
  440:     my %disk_env;
  441:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  442: 	    &GDBM_READER(),0640)) {
  443: 	return undef;	
  444:     }
  445: 
  446:     if (!defined($disk_env{'user.name'})
  447: 	|| !defined($disk_env{'user.domain'})) {
  448: 	return undef;
  449:     }
  450:     return $handle;
  451: }
  452: 
  453: sub timed_flock {
  454:     my ($file,$lock_type) = @_;
  455:     my $failed=0;
  456:     eval {
  457: 	local $SIG{__DIE__}='DEFAULT';
  458: 	local $SIG{ALRM}=sub {
  459: 	    $failed=1;
  460: 	    die("failed lock");
  461: 	};
  462: 	alarm(13);
  463: 	flock($file,$lock_type);
  464: 	alarm(0);
  465:     };
  466:     if ($failed) {
  467: 	return undef;
  468:     } else {
  469: 	return 1;
  470:     }
  471: }
  472: 
  473: # ---------------------------------------------------------- Append Environment
  474: 
  475: sub appenv {
  476:     my ($newenv,$roles) = @_;
  477:     if (ref($newenv) eq 'HASH') {
  478:         foreach my $key (keys(%{$newenv})) {
  479:             my $refused = 0;
  480: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  481:                 $refused = 1;
  482:                 if (ref($roles) eq 'ARRAY') {
  483:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  484:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  485:                         $refused = 0;
  486:                     }
  487:                 }
  488:             }
  489:             if ($refused) {
  490:                 &logthis("<font color=\"blue\">WARNING: ".
  491:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  492:                          .'</font>');
  493: 	        delete($newenv->{$key});
  494:             } else {
  495:                 $env{$key}=$newenv->{$key};
  496:             }
  497:         }
  498:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  499:         if ($opened
  500: 	    && &timed_flock($env_file,LOCK_EX)
  501: 	    &&
  502: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  503: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  504: 	    while (my ($key,$value) = each(%{$newenv})) {
  505: 	        $disk_env{$key} = $value;
  506: 	    }
  507: 	    untie(%disk_env);
  508:         }
  509:     }
  510:     return 'ok';
  511: }
  512: # ----------------------------------------------------- Delete from Environment
  513: 
  514: sub delenv {
  515:     my $delthis=shift;
  516:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  517:         &logthis("<font color=\"blue\">WARNING: ".
  518:                 "Attempt to delete from environment ".$delthis);
  519:         return 'error';
  520:     }
  521:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  522:     if ($opened
  523: 	&& &timed_flock($env_file,LOCK_EX)
  524: 	&&
  525: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  526: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  527: 	foreach my $key (keys(%disk_env)) {
  528: 	    if ($key=~/^\Q$delthis\E/) { 
  529: 		delete($env{$key});
  530: 		delete($disk_env{$key});
  531: 	    }
  532: 	}
  533: 	untie(%disk_env);
  534:     }
  535:     return 'ok';
  536: }
  537: 
  538: sub get_env_multiple {
  539:     my ($name) = @_;
  540:     my @values;
  541:     if (defined($env{$name})) {
  542:         # exists is it an array
  543:         if (ref($env{$name})) {
  544:             @values=@{ $env{$name} };
  545:         } else {
  546:             $values[0]=$env{$name};
  547:         }
  548:     }
  549:     return(@values);
  550: }
  551: 
  552: # ------------------------------------------------------------------- Locking
  553: 
  554: sub set_lock {
  555:     my ($text)=@_;
  556:     $locknum++;
  557:     my $id=$$.'-'.$locknum;
  558:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  559:              'session.lock.'.$id => $text});
  560:     return $id;
  561: }
  562: 
  563: sub get_locks {
  564:     my $num=0;
  565:     my %texts=();
  566:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  567:        if ($lock=~/\w/) {
  568:           $num++;
  569:           $texts{$lock}=$env{'session.lock.'.$lock};
  570:        }
  571:    }
  572:    return ($num,%texts);
  573: }
  574: 
  575: sub remove_lock {
  576:     my ($id)=@_;
  577:     my $newlocks='';
  578:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  579:        if (($lock=~/\w/) && ($lock ne $id)) {
  580:           $newlocks.=','.$lock;
  581:        }
  582:     }
  583:     &appenv({'session.locks' => $newlocks});
  584:     &delenv('session.lock.'.$id);
  585: }
  586: 
  587: sub remove_all_locks {
  588:     my $activelocks=$env{'session.locks'};
  589:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  590:        if ($lock=~/\w/) {
  591:           &remove_lock($lock);
  592:        }
  593:     }
  594: }
  595: 
  596: 
  597: # ------------------------------------------ Find out current server userload
  598: sub userload {
  599:     my $numusers=0;
  600:     {
  601: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  602: 	my $filename;
  603: 	my $curtime=time;
  604: 	while ($filename=readdir(LONIDS)) {
  605: 	    next if ($filename eq '.' || $filename eq '..');
  606: 	    next if ($filename =~ /publicuser_\d+\.id/);
  607: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  608: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  609: 	}
  610: 	closedir(LONIDS);
  611:     }
  612:     my $userloadpercent=0;
  613:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  614:     if ($maxuserload) {
  615: 	$userloadpercent=100*$numusers/$maxuserload;
  616:     }
  617:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  618:     return $userloadpercent;
  619: }
  620: 
  621: # ------------------------------------------ Fight off request when overloaded
  622: 
  623: sub overloaderror {
  624:     my ($r,$checkserver)=@_;
  625:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  626:     my $loadavg;
  627:     if ($checkserver eq $perlvar{'lonHostID'}) {
  628:        open(my $loadfile,'/proc/loadavg');
  629:        $loadavg=<$loadfile>;
  630:        $loadavg =~ s/\s.*//g;
  631:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  632:        close($loadfile);
  633:     } else {
  634:        $loadavg=&reply('load',$checkserver);
  635:     }
  636:     my $overload=$loadavg-100;
  637:     if ($overload>0) {
  638: 	$r->err_headers_out->{'Retry-After'}=$overload;
  639:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  640:         return 413;
  641:     }    
  642:     return '';
  643: }
  644: 
  645: # ------------------------------ Find server with least workload from spare.tab
  646: 
  647: sub spareserver {
  648:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  649:     my $spare_server;
  650:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  651:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  652:                                                      :  $userloadpercent;
  653:     
  654:     foreach my $try_server (@{ $spareid{'primary'} }) {
  655: 	($spare_server, $lowest_load) =
  656: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  657:     }
  658: 
  659:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  660: 
  661:     if (!$found_server) {
  662: 	foreach my $try_server (@{ $spareid{'default'} }) {
  663: 	    ($spare_server, $lowest_load) =
  664: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  665: 	}
  666:     }
  667: 
  668:     if (!$want_server_name) {
  669:         my $protocol = 'http';
  670:         if ($protocol{$spare_server} eq 'https') {
  671:             $protocol = $protocol{$spare_server};
  672:         }
  673: 	$spare_server = $protocol.'://'.&hostname($spare_server);
  674:     }
  675:     return $spare_server;
  676: }
  677: 
  678: sub compare_server_load {
  679:     my ($try_server, $spare_server, $lowest_load) = @_;
  680: 
  681:     my $loadans     = &reply('load',    $try_server);
  682:     my $userloadans = &reply('userload',$try_server);
  683: 
  684:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  685: 	next; #didn't get a number from the server
  686:     }
  687: 
  688:     my $load;
  689:     if ($loadans =~ /\d/) {
  690: 	if ($userloadans =~ /\d/) {
  691: 	    #both are numbers, pick the bigger one
  692: 	    $load = ($loadans > $userloadans) ? $loadans 
  693: 		                              : $userloadans;
  694: 	} else {
  695: 	    $load = $loadans;
  696: 	}
  697:     } else {
  698: 	$load = $userloadans;
  699:     }
  700: 
  701:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  702: 	$spare_server = $try_server;
  703: 	$lowest_load  = $load;
  704:     }
  705:     return ($spare_server,$lowest_load);
  706: }
  707: 
  708: # --------------------------- ask offload servers if user already has a session
  709: sub find_existing_session {
  710:     my ($udom,$uname) = @_;
  711:     foreach my $try_server (@{ $spareid{'primary'} },
  712: 			    @{ $spareid{'default'} }) {
  713: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
  714:     }
  715:     return;
  716: }
  717: 
  718: # -------------------------------- ask if server already has a session for user
  719: sub has_user_session {
  720:     my ($lonid,$udom,$uname) = @_;
  721:     my $result = &reply(join(':','userhassession',
  722: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  723:     return 1 if ($result eq 'ok');
  724: 
  725:     return 0;
  726: }
  727: 
  728: # --------------------------------------------- Try to change a user's password
  729: 
  730: sub changepass {
  731:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  732:     $currentpass = &escape($currentpass);
  733:     $newpass     = &escape($newpass);
  734:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  735: 		       $server);
  736:     if (! $answer) {
  737: 	&logthis("No reply on password change request to $server ".
  738: 		 "by $uname in domain $udom.");
  739:     } elsif ($answer =~ "^ok") {
  740:         &logthis("$uname in $udom successfully changed their password ".
  741: 		 "on $server.");
  742:     } elsif ($answer =~ "^pwchange_failure") {
  743: 	&logthis("$uname in $udom was unable to change their password ".
  744: 		 "on $server.  The action was blocked by either lcpasswd ".
  745: 		 "or pwchange");
  746:     } elsif ($answer =~ "^non_authorized") {
  747:         &logthis("$uname in $udom did not get their password correct when ".
  748: 		 "attempting to change it on $server.");
  749:     } elsif ($answer =~ "^auth_mode_error") {
  750:         &logthis("$uname in $udom attempted to change their password despite ".
  751: 		 "not being locally or internally authenticated on $server.");
  752:     } elsif ($answer =~ "^unknown_user") {
  753:         &logthis("$uname in $udom attempted to change their password ".
  754: 		 "on $server but were unable to because $server is not ".
  755: 		 "their home server.");
  756:     } elsif ($answer =~ "^refused") {
  757: 	&logthis("$server refused to change $uname in $udom password because ".
  758: 		 "it was sent an unencrypted request to change the password.");
  759:     }
  760:     return $answer;
  761: }
  762: 
  763: # ----------------------- Try to determine user's current authentication scheme
  764: 
  765: sub queryauthenticate {
  766:     my ($uname,$udom)=@_;
  767:     my $uhome=&homeserver($uname,$udom);
  768:     if (!$uhome) {
  769: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  770: 	return 'no_host';
  771:     }
  772:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  773:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  774: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  775:     }
  776:     return $answer;
  777: }
  778: 
  779: # --------- Try to authenticate user from domain's lib servers (first this one)
  780: 
  781: sub authenticate {
  782:     my ($uname,$upass,$udom,$checkdefauth)=@_;
  783:     $upass=&escape($upass);
  784:     $uname= &LONCAPA::clean_username($uname);
  785:     my $uhome=&homeserver($uname,$udom,1);
  786:     my $newhome;
  787:     if ((!$uhome) || ($uhome eq 'no_host')) {
  788: # Maybe the machine was offline and only re-appeared again recently?
  789:         &reconlonc();
  790: # One more
  791: 	$uhome=&homeserver($uname,$udom,1);
  792:         if (($uhome eq 'no_host') && $checkdefauth) {
  793:             if (defined(&domain($udom,'primary'))) {
  794:                 $newhome=&domain($udom,'primary');
  795:             }
  796:             if ($newhome ne '') {
  797:                 $uhome = $newhome;
  798:             }
  799:         }
  800: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  801: 	    &logthis("User $uname at $udom is unknown in authenticate");
  802: 	    return 'no_host';
  803:         }
  804:     }
  805:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
  806:     if ($answer eq 'authorized') {
  807:         if ($newhome) {
  808:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
  809:             return 'no_account_on_host'; 
  810:         } else {
  811:             &logthis("User $uname at $udom authorized by $uhome");
  812:             return $uhome;
  813:         }
  814:     }
  815:     if ($answer eq 'non_authorized') {
  816: 	&logthis("User $uname at $udom rejected by $uhome");
  817: 	return 'no_host'; 
  818:     }
  819:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  820:     return 'no_host';
  821: }
  822: 
  823: # ---------------------- Find the homebase for a user from domain's lib servers
  824: 
  825: my %homecache;
  826: sub homeserver {
  827:     my ($uname,$udom,$ignoreBadCache)=@_;
  828:     my $index="$uname:$udom";
  829: 
  830:     if (exists($homecache{$index})) { return $homecache{$index}; }
  831: 
  832:     my %servers = &get_servers($udom,'library');
  833:     foreach my $tryserver (keys(%servers)) {
  834:         next if ($ignoreBadCache ne 'true' && 
  835: 		 exists($badServerCache{$tryserver}));
  836: 
  837: 	my $answer=reply("home:$udom:$uname",$tryserver);
  838: 	if ($answer eq 'found') {
  839: 	    delete($badServerCache{$tryserver}); 
  840: 	    return $homecache{$index}=$tryserver;
  841: 	} elsif ($answer eq 'no_host') {
  842: 	    $badServerCache{$tryserver}=1;
  843: 	}
  844:     }    
  845:     return 'no_host';
  846: }
  847: 
  848: # ------------------------------------- Find the usernames behind a list of IDs
  849: 
  850: sub idget {
  851:     my ($udom,@ids)=@_;
  852:     my %returnhash=();
  853:     
  854:     my %servers = &get_servers($udom,'library');
  855:     foreach my $tryserver (keys(%servers)) {
  856: 	my $idlist=join('&',@ids);
  857: 	$idlist=~tr/A-Z/a-z/; 
  858: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  859: 	my @answer=();
  860: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  861: 	    @answer=split(/\&/,$reply);
  862: 	}                    ;
  863: 	my $i;
  864: 	for ($i=0;$i<=$#ids;$i++) {
  865: 	    if ($answer[$i]) {
  866: 		$returnhash{$ids[$i]}=$answer[$i];
  867: 	    } 
  868: 	}
  869:     } 
  870:     return %returnhash;
  871: }
  872: 
  873: # ------------------------------------- Find the IDs behind a list of usernames
  874: 
  875: sub idrget {
  876:     my ($udom,@unames)=@_;
  877:     my %returnhash=();
  878:     foreach my $uname (@unames) {
  879:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  880:     }
  881:     return %returnhash;
  882: }
  883: 
  884: # ------------------------------- Store away a list of names and associated IDs
  885: 
  886: sub idput {
  887:     my ($udom,%ids)=@_;
  888:     my %servers=();
  889:     foreach my $uname (keys(%ids)) {
  890: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  891:         my $uhom=&homeserver($uname,$udom);
  892:         if ($uhom ne 'no_host') {
  893:             my $id=&escape($ids{$uname});
  894:             $id=~tr/A-Z/a-z/;
  895:             my $esc_unam=&escape($uname);
  896: 	    if ($servers{$uhom}) {
  897: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  898:             } else {
  899:                 $servers{$uhom}=$id.'='.$esc_unam;
  900:             }
  901:         }
  902:     }
  903:     foreach my $server (keys(%servers)) {
  904:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  905:     }
  906: }
  907: 
  908: # ------------------------------------------- get items from domain db files   
  909: 
  910: sub get_dom {
  911:     my ($namespace,$storearr,$udom,$uhome)=@_;
  912:     my $items='';
  913:     foreach my $item (@$storearr) {
  914:         $items.=&escape($item).'&';
  915:     }
  916:     $items=~s/\&$//;
  917:     if (!$udom) {
  918:         $udom=$env{'user.domain'};
  919:         if (defined(&domain($udom,'primary'))) {
  920:             $uhome=&domain($udom,'primary');
  921:         } else {
  922:             undef($uhome);
  923:         }
  924:     } else {
  925:         if (!$uhome) {
  926:             if (defined(&domain($udom,'primary'))) {
  927:                 $uhome=&domain($udom,'primary');
  928:             }
  929:         }
  930:     }
  931:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  932:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  933:         my %returnhash;
  934:         if ($rep eq '' || $rep =~ /^error: 2 /) {
  935:             return %returnhash;
  936:         }
  937:         my @pairs=split(/\&/,$rep);
  938:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  939:             return @pairs;
  940:         }
  941:         my $i=0;
  942:         foreach my $item (@$storearr) {
  943:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  944:             $i++;
  945:         }
  946:         return %returnhash;
  947:     } else {
  948:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
  949:     }
  950: }
  951: 
  952: # -------------------------------------------- put items in domain db files 
  953: 
  954: sub put_dom {
  955:     my ($namespace,$storehash,$udom,$uhome)=@_;
  956:     if (!$udom) {
  957:         $udom=$env{'user.domain'};
  958:         if (defined(&domain($udom,'primary'))) {
  959:             $uhome=&domain($udom,'primary');
  960:         } else {
  961:             undef($uhome);
  962:         }
  963:     } else {
  964:         if (!$uhome) {
  965:             if (defined(&domain($udom,'primary'))) {
  966:                 $uhome=&domain($udom,'primary');
  967:             }
  968:         }
  969:     } 
  970:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  971:         my $items='';
  972:         foreach my $item (keys(%$storehash)) {
  973:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  974:         }
  975:         $items=~s/\&$//;
  976:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  977:     } else {
  978:         &logthis("put_dom failed - no homeserver and/or domain");
  979:     }
  980: }
  981: 
  982: sub retrieve_inst_usertypes {
  983:     my ($udom) = @_;
  984:     my (%returnhash,@order);
  985:     if (defined(&domain($udom,'primary'))) {
  986:         my $uhome=&domain($udom,'primary');
  987:         my $rep=&reply("inst_usertypes:$udom",$uhome);
  988:         if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
  989:             &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
  990:             return (\%returnhash,\@order);
  991:         }
  992:         my ($hashitems,$orderitems) = split(/:/,$rep); 
  993:         my @pairs=split(/\&/,$hashitems);
  994:         foreach my $item (@pairs) {
  995:             my ($key,$value)=split(/=/,$item,2);
  996:             $key = &unescape($key);
  997:             next if ($key =~ /^error: 2 /);
  998:             $returnhash{$key}=&thaw_unescape($value);
  999:         }
 1000:         my @esc_order = split(/\&/,$orderitems);
 1001:         foreach my $item (@esc_order) {
 1002:             push(@order,&unescape($item));
 1003:         }
 1004:     } else {
 1005:         &logthis("get_dom failed - no primary domain server for $udom");
 1006:     }
 1007:     return (\%returnhash,\@order);
 1008: }
 1009: 
 1010: sub is_domainimage {
 1011:     my ($url) = @_;
 1012:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1013:         if (&domain($1) ne '') {
 1014:             return '1';
 1015:         }
 1016:     }
 1017:     return;
 1018: }
 1019: 
 1020: sub inst_directory_query {
 1021:     my ($srch) = @_;
 1022:     my $udom = $srch->{'srchdomain'};
 1023:     my %results;
 1024:     my $homeserver = &domain($udom,'primary');
 1025:     my $outcome;
 1026:     if ($homeserver ne '') {
 1027: 	my $queryid=&reply("querysend:instdirsearch:".
 1028: 			   &escape($srch->{'srchby'}).':'.
 1029: 			   &escape($srch->{'srchterm'}).':'.
 1030: 			   &escape($srch->{'srchtype'}),$homeserver);
 1031: 	my $host=&hostname($homeserver);
 1032: 	if ($queryid !~/^\Q$host\E\_/) {
 1033: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1034: 	    return;
 1035: 	}
 1036: 	my $response = &get_query_reply($queryid);
 1037: 	my $maxtries = 5;
 1038: 	my $tries = 1;
 1039: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1040: 	    $response = &get_query_reply($queryid);
 1041: 	    $tries ++;
 1042: 	}
 1043: 
 1044:         if (!&error($response) && $response ne 'refused') {
 1045:             if ($response eq 'unavailable') {
 1046:                 $outcome = $response;
 1047:             } else {
 1048:                 $outcome = 'ok';
 1049:                 my @matches = split(/\n/,$response);
 1050:                 foreach my $match (@matches) {
 1051:                     my ($key,$value) = split(/=/,$match);
 1052:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1053:                 }
 1054:             }
 1055:         }
 1056:     }
 1057:     return ($outcome,%results);
 1058: }
 1059: 
 1060: sub usersearch {
 1061:     my ($srch) = @_;
 1062:     my $dom = $srch->{'srchdomain'};
 1063:     my %results;
 1064:     my %libserv = &all_library();
 1065:     my $query = 'usersearch';
 1066:     foreach my $tryserver (keys(%libserv)) {
 1067:         if (&host_domain($tryserver) eq $dom) {
 1068:             my $host=&hostname($tryserver);
 1069:             my $queryid=
 1070:                 &reply("querysend:".&escape($query).':'.
 1071:                        &escape($srch->{'srchby'}).':'.
 1072:                        &escape($srch->{'srchtype'}).':'.
 1073:                        &escape($srch->{'srchterm'}),$tryserver);
 1074:             if ($queryid !~/^\Q$host\E\_/) {
 1075:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1076:                 next;
 1077:             }
 1078:             my $reply = &get_query_reply($queryid);
 1079:             my $maxtries = 1;
 1080:             my $tries = 1;
 1081:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1082:                 $reply = &get_query_reply($queryid);
 1083:                 $tries ++;
 1084:             }
 1085:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1086:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1087:             } else {
 1088:                 my @matches;
 1089:                 if ($reply =~ /\n/) {
 1090:                     @matches = split(/\n/,$reply);
 1091:                 } else {
 1092:                     @matches = split(/\&/,$reply);
 1093:                 }
 1094:                 foreach my $match (@matches) {
 1095:                     my ($uname,$udom,%userhash);
 1096:                     foreach my $entry (split(/:/,$match)) {
 1097:                         my ($key,$value) =
 1098:                             map {&unescape($_);} split(/=/,$entry);
 1099:                         $userhash{$key} = $value;
 1100:                         if ($key eq 'username') {
 1101:                             $uname = $value;
 1102:                         } elsif ($key eq 'domain') {
 1103:                             $udom = $value;
 1104:                         }
 1105:                     }
 1106:                     $results{$uname.':'.$udom} = \%userhash;
 1107:                 }
 1108:             }
 1109:         }
 1110:     }
 1111:     return %results;
 1112: }
 1113: 
 1114: sub get_instuser {
 1115:     my ($udom,$uname,$id) = @_;
 1116:     my $homeserver = &domain($udom,'primary');
 1117:     my ($outcome,%results);
 1118:     if ($homeserver ne '') {
 1119:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1120:                            &escape($id).':'.&escape($udom),$homeserver);
 1121:         my $host=&hostname($homeserver);
 1122:         if ($queryid !~/^\Q$host\E\_/) {
 1123:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1124:             return;
 1125:         }
 1126:         my $response = &get_query_reply($queryid);
 1127:         my $maxtries = 5;
 1128:         my $tries = 1;
 1129:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1130:             $response = &get_query_reply($queryid);
 1131:             $tries ++;
 1132:         }
 1133:         if (!&error($response) && $response ne 'refused') {
 1134:             if ($response eq 'unavailable') {
 1135:                 $outcome = $response;
 1136:             } else {
 1137:                 $outcome = 'ok';
 1138:                 my @matches = split(/\n/,$response);
 1139:                 foreach my $match (@matches) {
 1140:                     my ($key,$value) = split(/=/,$match);
 1141:                     $results{&unescape($key)} = &thaw_unescape($value);
 1142:                 }
 1143:             }
 1144:         }
 1145:     }
 1146:     my %userinfo;
 1147:     if (ref($results{$uname}) eq 'HASH') {
 1148:         %userinfo = %{$results{$uname}};
 1149:     } 
 1150:     return ($outcome,%userinfo);
 1151: }
 1152: 
 1153: sub inst_rulecheck {
 1154:     my ($udom,$uname,$id,$item,$rules) = @_;
 1155:     my %returnhash;
 1156:     if ($udom ne '') {
 1157:         if (ref($rules) eq 'ARRAY') {
 1158:             @{$rules} = map {&escape($_);} (@{$rules});
 1159:             my $rulestr = join(':',@{$rules});
 1160:             my $homeserver=&domain($udom,'primary');
 1161:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1162:                 my $response;
 1163:                 if ($item eq 'username') {                
 1164:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1165:                                               ':'.&escape($uname).':'.$rulestr,
 1166:                                               $homeserver));
 1167:                 } elsif ($item eq 'id') {
 1168:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1169:                                               ':'.&escape($id).':'.$rulestr,
 1170:                                               $homeserver));
 1171:                 } elsif ($item eq 'selfcreate') {
 1172:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1173:                                                &escape($udom).':'.&escape($uname).
 1174:                                               ':'.$rulestr,$homeserver));
 1175:                 }
 1176:                 if ($response ne 'refused') {
 1177:                     my @pairs=split(/\&/,$response);
 1178:                     foreach my $item (@pairs) {
 1179:                         my ($key,$value)=split(/=/,$item,2);
 1180:                         $key = &unescape($key);
 1181:                         next if ($key =~ /^error: 2 /);
 1182:                         $returnhash{$key}=&thaw_unescape($value);
 1183:                     }
 1184:                 }
 1185:             }
 1186:         }
 1187:     }
 1188:     return %returnhash;
 1189: }
 1190: 
 1191: sub inst_userrules {
 1192:     my ($udom,$check) = @_;
 1193:     my (%ruleshash,@ruleorder);
 1194:     if ($udom ne '') {
 1195:         my $homeserver=&domain($udom,'primary');
 1196:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1197:             my $response;
 1198:             if ($check eq 'id') {
 1199:                 $response=&reply('instidrules:'.&escape($udom),
 1200:                                  $homeserver);
 1201:             } elsif ($check eq 'email') {
 1202:                 $response=&reply('instemailrules:'.&escape($udom),
 1203:                                  $homeserver);
 1204:             } else {
 1205:                 $response=&reply('instuserrules:'.&escape($udom),
 1206:                                  $homeserver);
 1207:             }
 1208:             if (($response ne 'refused') && ($response ne 'error') && 
 1209:                 ($response ne 'unknown_cmd') && 
 1210:                 ($response ne 'no_such_host')) {
 1211:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1212:                 my @pairs=split(/\&/,$hashitems);
 1213:                 foreach my $item (@pairs) {
 1214:                     my ($key,$value)=split(/=/,$item,2);
 1215:                     $key = &unescape($key);
 1216:                     next if ($key =~ /^error: 2 /);
 1217:                     $ruleshash{$key}=&thaw_unescape($value);
 1218:                 }
 1219:                 my @esc_order = split(/\&/,$orderitems);
 1220:                 foreach my $item (@esc_order) {
 1221:                     push(@ruleorder,&unescape($item));
 1222:                 }
 1223:             }
 1224:         }
 1225:     }
 1226:     return (\%ruleshash,\@ruleorder);
 1227: }
 1228: 
 1229: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1230: 
 1231: sub get_domain_defaults {
 1232:     my ($domain) = @_;
 1233:     my $cachetime = 60*60*24;
 1234:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1235:     if (defined($cached)) {
 1236:         if (ref($result) eq 'HASH') {
 1237:             return %{$result};
 1238:         }
 1239:     }
 1240:     my %domdefaults;
 1241:     my %domconfig =
 1242:          &Apache::lonnet::get_dom('configuration',['defaults','quotas'],$domain);
 1243:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1244:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1245:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1246:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1247:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1248:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'}
 1249:     } else {
 1250:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1251:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1252:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1253:     }
 1254:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1255:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1256:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1257:         } else {
 1258:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1259:         } 
 1260:         my @usertools = ('aboutme','blog','portfolio');
 1261:         foreach my $item (@usertools) {
 1262:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1263:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1264:             }
 1265:         }
 1266:     }
 1267:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1268:                                   $cachetime);
 1269:     return %domdefaults;
 1270: }
 1271: 
 1272: # --------------------------------------------------- Assign a key to a student
 1273: 
 1274: sub assign_access_key {
 1275: #
 1276: # a valid key looks like uname:udom#comments
 1277: # comments are being appended
 1278: #
 1279:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1280:     $kdom=
 1281:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1282:     $knum=
 1283:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1284:     $cdom=
 1285:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1286:     $cnum=
 1287:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1288:     $udom=$env{'user.name'} unless (defined($udom));
 1289:     $uname=$env{'user.domain'} unless (defined($uname));
 1290:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1291:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1292:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1293:                                                   # assigned to this person
 1294:                                                   # - this should not happen,
 1295:                                                   # unless something went wrong
 1296:                                                   # the first time around
 1297: # ready to assign
 1298:         $logentry=$1.'; '.$logentry;
 1299:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1300:                                                  $kdom,$knum) eq 'ok') {
 1301: # key now belongs to user
 1302: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1303:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1304:                 &appenv({'environment.'.$envkey => $ckey});
 1305:                 return 'ok';
 1306:             } else {
 1307:                 return 
 1308:   'error: Count not permanently assign key, will need to be re-entered later.';
 1309: 	    }
 1310:         } else {
 1311:             return 'error: Could not assign key, try again later.';
 1312:         }
 1313:     } elsif (!$existing{$ckey}) {
 1314: # the key does not exist
 1315: 	return 'error: The key does not exist';
 1316:     } else {
 1317: # the key is somebody else's
 1318: 	return 'error: The key is already in use';
 1319:     }
 1320: }
 1321: 
 1322: # ------------------------------------------ put an additional comment on a key
 1323: 
 1324: sub comment_access_key {
 1325: #
 1326: # a valid key looks like uname:udom#comments
 1327: # comments are being appended
 1328: #
 1329:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1330:     $cdom=
 1331:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1332:     $cnum=
 1333:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1334:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1335:     if ($existing{$ckey}) {
 1336:         $existing{$ckey}.='; '.$logentry;
 1337: # ready to assign
 1338:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1339:                                                  $cdom,$cnum) eq 'ok') {
 1340: 	    return 'ok';
 1341:         } else {
 1342: 	    return 'error: Count not store comment.';
 1343:         }
 1344:     } else {
 1345: # the key does not exist
 1346: 	return 'error: The key does not exist';
 1347:     }
 1348: }
 1349: 
 1350: # ------------------------------------------------------ Generate a set of keys
 1351: 
 1352: sub generate_access_keys {
 1353:     my ($number,$cdom,$cnum,$logentry)=@_;
 1354:     $cdom=
 1355:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1356:     $cnum=
 1357:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1358:     unless (&allowed('mky',$cdom)) { return 0; }
 1359:     unless (($cdom) && ($cnum)) { return 0; }
 1360:     if ($number>10000) { return 0; }
 1361:     sleep(2); # make sure don't get same seed twice
 1362:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1363:     my $total=0;
 1364:     for (my $i=1;$i<=$number;$i++) {
 1365:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1366:                   sprintf("%lx",int(100000*rand)).'-'.
 1367:                   sprintf("%lx",int(100000*rand));
 1368:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1369:        $newkey=~s/0/h/g; # and also 0 and O
 1370:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1371:        if ($existing{$newkey}) {
 1372:            $i--;
 1373:        } else {
 1374: 	  if (&put('accesskeys',
 1375:               { $newkey => '# generated '.localtime().
 1376:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1377:                            '; '.$logentry },
 1378: 		   $cdom,$cnum) eq 'ok') {
 1379:               $total++;
 1380: 	  }
 1381:        }
 1382:     }
 1383:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1384:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1385:     return $total;
 1386: }
 1387: 
 1388: # ------------------------------------------------------- Validate an accesskey
 1389: 
 1390: sub validate_access_key {
 1391:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1392:     $cdom=
 1393:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1394:     $cnum=
 1395:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1396:     $udom=$env{'user.domain'} unless (defined($udom));
 1397:     $uname=$env{'user.name'} unless (defined($uname));
 1398:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1399:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1400: }
 1401: 
 1402: # ------------------------------------- Find the section of student in a course
 1403: sub devalidate_getsection_cache {
 1404:     my ($udom,$unam,$courseid)=@_;
 1405:     my $hashid="$udom:$unam:$courseid";
 1406:     &devalidate_cache_new('getsection',$hashid);
 1407: }
 1408: 
 1409: sub courseid_to_courseurl {
 1410:     my ($courseid) = @_;
 1411:     #already url style courseid
 1412:     return $courseid if ($courseid =~ m{^/});
 1413: 
 1414:     if (exists($env{'course.'.$courseid.'.num'})) {
 1415: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1416: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1417: 	return "/$cdom/$cnum";
 1418:     }
 1419: 
 1420:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1421:     if (exists($courseinfo{'num'})) {
 1422: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1423:     }
 1424: 
 1425:     return undef;
 1426: }
 1427: 
 1428: sub getsection {
 1429:     my ($udom,$unam,$courseid)=@_;
 1430:     my $cachetime=1800;
 1431: 
 1432:     my $hashid="$udom:$unam:$courseid";
 1433:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1434:     if (defined($cached)) { return $result; }
 1435: 
 1436:     my %Pending; 
 1437:     my %Expired;
 1438:     #
 1439:     # Each role can either have not started yet (pending), be active, 
 1440:     #    or have expired.
 1441:     #
 1442:     # If there is an active role, we are done.
 1443:     #
 1444:     # If there is more than one role which has not started yet, 
 1445:     #     choose the one which will start sooner
 1446:     # If there is one role which has not started yet, return it.
 1447:     #
 1448:     # If there is more than one expired role, choose the one which ended last.
 1449:     # If there is a role which has expired, return it.
 1450:     #
 1451:     $courseid = &courseid_to_courseurl($courseid);
 1452:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1453:     foreach my $key (keys(%roleshash)) {
 1454:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1455:         my $section=$1;
 1456:         if ($key eq $courseid.'_st') { $section=''; }
 1457:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1458:         my $now=time;
 1459:         if (defined($end) && $end && ($now > $end)) {
 1460:             $Expired{$end}=$section;
 1461:             next;
 1462:         }
 1463:         if (defined($start) && $start && ($now < $start)) {
 1464:             $Pending{$start}=$section;
 1465:             next;
 1466:         }
 1467:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1468:     }
 1469:     #
 1470:     # Presumedly there will be few matching roles from the above
 1471:     # loop and the sorting time will be negligible.
 1472:     if (scalar(keys(%Pending))) {
 1473:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1474:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1475:     } 
 1476:     if (scalar(keys(%Expired))) {
 1477:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1478:         my $time = pop(@sorted);
 1479:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1480:     }
 1481:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1482: }
 1483: 
 1484: sub save_cache {
 1485:     &purge_remembered();
 1486:     #&Apache::loncommon::validate_page();
 1487:     undef(%env);
 1488:     undef($env_loaded);
 1489: }
 1490: 
 1491: my $to_remember=-1;
 1492: my %remembered;
 1493: my %accessed;
 1494: my $kicks=0;
 1495: my $hits=0;
 1496: sub make_key {
 1497:     my ($name,$id) = @_;
 1498:     if (length($id) > 65 
 1499: 	&& length(&escape($id)) > 200) {
 1500: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1501:     }
 1502:     return &escape($name.':'.$id);
 1503: }
 1504: 
 1505: sub devalidate_cache_new {
 1506:     my ($name,$id,$debug) = @_;
 1507:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1508:     $id=&make_key($name,$id);
 1509:     $memcache->delete($id);
 1510:     delete($remembered{$id});
 1511:     delete($accessed{$id});
 1512: }
 1513: 
 1514: sub is_cached_new {
 1515:     my ($name,$id,$debug) = @_;
 1516:     $id=&make_key($name,$id);
 1517:     if (exists($remembered{$id})) {
 1518: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1519: 	$accessed{$id}=[&gettimeofday()];
 1520: 	$hits++;
 1521: 	return ($remembered{$id},1);
 1522:     }
 1523:     my $value = $memcache->get($id);
 1524:     if (!(defined($value))) {
 1525: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1526: 	return (undef,undef);
 1527:     }
 1528:     if ($value eq '__undef__') {
 1529: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1530: 	$value=undef;
 1531:     }
 1532:     &make_room($id,$value,$debug);
 1533:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1534:     return ($value,1);
 1535: }
 1536: 
 1537: sub do_cache_new {
 1538:     my ($name,$id,$value,$time,$debug) = @_;
 1539:     $id=&make_key($name,$id);
 1540:     my $setvalue=$value;
 1541:     if (!defined($setvalue)) {
 1542: 	$setvalue='__undef__';
 1543:     }
 1544:     if (!defined($time) ) {
 1545: 	$time=600;
 1546:     }
 1547:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1548:     my $result = $memcache->set($id,$setvalue,$time);
 1549:     if (! $result) {
 1550: 	&logthis("caching of id -> $id  failed");
 1551: 	$memcache->disconnect_all();
 1552:     }
 1553:     # need to make a copy of $value
 1554:     &make_room($id,$value,$debug);
 1555:     return $value;
 1556: }
 1557: 
 1558: sub make_room {
 1559:     my ($id,$value,$debug)=@_;
 1560: 
 1561:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1562:                                     : $value;
 1563:     if ($to_remember<0) { return; }
 1564:     $accessed{$id}=[&gettimeofday()];
 1565:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1566:     my $to_kick;
 1567:     my $max_time=0;
 1568:     foreach my $other (keys(%accessed)) {
 1569: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1570: 	    $to_kick=$other;
 1571: 	    $max_time=&tv_interval($accessed{$other});
 1572: 	}
 1573:     }
 1574:     delete($remembered{$to_kick});
 1575:     delete($accessed{$to_kick});
 1576:     $kicks++;
 1577:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1578:     return;
 1579: }
 1580: 
 1581: sub purge_remembered {
 1582:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1583:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1584:     undef(%remembered);
 1585:     undef(%accessed);
 1586: }
 1587: # ------------------------------------- Read an entry from a user's environment
 1588: 
 1589: sub userenvironment {
 1590:     my ($udom,$unam,@what)=@_;
 1591:     my $items;
 1592:     foreach my $item (@what) {
 1593:         $items.=&escape($item).'&';
 1594:     }
 1595:     $items=~s/\&$//;
 1596:     my %returnhash=();
 1597:     my @answer=split(/\&/,
 1598:                 &reply('get:'.$udom.':'.$unam.':environment:'.$items,
 1599:                       &homeserver($unam,$udom)));
 1600:     my $i;
 1601:     for ($i=0;$i<=$#what;$i++) {
 1602: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1603:     }
 1604:     return %returnhash;
 1605: }
 1606: 
 1607: # ---------------------------------------------------------- Get a studentphoto
 1608: sub studentphoto {
 1609:     my ($udom,$unam,$ext) = @_;
 1610:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1611:     if (defined($env{'request.course.id'})) {
 1612:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1613:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1614:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1615:             } else {
 1616:                 my ($result,$perm_reqd)=
 1617: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1618:                 if ($result eq 'ok') {
 1619:                     if (!($perm_reqd eq 'yes')) {
 1620:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1621:                     }
 1622:                 }
 1623:             }
 1624:         }
 1625:     } else {
 1626:         my ($result,$perm_reqd) = 
 1627: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1628:         if ($result eq 'ok') {
 1629:             if (!($perm_reqd eq 'yes')) {
 1630:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1631:             }
 1632:         }
 1633:     }
 1634:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1635: }
 1636: 
 1637: sub retrievestudentphoto {
 1638:     my ($udom,$unam,$ext,$type) = @_;
 1639:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1640:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1641:     if ($ret eq 'ok') {
 1642:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1643:         if ($type eq 'thumbnail') {
 1644:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1645:         }
 1646:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1647:         return $tokenurl;
 1648:     } else {
 1649:         if ($type eq 'thumbnail') {
 1650:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1651:         } else { 
 1652:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1653:         }
 1654:     }
 1655: }
 1656: 
 1657: # -------------------------------------------------------------------- New chat
 1658: 
 1659: sub chatsend {
 1660:     my ($newentry,$anon,$group)=@_;
 1661:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1662:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1663:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1664:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1665: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1666: 		   &escape($newentry)).':'.$group,$chome);
 1667: }
 1668: 
 1669: # ------------------------------------------ Find current version of a resource
 1670: 
 1671: sub getversion {
 1672:     my $fname=&clutter(shift);
 1673:     unless ($fname=~/^\/res\//) { return -1; }
 1674:     return &currentversion(&filelocation('',$fname));
 1675: }
 1676: 
 1677: sub currentversion {
 1678:     my $fname=shift;
 1679:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1680:     if (defined($cached)) { return $result; }
 1681:     my $author=$fname;
 1682:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1683:     my ($udom,$uname)=split(/\//,$author);
 1684:     my $home=homeserver($uname,$udom);
 1685:     if ($home eq 'no_host') { 
 1686:         return -1; 
 1687:     }
 1688:     my $answer=reply("currentversion:$fname",$home);
 1689:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1690: 	return -1;
 1691:     }
 1692:     return &do_cache_new('resversion',$fname,$answer,600);
 1693: }
 1694: 
 1695: # ----------------------------- Subscribe to a resource, return URL if possible
 1696: 
 1697: sub subscribe {
 1698:     my $fname=shift;
 1699:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1700:     $fname=~s/[\n\r]//g;
 1701:     my $author=$fname;
 1702:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1703:     my ($udom,$uname)=split(/\//,$author);
 1704:     my $home=homeserver($uname,$udom);
 1705:     if ($home eq 'no_host') {
 1706:         return 'not_found';
 1707:     }
 1708:     my $answer=reply("sub:$fname",$home);
 1709:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1710: 	$answer.=' by '.$home;
 1711:     }
 1712:     return $answer;
 1713: }
 1714:     
 1715: # -------------------------------------------------------------- Replicate file
 1716: 
 1717: sub repcopy {
 1718:     my $filename=shift;
 1719:     $filename=~s/\/+/\//g;
 1720:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1721:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1722:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1723: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1724: 	return &repcopy_userfile($filename);
 1725:     }
 1726:     $filename=~s/[\n\r]//g;
 1727:     my $transname="$filename.in.transfer";
 1728: # FIXME: this should flock
 1729:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1730:     my $remoteurl=subscribe($filename);
 1731:     if ($remoteurl =~ /^con_lost by/) {
 1732: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1733:            return 'unavailable';
 1734:     } elsif ($remoteurl eq 'not_found') {
 1735: 	   #&logthis("Subscribe returned not_found: $filename");
 1736: 	   return 'not_found';
 1737:     } elsif ($remoteurl =~ /^rejected by/) {
 1738: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1739:            return 'forbidden';
 1740:     } elsif ($remoteurl eq 'directory') {
 1741:            return 'ok';
 1742:     } else {
 1743:         my $author=$filename;
 1744:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1745:         my ($udom,$uname)=split(/\//,$author);
 1746:         my $home=homeserver($uname,$udom);
 1747:         unless ($home eq $perlvar{'lonHostID'}) {
 1748:            my @parts=split(/\//,$filename);
 1749:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1750:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1751:                &logthis("Malconfiguration for replication: $filename");
 1752: 	       return 'bad_request';
 1753:            }
 1754:            my $count;
 1755:            for ($count=5;$count<$#parts;$count++) {
 1756:                $path.="/$parts[$count]";
 1757:                if ((-e $path)!=1) {
 1758: 		   mkdir($path,0777);
 1759:                }
 1760:            }
 1761:            my $ua=new LWP::UserAgent;
 1762:            my $request=new HTTP::Request('GET',"$remoteurl");
 1763:            my $response=$ua->request($request,$transname);
 1764:            if ($response->is_error()) {
 1765: 	       unlink($transname);
 1766:                my $message=$response->status_line;
 1767:                &logthis("<font color=\"blue\">WARNING:"
 1768:                        ." LWP get: $message: $filename</font>");
 1769:                return 'unavailable';
 1770:            } else {
 1771: 	       if ($remoteurl!~/\.meta$/) {
 1772:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1773:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1774:                   if ($mresponse->is_error()) {
 1775: 		      unlink($filename.'.meta');
 1776:                       &logthis(
 1777:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1778:                   }
 1779: 	       }
 1780:                rename($transname,$filename);
 1781:                return 'ok';
 1782:            }
 1783:        }
 1784:     }
 1785: }
 1786: 
 1787: # ------------------------------------------------ Get server side include body
 1788: sub ssi_body {
 1789:     my ($filelink,%form)=@_;
 1790:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1791:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1792:     }
 1793:     my $output='';
 1794:     my $response;
 1795:     if ($filelink=~/^https?\:/) {
 1796:        ($output,$response)=&externalssi($filelink);
 1797:     } else {
 1798:        ($output,$response)=&ssi($filelink,%form);
 1799:     }
 1800:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1801:     $output=~s/^.*?\<body[^\>]*\>//si;
 1802:     $output=~s/\<\/body\s*\>.*?$//si;
 1803:     if (wantarray) {
 1804:         return ($output, $response);
 1805:     } else {
 1806:         return $output;
 1807:     }
 1808: }
 1809: 
 1810: # --------------------------------------------------------- Server Side Include
 1811: 
 1812: sub absolute_url {
 1813:     my ($host_name) = @_;
 1814:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1815:     if ($host_name eq '') {
 1816: 	$host_name = $ENV{'SERVER_NAME'};
 1817:     }
 1818:     return $protocol.$host_name;
 1819: }
 1820: 
 1821: #
 1822: #   Server side include.
 1823: # Parameters:
 1824: #  fn     Possibly encrypted resource name/id.
 1825: #  form   Hash that describes how the rendering should be done
 1826: #         and other things.
 1827: # Returns:
 1828: #   Scalar context: The content of the response.
 1829: #   Array context:  2 element list of the content and the full response object.
 1830: #     
 1831: sub ssi {
 1832: 
 1833:     my ($fn,%form)=@_;
 1834:     my $ua=new LWP::UserAgent;
 1835:     my $request;
 1836: 
 1837:     $form{'no_update_last_known'}=1;
 1838:     &Apache::lonenc::check_encrypt(\$fn);
 1839:     if (%form) {
 1840:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1841:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1842:     } else {
 1843:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1844:     }
 1845: 
 1846:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1847:     my $response=$ua->request($request);
 1848: 
 1849:     if (wantarray) {
 1850: 	return ($response->content, $response);
 1851:     } else {
 1852: 	return $response->content;
 1853:     }
 1854: }
 1855: 
 1856: sub externalssi {
 1857:     my ($url)=@_;
 1858:     my $ua=new LWP::UserAgent;
 1859:     my $request=new HTTP::Request('GET',$url);
 1860:     my $response=$ua->request($request);
 1861:     if (wantarray) {
 1862:         return ($response->content, $response);
 1863:     } else {
 1864:         return $response->content;
 1865:     }
 1866: }
 1867: 
 1868: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1869: 
 1870: sub allowuploaded {
 1871:     my ($srcurl,$url)=@_;
 1872:     $url=&clutter(&declutter($url));
 1873:     my $dir=$url;
 1874:     $dir=~s/\/[^\/]+$//;
 1875:     my %httpref=();
 1876:     my $httpurl=&hreflocation('',$url);
 1877:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1878:     &Apache::lonnet::appenv(\%httpref);
 1879: }
 1880: 
 1881: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1882: # input: action, courseID, current domain, intended
 1883: #        path to file, source of file, instruction to parse file for objects,
 1884: #        ref to hash for embedded objects,
 1885: #        ref to hash for codebase of java objects.
 1886: #
 1887: # output: url to file (if action was uploaddoc), 
 1888: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1889: #
 1890: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1891: # course.
 1892: #
 1893: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1894: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1895: #          course's home server.
 1896: #
 1897: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1898: #          be copied from $source (current location) to 
 1899: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1900: #         and will then be copied to
 1901: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1902: #         course's home server.
 1903: #
 1904: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1905: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1906: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1907: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1908: #         in course's home server.
 1909: #
 1910: 
 1911: sub process_coursefile {
 1912:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1913:     my $fetchresult;
 1914:     my $home=&homeserver($docuname,$docudom);
 1915:     if ($action eq 'propagate') {
 1916:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1917: 			     $home);
 1918:     } else {
 1919:         my $fpath = '';
 1920:         my $fname = $file;
 1921:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1922:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1923:         my $filepath = &build_filepath($fpath);
 1924:         if ($action eq 'copy') {
 1925:             if ($source eq '') {
 1926:                 $fetchresult = 'no source file';
 1927:                 return $fetchresult;
 1928:             } else {
 1929:                 my $destination = $filepath.'/'.$fname;
 1930:                 rename($source,$destination);
 1931:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1932:                                  $home);
 1933:             }
 1934:         } elsif ($action eq 'uploaddoc') {
 1935:             open(my $fh,'>'.$filepath.'/'.$fname);
 1936:             print $fh $env{'form.'.$source};
 1937:             close($fh);
 1938:             if ($parser eq 'parse') {
 1939:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 1940:                 unless ($parse_result eq 'ok') {
 1941:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1942:                 }
 1943:             }
 1944:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1945:                                  $home);
 1946:             if ($fetchresult eq 'ok') {
 1947:                 return '/uploaded/'.$fpath.'/'.$fname;
 1948:             } else {
 1949:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1950:                         ' to host '.$home.': '.$fetchresult);
 1951:                 return '/adm/notfound.html';
 1952:             }
 1953:         }
 1954:     }
 1955:     unless ( $fetchresult eq 'ok') {
 1956:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1957:              ' to host '.$home.': '.$fetchresult);
 1958:     }
 1959:     return $fetchresult;
 1960: }
 1961: 
 1962: sub build_filepath {
 1963:     my ($fpath) = @_;
 1964:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1965:     unless ($fpath eq '') {
 1966:         my @parts=split('/',$fpath);
 1967:         foreach my $part (@parts) {
 1968:             $filepath.= '/'.$part;
 1969:             if ((-e $filepath)!=1) {
 1970:                 mkdir($filepath,0777);
 1971:             }
 1972:         }
 1973:     }
 1974:     return $filepath;
 1975: }
 1976: 
 1977: sub store_edited_file {
 1978:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1979:     my $file = $primary_url;
 1980:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1981:     my $fpath = '';
 1982:     my $fname = $file;
 1983:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1984:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1985:     my $filepath = &build_filepath($fpath);
 1986:     open(my $fh,'>'.$filepath.'/'.$fname);
 1987:     print $fh $content;
 1988:     close($fh);
 1989:     my $home=&homeserver($docuname,$docudom);
 1990:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1991: 			  $home);
 1992:     if ($$fetchresult eq 'ok') {
 1993:         return '/uploaded/'.$fpath.'/'.$fname;
 1994:     } else {
 1995:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1996: 		 ' to host '.$home.': '.$$fetchresult);
 1997:         return '/adm/notfound.html';
 1998:     }
 1999: }
 2000: 
 2001: sub clean_filename {
 2002:     my ($fname,$args)=@_;
 2003: # Replace Windows backslashes by forward slashes
 2004:     $fname=~s/\\/\//g;
 2005:     if (!$args->{'keep_path'}) {
 2006:         # Get rid of everything but the actual filename
 2007: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2008:     }
 2009: # Replace spaces by underscores
 2010:     $fname=~s/\s+/\_/g;
 2011: # Replace all other weird characters by nothing
 2012:     $fname=~s{[^/\w\.\-]}{}g;
 2013: # Replace all .\d. sequences with _\d. so they no longer look like version
 2014: # numbers
 2015:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2016:     return $fname;
 2017: }
 2018: 
 2019: #Wrapper function for userphotoupload
 2020: sub userphotoupload
 2021: {
 2022: 	my($formname,$subdir) = @_;
 2023: 	$upload_photo_form = 1;
 2024: 	return &userfileupload($formname,undef,$subdir);
 2025: }
 2026: 
 2027: # --------------- Take an uploaded file and put it into the userfiles directory
 2028: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2029: #                    the desired filenam is in $env{"form.$formname.filename"}
 2030: #        $coursedoc - if true up to the current course
 2031: #                     if false
 2032: #        $subdir - directory in userfile to store the file into
 2033: #        $parser - instruction to parse file for objects ($parser = parse)    
 2034: #        $allfiles - reference to hash for embedded objects
 2035: #        $codebase - reference to hash for codebase of java objects
 2036: #        $desuname - username for permanent storage of uploaded file
 2037: #        $dsetudom - domain for permanaent storage of uploaded file
 2038: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2039: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2040: # 
 2041: # output: url of file in userspace, or error: <message> 
 2042: #             or /adm/notfound.html if failure to upload occurse
 2043: 
 2044: 
 2045: sub userfileupload {
 2046:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 2047:         $destudom,$thumbwidth,$thumbheight)=@_;
 2048:     if (!defined($subdir)) { $subdir='unknown'; }
 2049:     my $fname=$env{'form.'.$formname.'.filename'};
 2050:     $fname=&clean_filename($fname);
 2051: # See if there is anything left
 2052:     unless ($fname) { return 'error: no uploaded file'; }
 2053:     chop($env{'form.'.$formname});
 2054:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 2055:         my $now = time;
 2056:         my $filepath = 'tmp/helprequests/'.$now;
 2057:         my @parts=split(/\//,$filepath);
 2058:         my $fullpath = $perlvar{'lonDaemons'};
 2059:         for (my $i=0;$i<@parts;$i++) {
 2060:             $fullpath .= '/'.$parts[$i];
 2061:             if ((-e $fullpath)!=1) {
 2062:                 mkdir($fullpath,0777);
 2063:             }
 2064:         }
 2065:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2066:         print $fh $env{'form.'.$formname};
 2067:         close($fh);
 2068:         return $fullpath.'/'.$fname;
 2069:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 2070:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2071:                        '_'.$env{'user.domain'}.'/pending';
 2072:         my @parts=split(/\//,$filepath);
 2073:         my $fullpath = $perlvar{'lonDaemons'};
 2074:         for (my $i=0;$i<@parts;$i++) {
 2075:             $fullpath .= '/'.$parts[$i];
 2076:             if ((-e $fullpath)!=1) {
 2077:                 mkdir($fullpath,0777);
 2078:             }
 2079:         }
 2080:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2081:         print $fh $env{'form.'.$formname};
 2082:         close($fh);
 2083:         return $fullpath.'/'.$fname;
 2084:     }
 2085:     
 2086: # Create the directory if not present
 2087:     $fname="$subdir/$fname";
 2088:     if ($coursedoc) {
 2089: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2090: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2091:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2092:             return &finishuserfileupload($docuname,$docudom,
 2093: 					 $formname,$fname,$parser,$allfiles,
 2094: 					 $codebase,$thumbwidth,$thumbheight);
 2095:         } else {
 2096:             $fname=$env{'form.folder'}.'/'.$fname;
 2097:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2098: 				       $fname,$formname,$parser,
 2099: 				       $allfiles,$codebase);
 2100:         }
 2101:     } elsif (defined($destuname)) {
 2102:         my $docuname=$destuname;
 2103:         my $docudom=$destudom;
 2104: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2105: 				     $parser,$allfiles,$codebase,
 2106:                                      $thumbwidth,$thumbheight);
 2107:         
 2108:     } else {
 2109:         my $docuname=$env{'user.name'};
 2110:         my $docudom=$env{'user.domain'};
 2111:         if (exists($env{'form.group'})) {
 2112:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2113:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2114:         }
 2115: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2116: 				     $parser,$allfiles,$codebase,
 2117:                                      $thumbwidth,$thumbheight);
 2118:     }
 2119: }
 2120: 
 2121: sub finishuserfileupload {
 2122:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2123:         $thumbwidth,$thumbheight) = @_;
 2124:     my $path=$docudom.'/'.$docuname.'/';
 2125:     my $filepath=$perlvar{'lonDocRoot'};
 2126:     my ($fnamepath,$file,$fetchthumb);
 2127:     $file=$fname;
 2128:     if ($fname=~m|/|) {
 2129:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2130: 	$path.=$fnamepath.'/';
 2131:     }
 2132:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2133:     my $count;
 2134:     for ($count=4;$count<=$#parts;$count++) {
 2135:         $filepath.="/$parts[$count]";
 2136:         if ((-e $filepath)!=1) {
 2137: 	    mkdir($filepath,0777);
 2138:         }
 2139:     }
 2140: # Save the file
 2141:     {
 2142: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2143: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2144: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2145: 	    return '/adm/notfound.html';
 2146: 	}
 2147: 	if (!print FH ($env{'form.'.$formname})) {
 2148: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2149: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2150: 	    return '/adm/notfound.html';
 2151: 	}
 2152: 	close(FH);
 2153: 	if($upload_photo_form==1)
 2154: 	{
 2155: 		my $ima = Image::Magick->new;                       
 2156:             	$ima->Read($filepath.'/'.$file);
 2157: 		if($ima->Get('width') > 300)
 2158: 		{
 2159: 			my $factor = $ima->Get('width')/300;
 2160:              		$ima->Scale( width=>300, height=>$ima->Get('height')/$factor );
 2161: 		}
 2162: 		if($ima->Get('height') > 400)
 2163:                 {
 2164:                         my $factor = $ima->Get('height')/400;
 2165:                         $ima->Scale( width=>$ima->Get('width')/$factor, height=>400);
 2166:                 }
 2167:  
 2168: 		
 2169: 		$ima->Write($filepath.'/'.$file);
 2170: 		$upload_photo_form = 0;
 2171: 	}
 2172:     }
 2173:     if ($parser eq 'parse') {
 2174:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
 2175: 						   $codebase);
 2176:         unless ($parse_result eq 'ok') {
 2177:             &logthis('Failed to parse '.$filepath.$file.
 2178: 		     ' for embedded media: '.$parse_result); 
 2179:         }
 2180:     }
 2181:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2182:         my $input = $filepath.'/'.$file;
 2183:         my $output = $filepath.'/'.'tn-'.$file;
 2184:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2185:         system("convert -sample $thumbsize $input $output");
 2186:         if (-e $filepath.'/'.'tn-'.$file) {
 2187:             $fetchthumb  = 1; 
 2188:         }
 2189:     }
 2190:  
 2191: # Notify homeserver to grep it
 2192: #
 2193:     my $docuhome=&homeserver($docuname,$docudom);
 2194:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2195:     if ($fetchresult eq 'ok') {
 2196:         if ($fetchthumb) {
 2197:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2198:             if ($thumbresult ne 'ok') {
 2199:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2200:                          $docuhome.': '.$thumbresult);
 2201:             }
 2202:         }
 2203: #
 2204: # Return the URL to it
 2205:         return '/uploaded/'.$path.$file;
 2206:     } else {
 2207:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2208: 		 ': '.$fetchresult);
 2209:         return '/adm/notfound.html';
 2210:     }
 2211: }
 2212: 
 2213: sub extract_embedded_items {
 2214:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 2215:     my @state = ();
 2216:     my %javafiles = (
 2217:                       codebase => '',
 2218:                       code => '',
 2219:                       archive => ''
 2220:                     );
 2221:     my %mediafiles = (
 2222:                       src => '',
 2223:                       movie => '',
 2224:                      );
 2225:     my $p;
 2226:     if ($content) {
 2227:         $p = HTML::LCParser->new($content);
 2228:     } else {
 2229:         $p = HTML::LCParser->new($fullpath);
 2230:     }
 2231:     while (my $t=$p->get_token()) {
 2232: 	if ($t->[0] eq 'S') {
 2233: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2234: 	    push(@state, $tagname);
 2235:             if (lc($tagname) eq 'allow') {
 2236:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2237:             }
 2238: 	    if (lc($tagname) eq 'img') {
 2239: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2240: 	    }
 2241: 	    if (lc($tagname) eq 'a') {
 2242: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2243: 	    }
 2244:             if (lc($tagname) eq 'script') {
 2245:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2246:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2247:                 } else {
 2248:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2249:                 }
 2250:             }
 2251:             if (lc($tagname) eq 'link') {
 2252:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2253:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2254:                 }
 2255:             }
 2256: 	    if (lc($tagname) eq 'object' ||
 2257: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2258: 		foreach my $item (keys(%javafiles)) {
 2259: 		    $javafiles{$item} = '';
 2260: 		}
 2261: 	    }
 2262: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2263: 		my $name = lc($attr->{'name'});
 2264: 		foreach my $item (keys(%javafiles)) {
 2265: 		    if ($name eq $item) {
 2266: 			$javafiles{$item} = $attr->{'value'};
 2267: 			last;
 2268: 		    }
 2269: 		}
 2270: 		foreach my $item (keys(%mediafiles)) {
 2271: 		    if ($name eq $item) {
 2272: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2273: 			last;
 2274: 		    }
 2275: 		}
 2276: 	    }
 2277: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2278: 		foreach my $item (keys(%javafiles)) {
 2279: 		    if ($attr->{$item}) {
 2280: 			$javafiles{$item} = $attr->{$item};
 2281: 			last;
 2282: 		    }
 2283: 		}
 2284: 		foreach my $item (keys(%mediafiles)) {
 2285: 		    if ($attr->{$item}) {
 2286: 			&add_filetype($allfiles,$attr->{$item},$item);
 2287: 			last;
 2288: 		    }
 2289: 		}
 2290: 	    }
 2291: 	} elsif ($t->[0] eq 'E') {
 2292: 	    my ($tagname) = ($t->[1]);
 2293: 	    if ($javafiles{'codebase'} ne '') {
 2294: 		$javafiles{'codebase'} .= '/';
 2295: 	    }  
 2296: 	    if (lc($tagname) eq 'applet' ||
 2297: 		lc($tagname) eq 'object' ||
 2298: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2299: 		) {
 2300: 		foreach my $item (keys(%javafiles)) {
 2301: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2302: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2303: 			&add_filetype($allfiles,$file,$item);
 2304: 		    }
 2305: 		}
 2306: 	    } 
 2307: 	    pop @state;
 2308: 	}
 2309:     }
 2310:     return 'ok';
 2311: }
 2312: 
 2313: sub add_filetype {
 2314:     my ($allfiles,$file,$type)=@_;
 2315:     if (exists($allfiles->{$file})) {
 2316: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2317: 	    push(@{$allfiles->{$file}}, &escape($type));
 2318: 	}
 2319:     } else {
 2320: 	@{$allfiles->{$file}} = (&escape($type));
 2321:     }
 2322: }
 2323: 
 2324: sub removeuploadedurl {
 2325:     my ($url)=@_;
 2326:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 2327:     return &removeuserfile($uname,$udom,$fname);
 2328: }
 2329: 
 2330: sub removeuserfile {
 2331:     my ($docuname,$docudom,$fname)=@_;
 2332:     my $home=&homeserver($docuname,$docudom);
 2333:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2334:     if ($result eq 'ok') {
 2335:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2336:             my $metafile = $fname.'.meta';
 2337:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2338: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2339:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2340:             my $sqlresult = 
 2341:                 &update_portfolio_table($docuname,$docudom,$file,
 2342:                                         'portfolio_metadata',$group,
 2343:                                         'delete');
 2344:         }
 2345:     }
 2346:     return $result;
 2347: }
 2348: 
 2349: sub mkdiruserfile {
 2350:     my ($docuname,$docudom,$dir)=@_;
 2351:     my $home=&homeserver($docuname,$docudom);
 2352:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2353: }
 2354: 
 2355: sub renameuserfile {
 2356:     my ($docuname,$docudom,$old,$new)=@_;
 2357:     my $home=&homeserver($docuname,$docudom);
 2358:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2359:                         &escape("$old").':'.&escape("$new"),$home);
 2360:     if ($result eq 'ok') {
 2361:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2362:             my $oldmeta = $old.'.meta';
 2363:             my $newmeta = $new.'.meta';
 2364:             my $metaresult = 
 2365:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2366: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2367:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2368:             my $sqlresult = 
 2369:                 &update_portfolio_table($docuname,$docudom,$file,
 2370:                                         'portfolio_metadata',$group,
 2371:                                         'delete');
 2372:         }
 2373:     }
 2374:     return $result;
 2375: }
 2376: 
 2377: # ------------------------------------------------------------------------- Log
 2378: 
 2379: sub log {
 2380:     my ($dom,$nam,$hom,$what)=@_;
 2381:     return critical("log:$dom:$nam:$what",$hom);
 2382: }
 2383: 
 2384: # ------------------------------------------------------------------ Course Log
 2385: #
 2386: # This routine flushes several buffers of non-mission-critical nature
 2387: #
 2388: 
 2389: sub flushcourselogs {
 2390:     &logthis('Flushing log buffers');
 2391: #
 2392: # course logs
 2393: # This is a log of all transactions in a course, which can be used
 2394: # for data mining purposes
 2395: #
 2396: # It also collects the courseid database, which lists last transaction
 2397: # times and course titles for all courseids
 2398: #
 2399:     my %courseidbuffer=();
 2400:     foreach my $crsid (keys(%courselogs)) {
 2401:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2402: 		          &escape($courselogs{$crsid}),
 2403: 		          $coursehombuf{$crsid}) eq 'ok') {
 2404: 	    delete $courselogs{$crsid};
 2405:         } else {
 2406:             &logthis('Failed to flush log buffer for '.$crsid);
 2407:             if (length($courselogs{$crsid})>40000) {
 2408:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2409:                         " exceeded maximum size, deleting.</font>");
 2410:                delete $courselogs{$crsid};
 2411:             }
 2412:         }
 2413:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2414:             'description' => $coursedescrbuf{$crsid},
 2415:             'inst_code'    => $courseinstcodebuf{$crsid},
 2416:             'type'        => $coursetypebuf{$crsid},
 2417:             'owner'       => $courseownerbuf{$crsid},
 2418:         };
 2419:     }
 2420: #
 2421: # Write course id database (reverse lookup) to homeserver of courses 
 2422: # Is used in pickcourse
 2423: #
 2424:     foreach my $crs_home (keys(%courseidbuffer)) {
 2425:         my $response = &courseidput(&host_domain($crs_home),
 2426:                                     $courseidbuffer{$crs_home},
 2427:                                     $crs_home,'timeonly');
 2428:     }
 2429: #
 2430: # File accesses
 2431: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2432: #
 2433:     foreach my $entry (keys(%accesshash)) {
 2434:         if ($entry =~ /___count$/) {
 2435:             my ($dom,$name);
 2436:             ($dom,$name,undef)=
 2437: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2438:             if (! defined($dom) || $dom eq '' || 
 2439:                 ! defined($name) || $name eq '') {
 2440:                 my $cid = $env{'request.course.id'};
 2441:                 $dom  = $env{'request.'.$cid.'.domain'};
 2442:                 $name = $env{'request.'.$cid.'.num'};
 2443:             }
 2444:             my $value = $accesshash{$entry};
 2445:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2446:             my %temphash=($url => $value);
 2447:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2448:             if ($result eq 'ok') {
 2449:                 delete $accesshash{$entry};
 2450:             } elsif ($result eq 'unknown_cmd') {
 2451:                 # Target server has old code running on it.
 2452:                 my %temphash=($entry => $value);
 2453:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2454:                     delete $accesshash{$entry};
 2455:                 }
 2456:             }
 2457:         } else {
 2458:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2459:             my %temphash=($entry => $accesshash{$entry});
 2460:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2461:                 delete $accesshash{$entry};
 2462:             }
 2463:         }
 2464:     }
 2465: #
 2466: # Roles
 2467: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2468: #
 2469:     foreach my $entry (keys(%userrolehash)) {
 2470:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2471: 	    split(/\:/,$entry);
 2472:         if (&Apache::lonnet::put('nohist_userroles',
 2473:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2474:                 $rudom,$runame) eq 'ok') {
 2475: 	    delete $userrolehash{$entry};
 2476:         }
 2477:     }
 2478: #
 2479: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2480: #
 2481:     my %domrolebuffer = ();
 2482:     foreach my $entry (keys %domainrolehash) {
 2483:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2484:         if ($domrolebuffer{$rudom}) {
 2485:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2486:                       '='.&escape($domainrolehash{$entry});
 2487:         } else {
 2488:             $domrolebuffer{$rudom}.=&escape($entry).
 2489:                       '='.&escape($domainrolehash{$entry});
 2490:         }
 2491:         delete $domainrolehash{$entry};
 2492:     }
 2493:     foreach my $dom (keys(%domrolebuffer)) {
 2494: 	my %servers = &get_servers($dom,'library');
 2495: 	foreach my $tryserver (keys(%servers)) {
 2496: 	    unless (&reply('domroleput:'.$dom.':'.
 2497: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2498: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2499: 	    }
 2500:         }
 2501:     }
 2502:     $dumpcount++;
 2503: }
 2504: 
 2505: sub courselog {
 2506:     my $what=shift;
 2507:     $what=time.':'.$what;
 2508:     unless ($env{'request.course.id'}) { return ''; }
 2509:     $coursedombuf{$env{'request.course.id'}}=
 2510:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2511:     $coursenumbuf{$env{'request.course.id'}}=
 2512:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2513:     $coursehombuf{$env{'request.course.id'}}=
 2514:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2515:     $coursedescrbuf{$env{'request.course.id'}}=
 2516:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2517:     $courseinstcodebuf{$env{'request.course.id'}}=
 2518:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2519:     $courseownerbuf{$env{'request.course.id'}}=
 2520:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2521:     $coursetypebuf{$env{'request.course.id'}}=
 2522:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2523:     if (defined $courselogs{$env{'request.course.id'}}) {
 2524: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2525:     } else {
 2526: 	$courselogs{$env{'request.course.id'}}.=$what;
 2527:     }
 2528:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2529: 	&flushcourselogs();
 2530:     }
 2531: }
 2532: 
 2533: sub courseacclog {
 2534:     my $fnsymb=shift;
 2535:     unless ($env{'request.course.id'}) { return ''; }
 2536:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2537:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2538:         $what.=':POST';
 2539:         # FIXME: Probably ought to escape things....
 2540: 	foreach my $key (keys(%env)) {
 2541:             if ($key=~/^form\.(.*)/) {
 2542:                 my $formitem = $1;
 2543:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 2544:                     $what.=':'.$formitem.'='.$env{$key};
 2545:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 2546:                     $what.=':'.$formitem.'='.$env{$key};
 2547:                 }
 2548:             }
 2549:         }
 2550:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2551:         # FIXME: We should not be depending on a form parameter that someone
 2552:         # editing lonsearchcat.pm might change in the future.
 2553:         if ($env{'form.phase'} eq 'course_search') {
 2554:             $what.= ':POST';
 2555:             # FIXME: Probably ought to escape things....
 2556:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2557:                                  'crsdiscuss') {
 2558:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2559:             }
 2560:         }
 2561:     }
 2562:     &courselog($what);
 2563: }
 2564: 
 2565: sub countacc {
 2566:     my $url=&declutter(shift);
 2567:     return if (! defined($url) || $url eq '');
 2568:     unless ($env{'request.course.id'}) { return ''; }
 2569:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2570:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2571:     $accesshash{$key}++;
 2572: }
 2573: 
 2574: sub linklog {
 2575:     my ($from,$to)=@_;
 2576:     $from=&declutter($from);
 2577:     $to=&declutter($to);
 2578:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2579:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2580: }
 2581:   
 2582: sub userrolelog {
 2583:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2584:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2585:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2586:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2587:         ($trole=~/^ta/)) {
 2588:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2589:        $userrolehash
 2590:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2591:                     =$tend.':'.$tstart;
 2592:     }
 2593:     if (($env{'request.role'} =~ /dc\./) &&
 2594: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2595: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2596: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
 2597:        $userrolehash
 2598:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2599:                     =$tend.':'.$tstart;
 2600:     }
 2601:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2602:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2603:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2604:         ($trole=~/^sc/)) {
 2605:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2606:        $domainrolehash
 2607:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2608:                     = $tend.':'.$tstart;
 2609:     }
 2610: }
 2611: 
 2612: sub courserolelog {
 2613:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 2614:     if (($trole eq 'cc') || ($trole eq 'in') ||
 2615:         ($trole eq 'ep') || ($trole eq 'ad') ||
 2616:         ($trole eq 'ta') || ($trole eq 'st') ||
 2617:         ($trole=~/^cr/) || ($trole eq 'gr')) {
 2618:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 2619:             my $cdom = $1;
 2620:             my $cnum = $2;
 2621:             my $sec = $3;
 2622:             my $namespace = 'rolelog';
 2623:             my %storehash = (
 2624:                                role    => $trole,
 2625:                                start   => $tstart,
 2626:                                end     => $tend,
 2627:                                selfenroll => $selfenroll,
 2628:                                context    => $context,
 2629:                             );
 2630:             if ($trole eq 'gr') {
 2631:                 $namespace = 'groupslog';
 2632:                 $storehash{'group'} = $sec;
 2633:             } else {
 2634:                 $storehash{'section'} = $sec;
 2635:             }
 2636:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 2637:         }
 2638:     }
 2639:     return;
 2640: }
 2641: 
 2642: sub get_course_adv_roles {
 2643:     my ($cid,$codes) = @_;
 2644:     $cid=$env{'request.course.id'} unless (defined($cid));
 2645:     my %coursehash=&coursedescription($cid);
 2646:     my %nothide=();
 2647:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2648:         if ($user !~ /:/) {
 2649: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2650:         } else {
 2651:             $nothide{$user}=1;
 2652:         }
 2653:     }
 2654:     my %returnhash=();
 2655:     my %dumphash=
 2656:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2657:     my $now=time;
 2658:     foreach my $entry (keys %dumphash) {
 2659: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2660:         if (($tstart) && ($tstart<0)) { next; }
 2661:         if (($tend) && ($tend<$now)) { next; }
 2662:         if (($tstart) && ($now<$tstart)) { next; }
 2663:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2664: 	if ($username eq '' || $domain eq '') { next; }
 2665: 	if ((&privileged($username,$domain)) && 
 2666: 	    (!$nothide{$username.':'.$domain})) { next; }
 2667: 	if ($role eq 'cr') { next; }
 2668:         if ($codes) {
 2669:             if ($section) { $role .= ':'.$section; }
 2670:             if ($returnhash{$role}) {
 2671:                 $returnhash{$role}.=','.$username.':'.$domain;
 2672:             } else {
 2673:                 $returnhash{$role}=$username.':'.$domain;
 2674:             }
 2675:         } else {
 2676:             my $key=&plaintext($role);
 2677:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 2678:             if ($returnhash{$key}) {
 2679: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2680:             } else {
 2681:                 $returnhash{$key}=$username.':'.$domain;
 2682:             }
 2683:         }
 2684:     }
 2685:     return %returnhash;
 2686: }
 2687: 
 2688: sub get_my_roles {
 2689:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2690:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2691:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2692:     my (%dumphash,%nothide);
 2693:     if ($context eq 'userroles') { 
 2694:         %dumphash = &dump('roles',$udom,$uname);
 2695:     } else {
 2696:         %dumphash=
 2697:             &dump('nohist_userroles',$udom,$uname);
 2698:         if ($hidepriv) {
 2699:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2700:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2701:                 if ($user !~ /:/) {
 2702:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2703:                 } else {
 2704:                     $nothide{$user} = 1;
 2705:                 }
 2706:             }
 2707:         }
 2708:     }
 2709:     my %returnhash=();
 2710:     my $now=time;
 2711:     foreach my $entry (keys(%dumphash)) {
 2712:         my ($role,$tend,$tstart);
 2713:         if ($context eq 'userroles') {
 2714: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2715:         } else {
 2716:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2717:         }
 2718:         if (($tstart) && ($tstart<0)) { next; }
 2719:         my $status = 'active';
 2720:         if (($tend) && ($tend<=$now)) {
 2721:             $status = 'previous';
 2722:         } 
 2723:         if (($tstart) && ($now<$tstart)) {
 2724:             $status = 'future';
 2725:         }
 2726:         if (ref($types) eq 'ARRAY') {
 2727:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2728:                 next;
 2729:             } 
 2730:         } else {
 2731:             if ($status ne 'active') {
 2732:                 next;
 2733:             }
 2734:         }
 2735:         my ($rolecode,$username,$domain,$section,$area);
 2736:         if ($context eq 'userroles') {
 2737:             ($area,$rolecode) = split(/_/,$entry);
 2738:             (undef,$domain,$username,$section) = split(/\//,$area);
 2739:         } else {
 2740:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2741:         }
 2742:         if (ref($roledoms) eq 'ARRAY') {
 2743:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2744:                 next;
 2745:             }
 2746:         }
 2747:         if (ref($roles) eq 'ARRAY') {
 2748:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2749:                 if ($role =~ /^cr\//) {
 2750:                     if (!grep(/^cr$/,@{$roles})) {
 2751:                         next;
 2752:                     }
 2753:                 } else {
 2754:                     next;
 2755:                 }
 2756:             }
 2757:         }
 2758:         if ($hidepriv) {
 2759:             if ((&privileged($username,$domain)) &&
 2760:                 (!$nothide{$username.':'.$domain})) { 
 2761:                 next;
 2762:             }
 2763:         }
 2764:         if ($withsec) {
 2765:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2766:                 $tstart.':'.$tend;
 2767:         } else {
 2768:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2769:         }
 2770:     }
 2771:     return %returnhash;
 2772: }
 2773: 
 2774: # ----------------------------------------------------- Frontpage Announcements
 2775: #
 2776: #
 2777: 
 2778: sub postannounce {
 2779:     my ($server,$text)=@_;
 2780:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2781:     unless ($text=~/\w/) { $text=''; }
 2782:     return &reply('setannounce:'.&escape($text),$server);
 2783: }
 2784: 
 2785: sub getannounce {
 2786: 
 2787:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2788: 	my $announcement='';
 2789: 	while (my $line = <$fh>) { $announcement .= $line; }
 2790: 	close($fh);
 2791: 	if ($announcement=~/\w/) { 
 2792: 	    return 
 2793:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2794:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2795: 	} else {
 2796: 	    return '';
 2797: 	}
 2798:     } else {
 2799: 	return '';
 2800:     }
 2801: }
 2802: 
 2803: # ---------------------------------------------------------- Course ID routines
 2804: # Deal with domain's nohist_courseid.db files
 2805: #
 2806: 
 2807: sub courseidput {
 2808:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2809:     my $outcome;
 2810:     if ($caller eq 'timeonly') {
 2811:         my $cids = '';
 2812:         foreach my $item (keys(%$storehash)) {
 2813:             $cids.=&escape($item).'&';
 2814:         }
 2815:         $cids=~s/\&$//;
 2816:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 2817:                           $coursehome);       
 2818:     } else {
 2819:         my $items = '';
 2820:         foreach my $item (keys(%$storehash)) {
 2821:             $items.= &escape($item).'='.
 2822:                      &freeze_escape($$storehash{$item}).'&';
 2823:         }
 2824:         $items=~s/\&$//;
 2825:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 2826:                           $coursehome);
 2827:     }
 2828:     if ($outcome eq 'unknown_cmd') {
 2829:         my $what;
 2830:         foreach my $cid (keys(%$storehash)) {
 2831:             $what .= &escape($cid).'=';
 2832:             foreach my $item ('description','inst_code','owner','type') {
 2833:                 $what .= &escape($storehash->{$cid}{$item}).':';
 2834:             }
 2835:             $what =~ s/\:$/&/;
 2836:         }
 2837:         $what =~ s/\&$//;  
 2838:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2839:     } else {
 2840:         return $outcome;
 2841:     }
 2842: }
 2843: 
 2844: sub courseiddump {
 2845:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 2846:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 2847:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
 2848:     my $as_hash = 1;
 2849:     my %returnhash;
 2850:     if (!$domfilter) { $domfilter=''; }
 2851:     my %libserv = &all_library();
 2852:     foreach my $tryserver (keys(%libserv)) {
 2853:         if ( (  $hostidflag == 1 
 2854: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2855: 	     || (!defined($hostidflag)) ) {
 2856: 
 2857: 	    if (($domfilter eq '') ||
 2858: 		(&host_domain($tryserver) eq $domfilter)) {
 2859:                 my $rep = 
 2860:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 2861:                          $sincefilter.':'.&escape($descfilter).':'.
 2862:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 2863:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 2864:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 2865:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 2866:                          $showhidden.':'.$caller,$tryserver);
 2867:                 my @pairs=split(/\&/,$rep);
 2868:                 foreach my $item (@pairs) {
 2869:                     my ($key,$value)=split(/\=/,$item,2);
 2870:                     $key = &unescape($key);
 2871:                     next if ($key =~ /^error: 2 /);
 2872:                     my $result = &thaw_unescape($value);
 2873:                     if (ref($result) eq 'HASH') {
 2874:                         $returnhash{$key}=$result;
 2875:                     } else {
 2876:                         my @responses = split(/:/,$value);
 2877:                         my @items = ('description','inst_code','owner','type');
 2878:                         for (my $i=0; $i<@responses; $i++) {
 2879:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 2880:                         }
 2881:                     } 
 2882:                 }
 2883:             }
 2884:         }
 2885:     }
 2886:     return %returnhash;
 2887: }
 2888: 
 2889: # ---------------------------------------------------------- DC e-mail
 2890: 
 2891: sub dcmailput {
 2892:     my ($domain,$msgid,$message,$server)=@_;
 2893:     my $status = &Apache::lonnet::critical(
 2894:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2895:        &escape($message),$server);
 2896:     return $status;
 2897: }
 2898: 
 2899: sub dcmaildump {
 2900:     my ($dom,$startdate,$enddate,$senders) = @_;
 2901:     my %returnhash=();
 2902: 
 2903:     if (defined(&domain($dom,'primary'))) {
 2904:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2905:                                                          &escape($enddate).':';
 2906: 	my @esc_senders=map { &escape($_)} @$senders;
 2907: 	$cmd.=&escape(join('&',@esc_senders));
 2908: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2909:             my ($key,$value) = split(/\=/,$line,2);
 2910:             if (($key) && ($value)) {
 2911:                 $returnhash{&unescape($key)} = &unescape($value);
 2912:             }
 2913:         }
 2914:     }
 2915:     return %returnhash;
 2916: }
 2917: # ---------------------------------------------------------- Domain roles
 2918: 
 2919: sub get_domain_roles {
 2920:     my ($dom,$roles,$startdate,$enddate)=@_;
 2921:     if (undef($startdate) || $startdate eq '') {
 2922:         $startdate = '.';
 2923:     }
 2924:     if (undef($enddate) || $enddate eq '') {
 2925:         $enddate = '.';
 2926:     }
 2927:     my $rolelist;
 2928:     if (ref($roles) eq 'ARRAY') {
 2929:         $rolelist = join(':',@{$roles});
 2930:     }
 2931:     my %personnel = ();
 2932: 
 2933:     my %servers = &get_servers($dom,'library');
 2934:     foreach my $tryserver (keys(%servers)) {
 2935: 	%{$personnel{$tryserver}}=();
 2936: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2937: 					    &escape($startdate).':'.
 2938: 					    &escape($enddate).':'.
 2939: 					    &escape($rolelist), $tryserver))) {
 2940: 	    my ($key,$value) = split(/\=/,$line,2);
 2941: 	    if (($key) && ($value)) {
 2942: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2943: 	    }
 2944: 	}
 2945:     }
 2946:     return %personnel;
 2947: }
 2948: 
 2949: # ----------------------------------------------------------- Check out an item
 2950: 
 2951: sub get_first_access {
 2952:     my ($type,$argsymb)=@_;
 2953:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2954:     if ($argsymb) { $symb=$argsymb; }
 2955:     my ($map,$id,$res)=&decode_symb($symb);
 2956:     if ($type eq 'course') {
 2957: 	$res='course';
 2958:     } elsif ($type eq 'map') {
 2959: 	$res=&symbread($map);
 2960:     } else {
 2961: 	$res=$symb;
 2962:     }
 2963:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2964:     return $times{"$courseid\0$res"};
 2965: }
 2966: 
 2967: sub set_first_access {
 2968:     my ($type)=@_;
 2969:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2970:     my ($map,$id,$res)=&decode_symb($symb);
 2971:     if ($type eq 'course') {
 2972: 	$res='course';
 2973:     } elsif ($type eq 'map') {
 2974: 	$res=&symbread($map);
 2975:     } else {
 2976: 	$res=$symb;
 2977:     }
 2978:     my $firstaccess=&get_first_access($type,$symb);
 2979:     if (!$firstaccess) {
 2980: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2981:     }
 2982:     return 'already_set';
 2983: }
 2984: 
 2985: sub checkout {
 2986:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2987:     my $now=time;
 2988:     my $lonhost=$perlvar{'lonHostID'};
 2989:     my $infostr=&escape(
 2990:                  'CHECKOUTTOKEN&'.
 2991:                  $tuname.'&'.
 2992:                  $tudom.'&'.
 2993:                  $tcrsid.'&'.
 2994:                  $symb.'&'.
 2995: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2996:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2997:     if ($token=~/^error\:/) { 
 2998:         &logthis("<font color=\"blue\">WARNING: ".
 2999:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 3000:                  "</font>");
 3001:         return ''; 
 3002:     }
 3003: 
 3004:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 3005:     $token=~tr/a-z/A-Z/;
 3006: 
 3007:     my %infohash=('resource.0.outtoken' => $token,
 3008:                   'resource.0.checkouttime' => $now,
 3009:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 3010: 
 3011:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3012:        return '';
 3013:     } else {
 3014:         &logthis("<font color=\"blue\">WARNING: ".
 3015:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 3016:                  "</font>");
 3017:     }    
 3018: 
 3019:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3020:                          &escape('Checkout '.$infostr.' - '.
 3021:                                                  $token)) ne 'ok') {
 3022: 	return '';
 3023:     } else {
 3024:         &logthis("<font color=\"blue\">WARNING: ".
 3025:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 3026:                  "</font>");
 3027:     }
 3028:     return $token;
 3029: }
 3030: 
 3031: # ------------------------------------------------------------ Check in an item
 3032: 
 3033: sub checkin {
 3034:     my $token=shift;
 3035:     my $now=time;
 3036:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 3037:     $lonhost=~tr/A-Z/a-z/;
 3038:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 3039:     $dtoken=~s/\W/\_/g;
 3040:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 3041:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 3042: 
 3043:     unless (($tuname) && ($tudom)) {
 3044:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 3045:         return '';
 3046:     }
 3047:     
 3048:     unless (&allowed('mgr',$tcrsid)) {
 3049:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 3050:                  $env{'user.name'}.' - '.$env{'user.domain'});
 3051:         return '';
 3052:     }
 3053: 
 3054:     my %infohash=('resource.0.intoken' => $token,
 3055:                   'resource.0.checkintime' => $now,
 3056:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 3057: 
 3058:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3059:        return '';
 3060:     }    
 3061: 
 3062:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3063:                          &escape('Checkin - '.$token)) ne 'ok') {
 3064: 	return '';
 3065:     }
 3066: 
 3067:     return ($symb,$tuname,$tudom,$tcrsid);    
 3068: }
 3069: 
 3070: # --------------------------------------------- Set Expire Date for Spreadsheet
 3071: 
 3072: sub expirespread {
 3073:     my ($uname,$udom,$stype,$usymb)=@_;
 3074:     my $cid=$env{'request.course.id'}; 
 3075:     if ($cid) {
 3076:        my $now=time;
 3077:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3078:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3079:                             $env{'course.'.$cid.'.num'}.
 3080: 	        	    ':nohist_expirationdates:'.
 3081:                             &escape($key).'='.$now,
 3082:                             $env{'course.'.$cid.'.home'})
 3083:     }
 3084:     return 'ok';
 3085: }
 3086: 
 3087: # ----------------------------------------------------- Devalidate Spreadsheets
 3088: 
 3089: sub devalidate {
 3090:     my ($symb,$uname,$udom)=@_;
 3091:     my $cid=$env{'request.course.id'}; 
 3092:     if ($cid) {
 3093:         # delete the stored spreadsheets for
 3094:         # - the student level sheet of this user in course's homespace
 3095:         # - the assessment level sheet for this resource 
 3096:         #   for this user in user's homespace
 3097: 	# - current conditional state info
 3098: 	my $key=$uname.':'.$udom.':';
 3099:         my $status=
 3100: 	    &del('nohist_calculatedsheets',
 3101: 		 [$key.'studentcalc:'],
 3102: 		 $env{'course.'.$cid.'.domain'},
 3103: 		 $env{'course.'.$cid.'.num'})
 3104: 		.' '.
 3105: 	    &del('nohist_calculatedsheets_'.$cid,
 3106: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3107:         unless ($status eq 'ok ok') {
 3108:            &logthis('Could not devalidate spreadsheet '.
 3109:                     $uname.' at '.$udom.' for '.
 3110: 		    $symb.': '.$status);
 3111:         }
 3112: 	&delenv('user.state.'.$cid);
 3113:     }
 3114: }
 3115: 
 3116: sub get_scalar {
 3117:     my ($string,$end) = @_;
 3118:     my $value;
 3119:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3120: 	$value = $1;
 3121:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3122: 	$value = $1;
 3123:     }
 3124:     return &unescape($value);
 3125: }
 3126: 
 3127: sub array2str {
 3128:   my (@array) = @_;
 3129:   my $result=&arrayref2str(\@array);
 3130:   $result=~s/^__ARRAY_REF__//;
 3131:   $result=~s/__END_ARRAY_REF__$//;
 3132:   return $result;
 3133: }
 3134: 
 3135: sub arrayref2str {
 3136:   my ($arrayref) = @_;
 3137:   my $result='__ARRAY_REF__';
 3138:   foreach my $elem (@$arrayref) {
 3139:     if(ref($elem) eq 'ARRAY') {
 3140:       $result.=&arrayref2str($elem).'&';
 3141:     } elsif(ref($elem) eq 'HASH') {
 3142:       $result.=&hashref2str($elem).'&';
 3143:     } elsif(ref($elem)) {
 3144:       #print("Got a ref of ".(ref($elem))." skipping.");
 3145:     } else {
 3146:       $result.=&escape($elem).'&';
 3147:     }
 3148:   }
 3149:   $result=~s/\&$//;
 3150:   $result .= '__END_ARRAY_REF__';
 3151:   return $result;
 3152: }
 3153: 
 3154: sub hash2str {
 3155:   my (%hash) = @_;
 3156:   my $result=&hashref2str(\%hash);
 3157:   $result=~s/^__HASH_REF__//;
 3158:   $result=~s/__END_HASH_REF__$//;
 3159:   return $result;
 3160: }
 3161: 
 3162: sub hashref2str {
 3163:   my ($hashref)=@_;
 3164:   my $result='__HASH_REF__';
 3165:   foreach my $key (sort(keys(%$hashref))) {
 3166:     if (ref($key) eq 'ARRAY') {
 3167:       $result.=&arrayref2str($key).'=';
 3168:     } elsif (ref($key) eq 'HASH') {
 3169:       $result.=&hashref2str($key).'=';
 3170:     } elsif (ref($key)) {
 3171:       $result.='=';
 3172:       #print("Got a ref of ".(ref($key))." skipping.");
 3173:     } else {
 3174: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3175:     }
 3176: 
 3177:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3178:       $result.=&arrayref2str($hashref->{$key}).'&';
 3179:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3180:       $result.=&hashref2str($hashref->{$key}).'&';
 3181:     } elsif(ref($hashref->{$key})) {
 3182:        $result.='&';
 3183:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3184:     } else {
 3185:       $result.=&escape($hashref->{$key}).'&';
 3186:     }
 3187:   }
 3188:   $result=~s/\&$//;
 3189:   $result .= '__END_HASH_REF__';
 3190:   return $result;
 3191: }
 3192: 
 3193: sub str2hash {
 3194:     my ($string)=@_;
 3195:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3196:     return %$hash;
 3197: }
 3198: 
 3199: sub str2hashref {
 3200:   my ($string) = @_;
 3201: 
 3202:   my %hash;
 3203: 
 3204:   if($string !~ /^__HASH_REF__/) {
 3205:       if (! ($string eq '' || !defined($string))) {
 3206: 	  $hash{'error'}='Not hash reference';
 3207:       }
 3208:       return (\%hash, $string);
 3209:   }
 3210: 
 3211:   $string =~ s/^__HASH_REF__//;
 3212: 
 3213:   while($string !~ /^__END_HASH_REF__/) {
 3214:       #key
 3215:       my $key='';
 3216:       if($string =~ /^__HASH_REF__/) {
 3217:           ($key, $string)=&str2hashref($string);
 3218:           if(defined($key->{'error'})) {
 3219:               $hash{'error'}='Bad data';
 3220:               return (\%hash, $string);
 3221:           }
 3222:       } elsif($string =~ /^__ARRAY_REF__/) {
 3223:           ($key, $string)=&str2arrayref($string);
 3224:           if($key->[0] eq 'Array reference error') {
 3225:               $hash{'error'}='Bad data';
 3226:               return (\%hash, $string);
 3227:           }
 3228:       } else {
 3229:           $string =~ s/^(.*?)=//;
 3230: 	  $key=&unescape($1);
 3231:       }
 3232:       $string =~ s/^=//;
 3233: 
 3234:       #value
 3235:       my $value='';
 3236:       if($string =~ /^__HASH_REF__/) {
 3237:           ($value, $string)=&str2hashref($string);
 3238:           if(defined($value->{'error'})) {
 3239:               $hash{'error'}='Bad data';
 3240:               return (\%hash, $string);
 3241:           }
 3242:       } elsif($string =~ /^__ARRAY_REF__/) {
 3243:           ($value, $string)=&str2arrayref($string);
 3244:           if($value->[0] eq 'Array reference error') {
 3245:               $hash{'error'}='Bad data';
 3246:               return (\%hash, $string);
 3247:           }
 3248:       } else {
 3249: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3250:       }
 3251:       $string =~ s/^&//;
 3252: 
 3253:       $hash{$key}=$value;
 3254:   }
 3255: 
 3256:   $string =~ s/^__END_HASH_REF__//;
 3257: 
 3258:   return (\%hash, $string);
 3259: }
 3260: 
 3261: sub str2array {
 3262:     my ($string)=@_;
 3263:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3264:     return @$array;
 3265: }
 3266: 
 3267: sub str2arrayref {
 3268:   my ($string) = @_;
 3269:   my @array;
 3270: 
 3271:   if($string !~ /^__ARRAY_REF__/) {
 3272:       if (! ($string eq '' || !defined($string))) {
 3273: 	  $array[0]='Array reference error';
 3274:       }
 3275:       return (\@array, $string);
 3276:   }
 3277: 
 3278:   $string =~ s/^__ARRAY_REF__//;
 3279: 
 3280:   while($string !~ /^__END_ARRAY_REF__/) {
 3281:       my $value='';
 3282:       if($string =~ /^__HASH_REF__/) {
 3283:           ($value, $string)=&str2hashref($string);
 3284:           if(defined($value->{'error'})) {
 3285:               $array[0] ='Array reference error';
 3286:               return (\@array, $string);
 3287:           }
 3288:       } elsif($string =~ /^__ARRAY_REF__/) {
 3289:           ($value, $string)=&str2arrayref($string);
 3290:           if($value->[0] eq 'Array reference error') {
 3291:               $array[0] ='Array reference error';
 3292:               return (\@array, $string);
 3293:           }
 3294:       } else {
 3295: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3296:       }
 3297:       $string =~ s/^&//;
 3298: 
 3299:       push(@array, $value);
 3300:   }
 3301: 
 3302:   $string =~ s/^__END_ARRAY_REF__//;
 3303: 
 3304:   return (\@array, $string);
 3305: }
 3306: 
 3307: # -------------------------------------------------------------------Temp Store
 3308: 
 3309: sub tmpreset {
 3310:   my ($symb,$namespace,$domain,$stuname) = @_;
 3311:   if (!$symb) {
 3312:     $symb=&symbread();
 3313:     if (!$symb) { $symb= $env{'request.url'}; }
 3314:   }
 3315:   $symb=escape($symb);
 3316: 
 3317:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3318:   $namespace=~s/\//\_/g;
 3319:   $namespace=~s/\W//g;
 3320: 
 3321:   if (!$domain) { $domain=$env{'user.domain'}; }
 3322:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3323:   if ($domain eq 'public' && $stuname eq 'public') {
 3324:       $stuname=$ENV{'REMOTE_ADDR'};
 3325:   }
 3326:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3327:   my %hash;
 3328:   if (tie(%hash,'GDBM_File',
 3329: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3330: 	  &GDBM_WRCREAT(),0640)) {
 3331:     foreach my $key (keys %hash) {
 3332:       if ($key=~ /:$symb/) {
 3333: 	delete($hash{$key});
 3334:       }
 3335:     }
 3336:   }
 3337: }
 3338: 
 3339: sub tmpstore {
 3340:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3341: 
 3342:   if (!$symb) {
 3343:     $symb=&symbread();
 3344:     if (!$symb) { $symb= $env{'request.url'}; }
 3345:   }
 3346:   $symb=escape($symb);
 3347: 
 3348:   if (!$namespace) {
 3349:     # I don't think we would ever want to store this for a course.
 3350:     # it seems this will only be used if we don't have a course.
 3351:     #$namespace=$env{'request.course.id'};
 3352:     #if (!$namespace) {
 3353:       $namespace=$env{'request.state'};
 3354:     #}
 3355:   }
 3356:   $namespace=~s/\//\_/g;
 3357:   $namespace=~s/\W//g;
 3358:   if (!$domain) { $domain=$env{'user.domain'}; }
 3359:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3360:   if ($domain eq 'public' && $stuname eq 'public') {
 3361:       $stuname=$ENV{'REMOTE_ADDR'};
 3362:   }
 3363:   my $now=time;
 3364:   my %hash;
 3365:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3366:   if (tie(%hash,'GDBM_File',
 3367: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3368: 	  &GDBM_WRCREAT(),0640)) {
 3369:     $hash{"version:$symb"}++;
 3370:     my $version=$hash{"version:$symb"};
 3371:     my $allkeys=''; 
 3372:     foreach my $key (keys(%$storehash)) {
 3373:       $allkeys.=$key.':';
 3374:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3375:     }
 3376:     $hash{"$version:$symb:timestamp"}=$now;
 3377:     $allkeys.='timestamp';
 3378:     $hash{"$version:keys:$symb"}=$allkeys;
 3379:     if (untie(%hash)) {
 3380:       return 'ok';
 3381:     } else {
 3382:       return "error:$!";
 3383:     }
 3384:   } else {
 3385:     return "error:$!";
 3386:   }
 3387: }
 3388: 
 3389: # -----------------------------------------------------------------Temp Restore
 3390: 
 3391: sub tmprestore {
 3392:   my ($symb,$namespace,$domain,$stuname) = @_;
 3393: 
 3394:   if (!$symb) {
 3395:     $symb=&symbread();
 3396:     if (!$symb) { $symb= $env{'request.url'}; }
 3397:   }
 3398:   $symb=escape($symb);
 3399: 
 3400:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3401: 
 3402:   if (!$domain) { $domain=$env{'user.domain'}; }
 3403:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3404:   if ($domain eq 'public' && $stuname eq 'public') {
 3405:       $stuname=$ENV{'REMOTE_ADDR'};
 3406:   }
 3407:   my %returnhash;
 3408:   $namespace=~s/\//\_/g;
 3409:   $namespace=~s/\W//g;
 3410:   my %hash;
 3411:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3412:   if (tie(%hash,'GDBM_File',
 3413: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3414: 	  &GDBM_READER(),0640)) {
 3415:     my $version=$hash{"version:$symb"};
 3416:     $returnhash{'version'}=$version;
 3417:     my $scope;
 3418:     for ($scope=1;$scope<=$version;$scope++) {
 3419:       my $vkeys=$hash{"$scope:keys:$symb"};
 3420:       my @keys=split(/:/,$vkeys);
 3421:       my $key;
 3422:       $returnhash{"$scope:keys"}=$vkeys;
 3423:       foreach $key (@keys) {
 3424: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3425: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3426:       }
 3427:     }
 3428:     if (!(untie(%hash))) {
 3429:       return "error:$!";
 3430:     }
 3431:   } else {
 3432:     return "error:$!";
 3433:   }
 3434:   return %returnhash;
 3435: }
 3436: 
 3437: # ----------------------------------------------------------------------- Store
 3438: 
 3439: sub store {
 3440:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3441:     my $home='';
 3442: 
 3443:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3444: 
 3445:     $symb=&symbclean($symb);
 3446:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3447: 
 3448:     if (!$domain) { $domain=$env{'user.domain'}; }
 3449:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3450: 
 3451:     &devalidate($symb,$stuname,$domain);
 3452: 
 3453:     $symb=escape($symb);
 3454:     if (!$namespace) { 
 3455:        unless ($namespace=$env{'request.course.id'}) { 
 3456:           return ''; 
 3457:        } 
 3458:     }
 3459:     if (!$home) { $home=$env{'user.home'}; }
 3460: 
 3461:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3462:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3463: 
 3464:     my $namevalue='';
 3465:     foreach my $key (keys(%$storehash)) {
 3466:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3467:     }
 3468:     $namevalue=~s/\&$//;
 3469:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3470:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3471: }
 3472: 
 3473: # -------------------------------------------------------------- Critical Store
 3474: 
 3475: sub cstore {
 3476:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3477:     my $home='';
 3478: 
 3479:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3480: 
 3481:     $symb=&symbclean($symb);
 3482:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3483: 
 3484:     if (!$domain) { $domain=$env{'user.domain'}; }
 3485:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3486: 
 3487:     &devalidate($symb,$stuname,$domain);
 3488: 
 3489:     $symb=escape($symb);
 3490:     if (!$namespace) { 
 3491:        unless ($namespace=$env{'request.course.id'}) { 
 3492:           return ''; 
 3493:        } 
 3494:     }
 3495:     if (!$home) { $home=$env{'user.home'}; }
 3496: 
 3497:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3498:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3499: 
 3500:     my $namevalue='';
 3501:     foreach my $key (keys(%$storehash)) {
 3502:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3503:     }
 3504:     $namevalue=~s/\&$//;
 3505:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3506:     return critical
 3507:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3508: }
 3509: 
 3510: # --------------------------------------------------------------------- Restore
 3511: 
 3512: sub restore {
 3513:     my ($symb,$namespace,$domain,$stuname) = @_;
 3514:     my $home='';
 3515: 
 3516:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3517: 
 3518:     if (!$symb) {
 3519:       unless ($symb=escape(&symbread())) { return ''; }
 3520:     } else {
 3521:       $symb=&escape(&symbclean($symb));
 3522:     }
 3523:     if (!$namespace) { 
 3524:        unless ($namespace=$env{'request.course.id'}) { 
 3525:           return ''; 
 3526:        } 
 3527:     }
 3528:     if (!$domain) { $domain=$env{'user.domain'}; }
 3529:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3530:     if (!$home) { $home=$env{'user.home'}; }
 3531:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3532: 
 3533:     my %returnhash=();
 3534:     foreach my $line (split(/\&/,$answer)) {
 3535: 	my ($name,$value)=split(/\=/,$line);
 3536:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3537:     }
 3538:     my $version;
 3539:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3540:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3541:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3542:        }
 3543:     }
 3544:     return %returnhash;
 3545: }
 3546: 
 3547: # ---------------------------------------------------------- Course Description
 3548: 
 3549: sub coursedescription {
 3550:     my ($courseid,$args)=@_;
 3551:     $courseid=~s/^\///;
 3552:     $courseid=~s/\_/\//g;
 3553:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3554:     my $chome=&homeserver($cnum,$cdomain);
 3555:     my $normalid=$cdomain.'_'.$cnum;
 3556:     # need to always cache even if we get errors otherwise we keep 
 3557:     # trying and trying and trying to get the course description.
 3558:     my %envhash=();
 3559:     my %returnhash=();
 3560:     
 3561:     my $expiretime=600;
 3562:     if ($env{'request.course.id'} eq $normalid) {
 3563: 	$expiretime=120;
 3564:     }
 3565: 
 3566:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3567:     if (!$args->{'freshen_cache'}
 3568: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3569: 	foreach my $key (keys(%env)) {
 3570: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3571: 	    my ($setting) = $1;
 3572: 	    $returnhash{$setting} = $env{$key};
 3573: 	}
 3574: 	return %returnhash;
 3575:     }
 3576: 
 3577:     # get the data agin
 3578:     if (!$args->{'one_time'}) {
 3579: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3580:     }
 3581: 
 3582:     if ($chome ne 'no_host') {
 3583:        %returnhash=&dump('environment',$cdomain,$cnum);
 3584:        if (!exists($returnhash{'con_lost'})) {
 3585:            $returnhash{'home'}= $chome;
 3586: 	   $returnhash{'domain'} = $cdomain;
 3587: 	   $returnhash{'num'} = $cnum;
 3588:            if (!defined($returnhash{'type'})) {
 3589:                $returnhash{'type'} = 'Course';
 3590:            }
 3591:            while (my ($name,$value) = each %returnhash) {
 3592:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3593:            }
 3594:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3595:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3596: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3597:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3598:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3599:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3600:        }
 3601:     }
 3602:     if (!$args->{'one_time'}) {
 3603: 	&appenv(\%envhash);
 3604:     }
 3605:     return %returnhash;
 3606: }
 3607: 
 3608: # -------------------------------------------------See if a user is privileged
 3609: 
 3610: sub privileged {
 3611:     my ($username,$domain)=@_;
 3612:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3613: 			&homeserver($username,$domain));
 3614:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3615:     my $now=time;
 3616:     if ($rolesdump ne '') {
 3617:         foreach my $entry (split(/&/,$rolesdump)) {
 3618: 	    if ($entry!~/^rolesdef_/) {
 3619: 		my ($area,$role)=split(/=/,$entry);
 3620: 		$area=~s/\_\w\w$//;
 3621: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3622: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3623: 		    my $active=1;
 3624: 		    if ($tend) {
 3625: 			if ($tend<$now) { $active=0; }
 3626: 		    }
 3627: 		    if ($tstart) {
 3628: 			if ($tstart>$now) { $active=0; }
 3629: 		    }
 3630: 		    if ($active) { return 1; }
 3631: 		}
 3632: 	    }
 3633: 	}
 3634:     }
 3635:     return 0;
 3636: }
 3637: 
 3638: # -------------------------------------------------------- Get user privileges
 3639: 
 3640: sub rolesinit {
 3641:     my ($domain,$username,$authhost)=@_;
 3642:     my %userroles;
 3643:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3644:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
 3645:     my %allroles=();
 3646:     my %allgroups=();   
 3647:     my $now=time;
 3648:     %userroles = ('user.login.time' => $now);
 3649:     my $group_privs;
 3650: 
 3651:     if ($rolesdump ne '') {
 3652:         foreach my $entry (split(/&/,$rolesdump)) {
 3653: 	  if ($entry!~/^rolesdef_/) {
 3654:             my ($area,$role)=split(/=/,$entry);
 3655: 	    $area=~s/\_\w\w$//;
 3656:             my ($trole,$tend,$tstart,$group_privs);
 3657: 	    if ($role=~/^cr/) { 
 3658: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3659: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3660: 		    ($tend,$tstart)=split('_',$trest);
 3661: 		} else {
 3662: 		    $trole=$role;
 3663: 		}
 3664:             } elsif ($role =~ m|^gr/|) {
 3665:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3666:                 ($trole,$group_privs) = split(/\//,$trole);
 3667:                 $group_privs = &unescape($group_privs);
 3668: 	    } else {
 3669: 		($trole,$tend,$tstart)=split(/_/,$role);
 3670: 	    }
 3671: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3672: 					 $username);
 3673: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3674:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3675:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3676:             if (($area ne '') && ($trole ne '')) {
 3677: 		my $spec=$trole.'.'.$area;
 3678: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3679: 		if ($trole =~ /^cr\//) {
 3680:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3681:                 } elsif ($trole eq 'gr') {
 3682:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3683: 		} else {
 3684:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3685: 		}
 3686:             }
 3687:           }
 3688:         }
 3689:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3690:         $userroles{'user.adv'}    = $adv;
 3691: 	$userroles{'user.author'} = $author;
 3692:         $env{'user.adv'}=$adv;
 3693:     }
 3694:     return \%userroles;  
 3695: }
 3696: 
 3697: sub set_arearole {
 3698:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3699: # log the associated role with the area
 3700:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3701:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3702: }
 3703: 
 3704: sub custom_roleprivs {
 3705:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3706:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3707:     my $homsvr=homeserver($rauthor,$rdomain);
 3708:     if (&hostname($homsvr) ne '') {
 3709:         my ($rdummy,$roledef)=
 3710:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3711:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3712:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3713:             if (defined($syspriv)) {
 3714:                 $$allroles{'cm./'}.=':'.$syspriv;
 3715:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3716:             }
 3717:             if ($tdomain ne '') {
 3718:                 if (defined($dompriv)) {
 3719:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3720:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3721:                 }
 3722:                 if (($trest ne '') && (defined($coursepriv))) {
 3723:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3724:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3725:                 }
 3726:             }
 3727:         }
 3728:     }
 3729: }
 3730: 
 3731: sub group_roleprivs {
 3732:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3733:     my $access = 1;
 3734:     my $now = time;
 3735:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3736:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3737:     if ($access) {
 3738:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3739:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3740:     }
 3741: }
 3742: 
 3743: sub standard_roleprivs {
 3744:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3745:     if (defined($pr{$trole.':s'})) {
 3746:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3747:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3748:     }
 3749:     if ($tdomain ne '') {
 3750:         if (defined($pr{$trole.':d'})) {
 3751:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3752:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3753:         }
 3754:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3755:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3756:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3757:         }
 3758:     }
 3759: }
 3760: 
 3761: sub set_userprivs {
 3762:     my ($userroles,$allroles,$allgroups) = @_; 
 3763:     my $author=0;
 3764:     my $adv=0;
 3765:     my %grouproles = ();
 3766:     if (keys(%{$allgroups}) > 0) {
 3767:         foreach my $role (keys %{$allroles}) {
 3768:             my ($trole,$area,$sec,$extendedarea);
 3769:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3770:                 $trole = $1;
 3771:                 $area = $2;
 3772:                 $sec = $3;
 3773:                 $extendedarea = $area.$sec;
 3774:                 if (exists($$allgroups{$area})) {
 3775:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3776:                         my $spec = $trole.'.'.$extendedarea;
 3777:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3778:                                                 $$allgroups{$area}{$group};
 3779:                     }
 3780:                 }
 3781:             }
 3782:         }
 3783:     }
 3784:     foreach my $group (keys(%grouproles)) {
 3785:         $$allroles{$group} = $grouproles{$group};
 3786:     }
 3787:     foreach my $role (keys(%{$allroles})) {
 3788:         my %thesepriv;
 3789:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3790:         foreach my $item (split(/:/,$$allroles{$role})) {
 3791:             if ($item ne '') {
 3792:                 my ($privilege,$restrictions)=split(/&/,$item);
 3793:                 if ($restrictions eq '') {
 3794:                     $thesepriv{$privilege}='F';
 3795:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3796:                     $thesepriv{$privilege}.=$restrictions;
 3797:                 }
 3798:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3799:             }
 3800:         }
 3801:         my $thesestr='';
 3802:         foreach my $priv (keys(%thesepriv)) {
 3803: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3804: 	}
 3805:         $userroles->{'user.priv.'.$role} = $thesestr;
 3806:     }
 3807:     return ($author,$adv);
 3808: }
 3809: 
 3810: # --------------------------------------------------------------- get interface
 3811: 
 3812: sub get {
 3813:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3814:    my $items='';
 3815:    foreach my $item (@$storearr) {
 3816:        $items.=&escape($item).'&';
 3817:    }
 3818:    $items=~s/\&$//;
 3819:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3820:    if (!$uname) { $uname=$env{'user.name'}; }
 3821:    my $uhome=&homeserver($uname,$udomain);
 3822: 
 3823:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3824:    my @pairs=split(/\&/,$rep);
 3825:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3826:      return @pairs;
 3827:    }
 3828:    my %returnhash=();
 3829:    my $i=0;
 3830:    foreach my $item (@$storearr) {
 3831:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3832:       $i++;
 3833:    }
 3834:    return %returnhash;
 3835: }
 3836: 
 3837: # --------------------------------------------------------------- del interface
 3838: 
 3839: sub del {
 3840:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3841:    my $items='';
 3842:    foreach my $item (@$storearr) {
 3843:        $items.=&escape($item).'&';
 3844:    }
 3845:    $items=~s/\&$//;
 3846:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3847:    if (!$uname) { $uname=$env{'user.name'}; }
 3848:    my $uhome=&homeserver($uname,$udomain);
 3849: 
 3850:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3851: }
 3852: 
 3853: # -------------------------------------------------------------- dump interface
 3854: 
 3855: sub dump {
 3856:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3857:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3858:     if (!$uname) { $uname=$env{'user.name'}; }
 3859:     my $uhome=&homeserver($uname,$udomain);
 3860:     if ($regexp) {
 3861: 	$regexp=&escape($regexp);
 3862:     } else {
 3863: 	$regexp='.';
 3864:     }
 3865:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3866:     my @pairs=split(/\&/,$rep);
 3867:     my %returnhash=();
 3868:     foreach my $item (@pairs) {
 3869: 	my ($key,$value)=split(/=/,$item,2);
 3870: 	$key = &unescape($key);
 3871: 	next if ($key =~ /^error: 2 /);
 3872: 	$returnhash{$key}=&thaw_unescape($value);
 3873:     }
 3874:     return %returnhash;
 3875: }
 3876: 
 3877: # --------------------------------------------------------- dumpstore interface
 3878: 
 3879: sub dumpstore {
 3880:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3881:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3882:    if (!$uname) { $uname=$env{'user.name'}; }
 3883:    my $uhome=&homeserver($uname,$udomain);
 3884:    if ($regexp) {
 3885:        $regexp=&escape($regexp);
 3886:    } else {
 3887:        $regexp='.';
 3888:    }
 3889:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3890:    my @pairs=split(/\&/,$rep);
 3891:    my %returnhash=();
 3892:    foreach my $item (@pairs) {
 3893:        my ($key,$value)=split(/=/,$item,2);
 3894:        next if ($key =~ /^error: 2 /);
 3895:        $returnhash{$key}=&thaw_unescape($value);
 3896:    }
 3897:    return %returnhash;
 3898: }
 3899: 
 3900: # -------------------------------------------------------------- keys interface
 3901: 
 3902: sub getkeys {
 3903:    my ($namespace,$udomain,$uname)=@_;
 3904:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3905:    if (!$uname) { $uname=$env{'user.name'}; }
 3906:    my $uhome=&homeserver($uname,$udomain);
 3907:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3908:    my @keyarray=();
 3909:    foreach my $key (split(/\&/,$rep)) {
 3910:       next if ($key =~ /^error: 2 /);
 3911:       push(@keyarray,&unescape($key));
 3912:    }
 3913:    return @keyarray;
 3914: }
 3915: 
 3916: # --------------------------------------------------------------- currentdump
 3917: sub currentdump {
 3918:    my ($courseid,$sdom,$sname)=@_;
 3919:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3920:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3921:    $sname    = $env{'user.name'}         if (! defined($sname));
 3922:    my $uhome = &homeserver($sname,$sdom);
 3923:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3924:    return if ($rep =~ /^(error:|no_such_host)/);
 3925:    #
 3926:    my %returnhash=();
 3927:    #
 3928:    if ($rep eq "unknown_cmd") { 
 3929:        # an old lond will not know currentdump
 3930:        # Do a dump and make it look like a currentdump
 3931:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3932:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3933:        my %hash = @tmp;
 3934:        @tmp=();
 3935:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3936:    } else {
 3937:        my @pairs=split(/\&/,$rep);
 3938:        foreach my $pair (@pairs) {
 3939:            my ($key,$value)=split(/=/,$pair,2);
 3940:            my ($symb,$param) = split(/:/,$key);
 3941:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3942:                                                         &thaw_unescape($value);
 3943:        }
 3944:    }
 3945:    return %returnhash;
 3946: }
 3947: 
 3948: sub convert_dump_to_currentdump{
 3949:     my %hash = %{shift()};
 3950:     my %returnhash;
 3951:     # Code ripped from lond, essentially.  The only difference
 3952:     # here is the unescaping done by lonnet::dump().  Conceivably
 3953:     # we might run in to problems with parameter names =~ /^v\./
 3954:     while (my ($key,$value) = each(%hash)) {
 3955:         my ($v,$symb,$param) = split(/:/,$key);
 3956: 	$symb  = &unescape($symb);
 3957: 	$param = &unescape($param);
 3958:         next if ($v eq 'version' || $symb eq 'keys');
 3959:         next if (exists($returnhash{$symb}) &&
 3960:                  exists($returnhash{$symb}->{$param}) &&
 3961:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3962:         $returnhash{$symb}->{$param}=$value;
 3963:         $returnhash{$symb}->{'v.'.$param}=$v;
 3964:     }
 3965:     #
 3966:     # Remove all of the keys in the hashes which keep track of
 3967:     # the version of the parameter.
 3968:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3969:         # use a foreach because we are going to delete from the hash.
 3970:         foreach my $key (keys(%$param_hash)) {
 3971:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3972:         }
 3973:     }
 3974:     return \%returnhash;
 3975: }
 3976: 
 3977: # ------------------------------------------------------ critical inc interface
 3978: 
 3979: sub cinc {
 3980:     return &inc(@_,'critical');
 3981: }
 3982: 
 3983: # --------------------------------------------------------------- inc interface
 3984: 
 3985: sub inc {
 3986:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3987:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3988:     if (!$uname) { $uname=$env{'user.name'}; }
 3989:     my $uhome=&homeserver($uname,$udomain);
 3990:     my $items='';
 3991:     if (! ref($store)) {
 3992:         # got a single value, so use that instead
 3993:         $items = &escape($store).'=&';
 3994:     } elsif (ref($store) eq 'SCALAR') {
 3995:         $items = &escape($$store).'=&';        
 3996:     } elsif (ref($store) eq 'ARRAY') {
 3997:         $items = join('=&',map {&escape($_);} @{$store});
 3998:     } elsif (ref($store) eq 'HASH') {
 3999:         while (my($key,$value) = each(%{$store})) {
 4000:             $items.= &escape($key).'='.&escape($value).'&';
 4001:         }
 4002:     }
 4003:     $items=~s/\&$//;
 4004:     if ($critical) {
 4005: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 4006:     } else {
 4007: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 4008:     }
 4009: }
 4010: 
 4011: # --------------------------------------------------------------- put interface
 4012: 
 4013: sub put {
 4014:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4015:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4016:    if (!$uname) { $uname=$env{'user.name'}; }
 4017:    my $uhome=&homeserver($uname,$udomain);
 4018:    my $items='';
 4019:    foreach my $item (keys(%$storehash)) {
 4020:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4021:    }
 4022:    $items=~s/\&$//;
 4023:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4024: }
 4025: 
 4026: # ------------------------------------------------------------ newput interface
 4027: 
 4028: sub newput {
 4029:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4030:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4031:    if (!$uname) { $uname=$env{'user.name'}; }
 4032:    my $uhome=&homeserver($uname,$udomain);
 4033:    my $items='';
 4034:    foreach my $key (keys(%$storehash)) {
 4035:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4036:    }
 4037:    $items=~s/\&$//;
 4038:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 4039: }
 4040: 
 4041: # ---------------------------------------------------------  putstore interface
 4042: 
 4043: sub putstore {
 4044:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4045:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4046:    if (!$uname) { $uname=$env{'user.name'}; }
 4047:    my $uhome=&homeserver($uname,$udomain);
 4048:    my $items='';
 4049:    foreach my $key (keys(%$storehash)) {
 4050:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 4051:    }
 4052:    $items=~s/\&$//;
 4053:    my $esc_symb=&escape($symb);
 4054:    my $esc_v=&escape($version);
 4055:    my $reply =
 4056:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 4057: 	      $uhome);
 4058:    if ($reply eq 'unknown_cmd') {
 4059:        # gfall back to way things use to be done
 4060:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 4061: 			    $uname);
 4062:    }
 4063:    return $reply;
 4064: }
 4065: 
 4066: sub old_putstore {
 4067:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4068:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4069:     if (!$uname) { $uname=$env{'user.name'}; }
 4070:     my $uhome=&homeserver($uname,$udomain);
 4071:     my %newstorehash;
 4072:     foreach my $item (keys(%$storehash)) {
 4073: 	my $key = $version.':'.&escape($symb).':'.$item;
 4074: 	$newstorehash{$key} = $storehash->{$item};
 4075:     }
 4076:     my $items='';
 4077:     my %allitems = ();
 4078:     foreach my $item (keys(%newstorehash)) {
 4079: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 4080: 	    my $key = $1.':keys:'.$2;
 4081: 	    $allitems{$key} .= $3.':';
 4082: 	}
 4083: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 4084:     }
 4085:     foreach my $item (keys(%allitems)) {
 4086: 	$allitems{$item} =~ s/\:$//;
 4087: 	$items.= $item.'='.$allitems{$item}.'&';
 4088:     }
 4089:     $items=~s/\&$//;
 4090:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4091: }
 4092: 
 4093: # ------------------------------------------------------ critical put interface
 4094: 
 4095: sub cput {
 4096:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4097:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4098:    if (!$uname) { $uname=$env{'user.name'}; }
 4099:    my $uhome=&homeserver($uname,$udomain);
 4100:    my $items='';
 4101:    foreach my $item (keys(%$storehash)) {
 4102:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4103:    }
 4104:    $items=~s/\&$//;
 4105:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 4106: }
 4107: 
 4108: # -------------------------------------------------------------- eget interface
 4109: 
 4110: sub eget {
 4111:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4112:    my $items='';
 4113:    foreach my $item (@$storearr) {
 4114:        $items.=&escape($item).'&';
 4115:    }
 4116:    $items=~s/\&$//;
 4117:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4118:    if (!$uname) { $uname=$env{'user.name'}; }
 4119:    my $uhome=&homeserver($uname,$udomain);
 4120:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 4121:    my @pairs=split(/\&/,$rep);
 4122:    my %returnhash=();
 4123:    my $i=0;
 4124:    foreach my $item (@$storearr) {
 4125:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4126:       $i++;
 4127:    }
 4128:    return %returnhash;
 4129: }
 4130: 
 4131: # ------------------------------------------------------------ tmpput interface
 4132: sub tmpput {
 4133:     my ($storehash,$server,$context)=@_;
 4134:     my $items='';
 4135:     foreach my $item (keys(%$storehash)) {
 4136: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4137:     }
 4138:     $items=~s/\&$//;
 4139:     if (defined($context)) {
 4140:         $items .= ':'.&escape($context);
 4141:     }
 4142:     return &reply("tmpput:$items",$server);
 4143: }
 4144: 
 4145: # ------------------------------------------------------------ tmpget interface
 4146: sub tmpget {
 4147:     my ($token,$server)=@_;
 4148:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4149:     my $rep=&reply("tmpget:$token",$server);
 4150:     my %returnhash;
 4151:     foreach my $item (split(/\&/,$rep)) {
 4152: 	my ($key,$value)=split(/=/,$item);
 4153:         next if ($key =~ /^error: 2 /);
 4154: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 4155:     }
 4156:     return %returnhash;
 4157: }
 4158: 
 4159: # ------------------------------------------------------------ tmpget interface
 4160: sub tmpdel {
 4161:     my ($token,$server)=@_;
 4162:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4163:     return &reply("tmpdel:$token",$server);
 4164: }
 4165: 
 4166: # -------------------------------------------------- portfolio access checking
 4167: 
 4168: sub portfolio_access {
 4169:     my ($requrl) = @_;
 4170:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4171:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4172:     if ($result) {
 4173:         my %setters;
 4174:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4175:             my ($startblock,$endblock) =
 4176:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4177:             if ($startblock && $endblock) {
 4178:                 return 'B';
 4179:             }
 4180:         } else {
 4181:             my ($startblock,$endblock) =
 4182:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4183:             if ($startblock && $endblock) {
 4184:                 return 'B';
 4185:             }
 4186:         }
 4187:     }
 4188:     if ($result eq 'ok') {
 4189:        return 'F';
 4190:     } elsif ($result =~ /^[^:]+:guest_/) {
 4191:        return 'A';
 4192:     }
 4193:     return '';
 4194: }
 4195: 
 4196: sub get_portfolio_access {
 4197:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4198: 
 4199:     if (!ref($access_hash)) {
 4200: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4201: 	my %access_controls = &get_access_controls($current_perms,$group,
 4202: 						   $file_name);
 4203: 	$access_hash = $access_controls{$file_name};
 4204:     }
 4205: 
 4206:     my ($public,$guest,@domains,@users,@courses,@groups);
 4207:     my $now = time;
 4208:     if (ref($access_hash) eq 'HASH') {
 4209:         foreach my $key (keys(%{$access_hash})) {
 4210:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4211:             if ($start > $now) {
 4212:                 next;
 4213:             }
 4214:             if ($end && $end<$now) {
 4215:                 next;
 4216:             }
 4217:             if ($scope eq 'public') {
 4218:                 $public = $key;
 4219:                 last;
 4220:             } elsif ($scope eq 'guest') {
 4221:                 $guest = $key;
 4222:             } elsif ($scope eq 'domains') {
 4223:                 push(@domains,$key);
 4224:             } elsif ($scope eq 'users') {
 4225:                 push(@users,$key);
 4226:             } elsif ($scope eq 'course') {
 4227:                 push(@courses,$key);
 4228:             } elsif ($scope eq 'group') {
 4229:                 push(@groups,$key);
 4230:             }
 4231:         }
 4232:         if ($public) {
 4233:             return 'ok';
 4234:         }
 4235:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4236:             if ($guest) {
 4237:                 return $guest;
 4238:             }
 4239:         } else {
 4240:             if (@domains > 0) {
 4241:                 foreach my $domkey (@domains) {
 4242:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4243:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4244:                             return 'ok';
 4245:                         }
 4246:                     }
 4247:                 }
 4248:             }
 4249:             if (@users > 0) {
 4250:                 foreach my $userkey (@users) {
 4251:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4252:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4253:                             if (ref($item) eq 'HASH') {
 4254:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4255:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4256:                                     return 'ok';
 4257:                                 }
 4258:                             }
 4259:                         }
 4260:                     } 
 4261:                 }
 4262:             }
 4263:             my %roleshash;
 4264:             my @courses_and_groups = @courses;
 4265:             push(@courses_and_groups,@groups); 
 4266:             if (@courses_and_groups > 0) {
 4267:                 my (%allgroups,%allroles); 
 4268:                 my ($start,$end,$role,$sec,$group);
 4269:                 foreach my $envkey (%env) {
 4270:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4271:                         my $cid = $2.'_'.$3; 
 4272:                         if ($1 eq 'gr') {
 4273:                             $group = $4;
 4274:                             $allgroups{$cid}{$group} = $env{$envkey};
 4275:                         } else {
 4276:                             if ($4 eq '') {
 4277:                                 $sec = 'none';
 4278:                             } else {
 4279:                                 $sec = $4;
 4280:                             }
 4281:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4282:                         }
 4283:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4284:                         my $cid = $2.'_'.$3;
 4285:                         if ($4 eq '') {
 4286:                             $sec = 'none';
 4287:                         } else {
 4288:                             $sec = $4;
 4289:                         }
 4290:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4291:                     }
 4292:                 }
 4293:                 if (keys(%allroles) == 0) {
 4294:                     return;
 4295:                 }
 4296:                 foreach my $key (@courses_and_groups) {
 4297:                     my %content = %{$$access_hash{$key}};
 4298:                     my $cnum = $content{'number'};
 4299:                     my $cdom = $content{'domain'};
 4300:                     my $cid = $cdom.'_'.$cnum;
 4301:                     if (!exists($allroles{$cid})) {
 4302:                         next;
 4303:                     }    
 4304:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4305:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4306:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4307:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4308:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4309:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4310:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4311:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4312:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4313:                                         if (grep/^all$/,@sections) {
 4314:                                             return 'ok';
 4315:                                         } else {
 4316:                                             if (grep/^$sec$/,@sections) {
 4317:                                                 return 'ok';
 4318:                                             }
 4319:                                         }
 4320:                                     }
 4321:                                 }
 4322:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4323:                                     if (grep/^none$/,@groups) {
 4324:                                         return 'ok';
 4325:                                     }
 4326:                                 } else {
 4327:                                     if (grep/^all$/,@groups) {
 4328:                                         return 'ok';
 4329:                                     } 
 4330:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4331:                                         if (grep/^$group$/,@groups) {
 4332:                                             return 'ok';
 4333:                                         }
 4334:                                     }
 4335:                                 } 
 4336:                             }
 4337:                         }
 4338:                     }
 4339:                 }
 4340:             }
 4341:             if ($guest) {
 4342:                 return $guest;
 4343:             }
 4344:         }
 4345:     }
 4346:     return;
 4347: }
 4348: 
 4349: sub course_group_datechecker {
 4350:     my ($dates,$now,$status) = @_;
 4351:     my ($start,$end) = split(/\./,$dates);
 4352:     if (!$start && !$end) {
 4353:         return 'ok';
 4354:     }
 4355:     if (grep/^active$/,@{$status}) {
 4356:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4357:             return 'ok';
 4358:         }
 4359:     }
 4360:     if (grep/^previous$/,@{$status}) {
 4361:         if ($end > $now ) {
 4362:             return 'ok';
 4363:         }
 4364:     }
 4365:     if (grep/^future$/,@{$status}) {
 4366:         if ($start > $now) {
 4367:             return 'ok';
 4368:         }
 4369:     }
 4370:     return; 
 4371: }
 4372: 
 4373: sub parse_portfolio_url {
 4374:     my ($url) = @_;
 4375: 
 4376:     my ($type,$udom,$unum,$group,$file_name);
 4377:     
 4378:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4379: 	$type = 1;
 4380:         $udom = $1;
 4381:         $unum = $2;
 4382:         $file_name = $3;
 4383:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4384: 	$type = 2;
 4385:         $udom = $1;
 4386:         $unum = $2;
 4387:         $group = $3;
 4388:         $file_name = $3.'/'.$4;
 4389:     }
 4390:     if (wantarray) {
 4391: 	return ($type,$udom,$unum,$file_name,$group);
 4392:     }
 4393:     return $type;
 4394: }
 4395: 
 4396: sub is_portfolio_url {
 4397:     my ($url) = @_;
 4398:     return scalar(&parse_portfolio_url($url));
 4399: }
 4400: 
 4401: sub is_portfolio_file {
 4402:     my ($file) = @_;
 4403:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4404:         return 1;
 4405:     }
 4406:     return;
 4407: }
 4408: 
 4409: sub usertools_access {
 4410:     my ($uname,$udom,$tool,$action) = @_;
 4411:     my $access;
 4412:     my %tools = (
 4413:                   aboutme   => 1,
 4414:                   blog      => 1,
 4415:                   portfolio => 1,
 4416:                 );
 4417:     return if (!defined($tools{$tool}));
 4418: 
 4419:     if ((!defined($udom)) || (!defined($uname))) {
 4420:         $udom = $env{'user.domain'};
 4421:         $uname = $env{'user.name'};
 4422:     }
 4423: 
 4424:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4425:         if ($action ne 'reload') {
 4426:             return $env{'environment.availabletools.'.$tool};
 4427:         } 
 4428:     }
 4429: 
 4430:     my ($toolstatus,$inststatus);
 4431: 
 4432:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4433:         $toolstatus = $env{'environment.tools.'.$tool};
 4434:         $inststatus = $env{'environment.inststatus'};
 4435:     } else {
 4436:         my %userenv = &userenvironment($udom,$uname,'tools.'.$tool);
 4437:         $toolstatus = $userenv{'tools.'.$tool};
 4438:         $inststatus = $userenv{'inststatus'};
 4439:     }
 4440: 
 4441:     if ($toolstatus ne '') {
 4442:         if ($toolstatus) {
 4443:             $access = 1;
 4444:         } else {
 4445:             $access = 0;
 4446:         }
 4447:         return $access;
 4448:     }
 4449: 
 4450:     my $is_adv = &is_advanced_user($udom,$uname);
 4451:     my %domdef = &get_domain_defaults($udom);
 4452:     if (ref($domdef{$tool}) eq 'HASH') {
 4453:         if ($is_adv) {
 4454:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 4455:                 if ($domdef{$tool}{'_LC_adv'}) { 
 4456:                     $access = 1;
 4457:                 } else {
 4458:                     $access = 0;
 4459:                 }
 4460:                 return $access;
 4461:             }
 4462:         }
 4463:         if ($inststatus ne '') {
 4464:             my ($hasaccess,$hasnoaccess);
 4465:             foreach my $affiliation (split(/:/,$inststatus)) {
 4466:                 if ($domdef{$tool}{$affiliation} ne '') { 
 4467:                     if ($domdef{$tool}{$affiliation}) {
 4468:                         $hasaccess = 1;
 4469:                     } else {
 4470:                         $hasnoaccess = 1;
 4471:                     }
 4472:                 }
 4473:             }
 4474:             if ($hasaccess || $hasnoaccess) {
 4475:                 if ($hasaccess) {
 4476:                     $access = 1;
 4477:                 } elsif ($hasnoaccess) {
 4478:                     $access = 0; 
 4479:                 }
 4480:                 return $access;
 4481:             }
 4482:         } else {
 4483:             if ($domdef{$tool}{'default'} ne '') {
 4484:                 if ($domdef{$tool}{'default'}) {
 4485:                     $access = 1;
 4486:                 } elsif ($domdef{$tool}{'default'} == 0) {
 4487:                     $access = 0;
 4488:                 }
 4489:                 return $access;
 4490:             }
 4491:         }
 4492:     } else {
 4493:         $access = 1;
 4494:         return $access;
 4495:     }
 4496: }
 4497: 
 4498: sub is_advanced_user {
 4499:     my ($udom,$uname) = @_;
 4500:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 4501:     my %allroles;
 4502:     my $is_adv;
 4503:     foreach my $role (keys(%roleshash)) {
 4504:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 4505:         my $area = '/'.$tdomain.'/'.$trest;
 4506:         if ($sec ne '') {
 4507:             $area .= '/'.$sec;
 4508:         }
 4509:         if (($area ne '') && ($trole ne '')) {
 4510:             my $spec=$trole.'.'.$area;
 4511:             if ($trole =~ /^cr\//) {
 4512:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4513:             } elsif ($trole ne 'gr') {
 4514:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4515:             }
 4516:         }
 4517:     }
 4518:     foreach my $role (keys(%allroles)) {
 4519:         last if ($is_adv);
 4520:         foreach my $item (split(/:/,$allroles{$role})) {
 4521:             if ($item ne '') {
 4522:                 my ($privilege,$restrictions)=split(/&/,$item);
 4523:                 if ($privilege eq 'adv') {
 4524:                     $is_adv = 1;
 4525:                     last;
 4526:                 }
 4527:             }
 4528:         }
 4529:     }
 4530:     return $is_adv;
 4531: }
 4532: 
 4533: # ---------------------------------------------- Custom access rule evaluation
 4534: 
 4535: sub customaccess {
 4536:     my ($priv,$uri)=@_;
 4537:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4538:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4539:     $udom = &LONCAPA::clean_domain($udom);
 4540:     $ucrs = &LONCAPA::clean_username($ucrs);
 4541:     my $access=0;
 4542:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4543: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4544: 	if ($type eq 'user') {
 4545: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4546: 		my ($tdom,$tuname)=split(m{/},$scope);
 4547: 		if ($tdom) {
 4548: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4549: 		}
 4550: 		if ($tuname) {
 4551: 		    if ($tuname ne $env{'user.name'}) { next; }
 4552: 		}
 4553: 		$access=($effect eq 'allow');
 4554: 		last;
 4555: 	    }
 4556: 	} else {
 4557: 	    if ($role) {
 4558: 		if ($role ne $urole) { next; }
 4559: 	    }
 4560: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4561: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4562: 		if ($tdom) {
 4563: 		    if ($tdom ne $udom) { next; }
 4564: 		}
 4565: 		if ($tcrs) {
 4566: 		    if ($tcrs ne $ucrs) { next; }
 4567: 		}
 4568: 		if ($tsec) {
 4569: 		    if ($tsec ne $usec) { next; }
 4570: 		}
 4571: 		$access=($effect eq 'allow');
 4572: 		last;
 4573: 	    }
 4574: 	    if ($realm eq '' && $role eq '') {
 4575: 		$access=($effect eq 'allow');
 4576: 	    }
 4577: 	}
 4578:     }
 4579:     return $access;
 4580: }
 4581: 
 4582: # ------------------------------------------------- Check for a user privilege
 4583: 
 4584: sub allowed {
 4585:     my ($priv,$uri,$symb,$role)=@_;
 4586:     my $ver_orguri=$uri;
 4587:     $uri=&deversion($uri);
 4588:     my $orguri=$uri;
 4589:     $uri=&declutter($uri);
 4590: 
 4591:     if ($priv eq 'evb') {
 4592: # Evade communication block restrictions for specified role in a course
 4593:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4594:             return $1;
 4595:         } else {
 4596:             return;
 4597:         }
 4598:     }
 4599: 
 4600:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4601: # Free bre access to adm and meta resources
 4602:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4603: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4604: 	&& ($priv eq 'bre')) {
 4605: 	return 'F';
 4606:     }
 4607: 
 4608: # Free bre access to user's own portfolio contents
 4609:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4610:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4611: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4612:         my %setters;
 4613:         my ($startblock,$endblock) = 
 4614:             &Apache::loncommon::blockcheck(\%setters,'port');
 4615:         if ($startblock && $endblock) {
 4616:             return 'B';
 4617:         } else {
 4618:             return 'F';
 4619:         }
 4620:     }
 4621: 
 4622: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4623:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4624:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4625:         if (exists($env{'request.course.id'})) {
 4626:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4627:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4628:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4629:                 my $courseprivid=$env{'request.course.id'};
 4630:                 $courseprivid=~s/\_/\//;
 4631:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4632:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4633:                     return $1; 
 4634:                 } else {
 4635:                     if ($env{'request.course.sec'}) {
 4636:                         $courseprivid.='/'.$env{'request.course.sec'};
 4637:                     }
 4638:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4639:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4640:                         return $2;
 4641:                     }
 4642:                 }
 4643:             }
 4644:         }
 4645:     }
 4646: 
 4647: # Free bre to public access
 4648: 
 4649:     if ($priv eq 'bre') {
 4650:         my $copyright=&metadata($uri,'copyright');
 4651: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4652:            return 'F'; 
 4653:         }
 4654:         if ($copyright eq 'priv') {
 4655:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4656: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4657: 		return '';
 4658:             }
 4659:         }
 4660:         if ($copyright eq 'domain') {
 4661:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4662: 	    unless (($env{'user.domain'} eq $1) ||
 4663:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4664: 		return '';
 4665:             }
 4666:         }
 4667:         if ($env{'request.role'}=~ /li\.\//) {
 4668:             # Library role, so allow browsing of resources in this domain.
 4669:             return 'F';
 4670:         }
 4671:         if ($copyright eq 'custom') {
 4672: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4673:         }
 4674:     }
 4675:     # Domain coordinator is trying to create a course
 4676:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4677:         # uri is the requested domain in this case.
 4678:         # comparison to 'request.role.domain' shows if the user has selected
 4679:         # a role of dc for the domain in question.
 4680:         return 'F' if ($uri eq $env{'request.role.domain'});
 4681:     }
 4682: 
 4683:     my $thisallowed='';
 4684:     my $statecond=0;
 4685:     my $courseprivid='';
 4686: 
 4687: # Course
 4688: 
 4689:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4690:        $thisallowed.=$1;
 4691:     }
 4692: 
 4693: # Domain
 4694: 
 4695:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4696:        =~/\Q$priv\E\&([^\:]*)/) {
 4697:        $thisallowed.=$1;
 4698:     }
 4699: 
 4700: # Course: uri itself is a course
 4701:     my $courseuri=$uri;
 4702:     $courseuri=~s/\_(\d)/\/$1/;
 4703:     $courseuri=~s/^([^\/])/\/$1/;
 4704: 
 4705:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 4706:        =~/\Q$priv\E\&([^\:]*)/) {
 4707:        $thisallowed.=$1;
 4708:     }
 4709: 
 4710: # URI is an uploaded document for this course, default permissions don't matter
 4711: # not allowing 'edit' access (editupload) to uploaded course docs
 4712:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 4713: 	$thisallowed='';
 4714:         my ($match)=&is_on_map($uri);
 4715:         if ($match) {
 4716:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 4717:                   =~/\Q$priv\E\&([^\:]*)/) {
 4718:                 $thisallowed.=$1;
 4719:             }
 4720:         } else {
 4721:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 4722:             if ($refuri) {
 4723:                 if ($refuri =~ m|^/adm/|) {
 4724:                     $thisallowed='F';
 4725:                 } else {
 4726:                     $refuri=&declutter($refuri);
 4727:                     my ($match) = &is_on_map($refuri);
 4728:                     if ($match) {
 4729:                         $thisallowed='F';
 4730:                     }
 4731:                 }
 4732:             }
 4733:         }
 4734:     }
 4735: 
 4736:     if ($priv eq 'bre'
 4737: 	&& $thisallowed ne 'F' 
 4738: 	&& $thisallowed ne '2'
 4739: 	&& &is_portfolio_url($uri)) {
 4740: 	$thisallowed = &portfolio_access($uri);
 4741:     }
 4742:     
 4743: # Full access at system, domain or course-wide level? Exit.
 4744:     if ($thisallowed=~/F/) {
 4745: 	return 'F';
 4746:     }
 4747: 
 4748: # If this is generating or modifying users, exit with special codes
 4749: 
 4750:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4751: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4752: 	    my ($audom,$auname)=split('/',$uri);
 4753: # no author name given, so this just checks on the general right to make a co-author in this domain
 4754: 	    unless ($auname) { return $thisallowed; }
 4755: # an author name is given, so we are about to actually make a co-author for a certain account
 4756: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4757: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 4758: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 4759: 	}
 4760: 	return $thisallowed;
 4761:     }
 4762: #
 4763: # Gathered so far: system, domain and course wide privileges
 4764: #
 4765: # Course: See if uri or referer is an individual resource that is part of 
 4766: # the course
 4767: 
 4768:     if ($env{'request.course.id'}) {
 4769: 
 4770:        $courseprivid=$env{'request.course.id'};
 4771:        if ($env{'request.course.sec'}) {
 4772:           $courseprivid.='/'.$env{'request.course.sec'};
 4773:        }
 4774:        $courseprivid=~s/\_/\//;
 4775:        my $checkreferer=1;
 4776:        my ($match,$cond)=&is_on_map($uri);
 4777:        if ($match) {
 4778:            $statecond=$cond;
 4779:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4780:                =~/\Q$priv\E\&([^\:]*)/) {
 4781:                $thisallowed.=$1;
 4782:                $checkreferer=0;
 4783:            }
 4784:        }
 4785:        
 4786:        if ($checkreferer) {
 4787: 	  my $refuri=$env{'httpref.'.$orguri};
 4788:             unless ($refuri) {
 4789:                 foreach my $key (keys(%env)) {
 4790: 		    if ($key=~/^httpref\..*\*/) {
 4791: 			my $pattern=$key;
 4792:                         $pattern=~s/^httpref\.\/res\///;
 4793:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4794:                         $pattern=~s/\//\\\//g;
 4795:                         if ($orguri=~/$pattern/) {
 4796: 			    $refuri=$env{$key};
 4797:                         }
 4798:                     }
 4799:                 }
 4800:             }
 4801: 
 4802:          if ($refuri) { 
 4803: 	  $refuri=&declutter($refuri);
 4804:           my ($match,$cond)=&is_on_map($refuri);
 4805:             if ($match) {
 4806:               my $refstatecond=$cond;
 4807:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4808:                   =~/\Q$priv\E\&([^\:]*)/) {
 4809:                   $thisallowed.=$1;
 4810:                   $uri=$refuri;
 4811:                   $statecond=$refstatecond;
 4812:               }
 4813:           }
 4814:         }
 4815:        }
 4816:    }
 4817: 
 4818: #
 4819: # Gathered now: all privileges that could apply, and condition number
 4820: # 
 4821: #
 4822: # Full or no access?
 4823: #
 4824: 
 4825:     if ($thisallowed=~/F/) {
 4826: 	return 'F';
 4827:     }
 4828: 
 4829:     unless ($thisallowed) {
 4830:         return '';
 4831:     }
 4832: 
 4833: # Restrictions exist, deal with them
 4834: #
 4835: #   C:according to course preferences
 4836: #   R:according to resource settings
 4837: #   L:unless locked
 4838: #   X:according to user session state
 4839: #
 4840: 
 4841: # Possibly locked functionality, check all courses
 4842: # Locks might take effect only after 10 minutes cache expiration for other
 4843: # courses, and 2 minutes for current course
 4844: 
 4845:     my $envkey;
 4846:     if ($thisallowed=~/L/) {
 4847:         foreach $envkey (keys %env) {
 4848:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 4849:                my $courseid=$2;
 4850:                my $roleid=$1.'.'.$2;
 4851:                $courseid=~s/^\///;
 4852:                my $expiretime=600;
 4853:                if ($env{'request.role'} eq $roleid) {
 4854: 		  $expiretime=120;
 4855:                }
 4856: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 4857:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 4858:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 4859: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 4860:                }
 4861:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4862:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4863: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4864:                        &log($env{'user.domain'},$env{'user.name'},
 4865:                             $env{'user.home'},
 4866:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4867:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4868:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4869: 		       return '';
 4870:                    }
 4871:                }
 4872:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4873:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4874: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4875:                        &log($env{'user.domain'},$env{'user.name'},
 4876:                             $env{'user.home'},
 4877:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4878:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4879:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4880: 		       return '';
 4881:                    }
 4882:                }
 4883: 	   }
 4884:        }
 4885:     }
 4886:    
 4887: #
 4888: # Rest of the restrictions depend on selected course
 4889: #
 4890: 
 4891:     unless ($env{'request.course.id'}) {
 4892: 	if ($thisallowed eq 'A') {
 4893: 	    return 'A';
 4894:         } elsif ($thisallowed eq 'B') {
 4895:             return 'B';
 4896: 	} else {
 4897: 	    return '1';
 4898: 	}
 4899:     }
 4900: 
 4901: #
 4902: # Now user is definitely in a course
 4903: #
 4904: 
 4905: 
 4906: # Course preferences
 4907: 
 4908:    if ($thisallowed=~/C/) {
 4909:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4910:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4911:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4912: 	   =~/\Q$rolecode\E/) {
 4913: 	   if ($priv ne 'pch') { 
 4914: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4915: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4916: 			$env{'request.course.id'});
 4917: 	   }
 4918:            return '';
 4919:        }
 4920: 
 4921:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4922: 	   =~/\Q$unamedom\E/) {
 4923: 	   if ($priv ne 'pch') { 
 4924: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4925: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4926: 			$env{'request.course.id'});
 4927: 	   }
 4928:            return '';
 4929:        }
 4930:    }
 4931: 
 4932: # Resource preferences
 4933: 
 4934:    if ($thisallowed=~/R/) {
 4935:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4936:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4937: 	   if ($priv ne 'pch') { 
 4938: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4939: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4940: 	   }
 4941: 	   return '';
 4942:        }
 4943:    }
 4944: 
 4945: # Restricted by state or randomout?
 4946: 
 4947:    if ($thisallowed=~/X/) {
 4948:       if ($env{'acc.randomout'}) {
 4949: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4950:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4951:             return ''; 
 4952:          }
 4953:       }
 4954:       if (&condval($statecond)) {
 4955: 	 return '2';
 4956:       } else {
 4957:          return '';
 4958:       }
 4959:    }
 4960: 
 4961:     if ($thisallowed eq 'A') {
 4962: 	return 'A';
 4963:     } elsif ($thisallowed eq 'B') {
 4964:         return 'B';
 4965:     }
 4966:    return 'F';
 4967: }
 4968: 
 4969: sub split_uri_for_cond {
 4970:     my $uri=&deversion(&declutter(shift));
 4971:     my @uriparts=split(/\//,$uri);
 4972:     my $filename=pop(@uriparts);
 4973:     my $pathname=join('/',@uriparts);
 4974:     return ($pathname,$filename);
 4975: }
 4976: # --------------------------------------------------- Is a resource on the map?
 4977: 
 4978: sub is_on_map {
 4979:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 4980:     #Trying to find the conditional for the file
 4981:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 4982: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 4983:     if ($match) {
 4984: 	return (1,$1);
 4985:     } else {
 4986: 	return (0,0);
 4987:     }
 4988: }
 4989: 
 4990: # --------------------------------------------------------- Get symb from alias
 4991: 
 4992: sub get_symb_from_alias {
 4993:     my $symb=shift;
 4994:     my ($map,$resid,$url)=&decode_symb($symb);
 4995: # Already is a symb
 4996:     if ($url) { return $symb; }
 4997: # Must be an alias
 4998:     my $aliassymb='';
 4999:     my %bighash;
 5000:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5001:                             &GDBM_READER(),0640)) {
 5002:         my $rid=$bighash{'mapalias_'.$symb};
 5003: 	if ($rid) {
 5004: 	    my ($mapid,$resid)=split(/\./,$rid);
 5005: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 5006: 				    $resid,$bighash{'src_'.$rid});
 5007: 	}
 5008:         untie %bighash;
 5009:     }
 5010:     return $aliassymb;
 5011: }
 5012: 
 5013: # ----------------------------------------------------------------- Define Role
 5014: 
 5015: sub definerole {
 5016:   if (allowed('mcr','/')) {
 5017:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 5018:     foreach my $role (split(':',$sysrole)) {
 5019: 	my ($crole,$cqual)=split(/\&/,$role);
 5020:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 5021:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 5022: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5023:                return "refused:s:$crole&$cqual"; 
 5024:             }
 5025:         }
 5026:     }
 5027:     foreach my $role (split(':',$domrole)) {
 5028: 	my ($crole,$cqual)=split(/\&/,$role);
 5029:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 5030:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 5031: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 5032:                return "refused:d:$crole&$cqual"; 
 5033:             }
 5034:         }
 5035:     }
 5036:     foreach my $role (split(':',$courole)) {
 5037: 	my ($crole,$cqual)=split(/\&/,$role);
 5038:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 5039:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 5040: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5041:                return "refused:c:$crole&$cqual"; 
 5042:             }
 5043:         }
 5044:     }
 5045:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5046:                 "$env{'user.domain'}:$env{'user.name'}:".
 5047: 	        "rolesdef_$rolename=".
 5048:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 5049:     return reply($command,$env{'user.home'});
 5050:   } else {
 5051:     return 'refused';
 5052:   }
 5053: }
 5054: 
 5055: # ---------------- Make a metadata query against the network of library servers
 5056: 
 5057: sub metadata_query {
 5058:     my ($query,$custom,$customshow,$server_array)=@_;
 5059:     my %rhash;
 5060:     my %libserv = &all_library();
 5061:     my @server_list = (defined($server_array) ? @$server_array
 5062:                                               : keys(%libserv) );
 5063:     for my $server (@server_list) {
 5064: 	unless ($custom or $customshow) {
 5065: 	    my $reply=&reply("querysend:".&escape($query),$server);
 5066: 	    $rhash{$server}=$reply;
 5067: 	}
 5068: 	else {
 5069: 	    my $reply=&reply("querysend:".&escape($query).':'.
 5070: 			     &escape($custom).':'.&escape($customshow),
 5071: 			     $server);
 5072: 	    $rhash{$server}=$reply;
 5073: 	}
 5074:     }
 5075:     return \%rhash;
 5076: }
 5077: 
 5078: # ----------------------------------------- Send log queries and wait for reply
 5079: 
 5080: sub log_query {
 5081:     my ($uname,$udom,$query,%filters)=@_;
 5082:     my $uhome=&homeserver($uname,$udom);
 5083:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 5084:     my $uhost=&hostname($uhome);
 5085:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 5086:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 5087:                        $uhome);
 5088:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 5089:     return get_query_reply($queryid);
 5090: }
 5091: 
 5092: # -------------------------- Update MySQL table for portfolio file
 5093: 
 5094: sub update_portfolio_table {
 5095:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 5096:     if ($group ne '') {
 5097:         $file_name =~s /^\Q$group\E//;
 5098:     }
 5099:     my $homeserver = &homeserver($uname,$udom);
 5100:     my $queryid=
 5101:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 5102:                ':'.&escape($file_name).':'.$action,$homeserver);
 5103:     my $reply = &get_query_reply($queryid);
 5104:     return $reply;
 5105: }
 5106: 
 5107: # -------------------------- Update MySQL allusers table
 5108: 
 5109: sub update_allusers_table {
 5110:     my ($uname,$udom,$names) = @_;
 5111:     my $homeserver = &homeserver($uname,$udom);
 5112:     my $queryid=
 5113:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 5114:                'lastname='.&escape($names->{'lastname'}).'%%'.
 5115:                'firstname='.&escape($names->{'firstname'}).'%%'.
 5116:                'middlename='.&escape($names->{'middlename'}).'%%'.
 5117:                'generation='.&escape($names->{'generation'}).'%%'.
 5118:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 5119:                'id='.&escape($names->{'id'}),$homeserver);
 5120:     my $reply = &get_query_reply($queryid);
 5121:     return $reply;
 5122: }
 5123: 
 5124: # ------- Request retrieval of institutional classlists for course(s)
 5125: 
 5126: sub fetch_enrollment_query {
 5127:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 5128:     my $homeserver;
 5129:     my $maxtries = 1;
 5130:     if ($context eq 'automated') {
 5131:         $homeserver = $perlvar{'lonHostID'};
 5132:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 5133:     } else {
 5134:         $homeserver = &homeserver($cnum,$dom);
 5135:     }
 5136:     my $host=&hostname($homeserver);
 5137:     my $cmd = '';
 5138:     foreach my $affiliate (keys %{$affiliatesref}) {
 5139:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5140:     }
 5141:     $cmd =~ s/%%$//;
 5142:     $cmd = &escape($cmd);
 5143:     my $query = 'fetchenrollment';
 5144:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 5145:     unless ($queryid=~/^\Q$host\E\_/) { 
 5146:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 5147:         return 'error: '.$queryid;
 5148:     }
 5149:     my $reply = &get_query_reply($queryid);
 5150:     my $tries = 1;
 5151:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5152:         $reply = &get_query_reply($queryid);
 5153:         $tries ++;
 5154:     }
 5155:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5156:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5157:     } else {
 5158:         my @responses = split(/:/,$reply);
 5159:         if ($homeserver eq $perlvar{'lonHostID'}) {
 5160:             foreach my $line (@responses) {
 5161:                 my ($key,$value) = split(/=/,$line,2);
 5162:                 $$replyref{$key} = $value;
 5163:             }
 5164:         } else {
 5165:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 5166:             foreach my $line (@responses) {
 5167:                 my ($key,$value) = split(/=/,$line);
 5168:                 $$replyref{$key} = $value;
 5169:                 if ($value > 0) {
 5170:                     foreach my $item (@{$$affiliatesref{$key}}) {
 5171:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 5172:                         my $destname = $pathname.'/'.$filename;
 5173:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 5174:                         if ($xml_classlist =~ /^error/) {
 5175:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 5176:                         } else {
 5177:                             if ( open(FILE,">$destname") ) {
 5178:                                 print FILE &unescape($xml_classlist);
 5179:                                 close(FILE);
 5180:                             } else {
 5181:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 5182:                             }
 5183:                         }
 5184:                     }
 5185:                 }
 5186:             }
 5187:         }
 5188:         return 'ok';
 5189:     }
 5190:     return 'error';
 5191: }
 5192: 
 5193: sub get_query_reply {
 5194:     my $queryid=shift;
 5195:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 5196:     my $reply='';
 5197:     for (1..100) {
 5198: 	sleep 2;
 5199:         if (-e $replyfile.'.end') {
 5200: 	    if (open(my $fh,$replyfile)) {
 5201: 		$reply = join('',<$fh>);
 5202: 		close($fh);
 5203: 	   } else { return 'error: reply_file_error'; }
 5204:            return &unescape($reply);
 5205: 	}
 5206:     }
 5207:     return 'timeout:'.$queryid;
 5208: }
 5209: 
 5210: sub courselog_query {
 5211: #
 5212: # possible filters:
 5213: # url: url or symb
 5214: # username
 5215: # domain
 5216: # action: view, submit, grade
 5217: # start: timestamp
 5218: # end: timestamp
 5219: #
 5220:     my (%filters)=@_;
 5221:     unless ($env{'request.course.id'}) { return 'no_course'; }
 5222:     if ($filters{'url'}) {
 5223: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 5224:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 5225:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 5226:     }
 5227:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5228:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5229:     return &log_query($cname,$cdom,'courselog',%filters);
 5230: }
 5231: 
 5232: sub userlog_query {
 5233: #
 5234: # possible filters:
 5235: # action: log check role
 5236: # start: timestamp
 5237: # end: timestamp
 5238: #
 5239:     my ($uname,$udom,%filters)=@_;
 5240:     return &log_query($uname,$udom,'userlog',%filters);
 5241: }
 5242: 
 5243: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 5244: 
 5245: sub auto_run {
 5246:     my ($cnum,$cdom) = @_;
 5247:     my $response = 0;
 5248:     my $settings;
 5249:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 5250:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5251:         $settings = $domconfig{'autoenroll'};
 5252:         if ($settings->{'run'} eq '1') {
 5253:             $response = 1;
 5254:         }
 5255:     } else {
 5256:         my $homeserver;
 5257:         if (&is_course($cdom,$cnum)) {
 5258:             $homeserver = &homeserver($cnum,$cdom);
 5259:         } else {
 5260:             $homeserver = &domain($cdom,'primary');
 5261:         }
 5262:         if ($homeserver ne 'no_host') {
 5263:             $response = &reply('autorun:'.$cdom,$homeserver);
 5264:         }
 5265:     }
 5266:     return $response;
 5267: }
 5268: 
 5269: sub auto_get_sections {
 5270:     my ($cnum,$cdom,$inst_coursecode) = @_;
 5271:     my $homeserver = &homeserver($cnum,$cdom);
 5272:     my @secs = ();
 5273:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 5274:     unless ($response eq 'refused') {
 5275:         @secs = split(/:/,$response);
 5276:     }
 5277:     return @secs;
 5278: }
 5279: 
 5280: sub auto_new_course {
 5281:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 5282:     my $homeserver = &homeserver($cnum,$cdom);
 5283:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 5284:     return $response;
 5285: }
 5286: 
 5287: sub auto_validate_courseID {
 5288:     my ($cnum,$cdom,$inst_course_id) = @_;
 5289:     my $homeserver = &homeserver($cnum,$cdom);
 5290:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5291:     return $response;
 5292: }
 5293: 
 5294: sub auto_create_password {
 5295:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5296:     my ($homeserver,$response);
 5297:     my $create_passwd = 0;
 5298:     my $authchk = '';
 5299:     if ($udom =~ /^$match_domain$/) {
 5300:         $homeserver = &domain($udom,'primary');
 5301:     }
 5302:     if ($homeserver eq '') {
 5303:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5304:             $homeserver = &homeserver($cnum,$cdom);
 5305:         }
 5306:     }
 5307:     if ($homeserver eq '') {
 5308:         $authchk = 'nodomain';
 5309:     } else {
 5310:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5311:         if ($response eq 'refused') {
 5312:             $authchk = 'refused';
 5313:         } else {
 5314:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5315:         }
 5316:     }
 5317:     return ($authparam,$create_passwd,$authchk);
 5318: }
 5319: 
 5320: sub auto_photo_permission {
 5321:     my ($cnum,$cdom,$students) = @_;
 5322:     my $homeserver = &homeserver($cnum,$cdom);
 5323:     my ($outcome,$perm_reqd,$conditions) = 
 5324: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5325:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5326: 	return (undef,undef);
 5327:     }
 5328:     return ($outcome,$perm_reqd,$conditions);
 5329: }
 5330: 
 5331: sub auto_checkphotos {
 5332:     my ($uname,$udom,$pid) = @_;
 5333:     my $homeserver = &homeserver($uname,$udom);
 5334:     my ($result,$resulttype);
 5335:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5336: 				   &escape($uname).':'.&escape($pid),
 5337: 				   $homeserver));
 5338:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5339: 	return (undef,undef);
 5340:     }
 5341:     if ($outcome) {
 5342:         ($result,$resulttype) = split(/:/,$outcome);
 5343:     } 
 5344:     return ($result,$resulttype);
 5345: }
 5346: 
 5347: sub auto_photochoice {
 5348:     my ($cnum,$cdom) = @_;
 5349:     my $homeserver = &homeserver($cnum,$cdom);
 5350:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5351: 						       &escape($cdom),
 5352: 						       $homeserver)));
 5353:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5354: 	return (undef,undef);
 5355:     }
 5356:     return ($update,$comment);
 5357: }
 5358: 
 5359: sub auto_photoupdate {
 5360:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5361:     my $homeserver = &homeserver($cnum,$dom);
 5362:     my $host=&hostname($homeserver);
 5363:     my $cmd = '';
 5364:     my $maxtries = 1;
 5365:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5366:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5367:     }
 5368:     $cmd =~ s/%%$//;
 5369:     $cmd = &escape($cmd);
 5370:     my $query = 'institutionalphotos';
 5371:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5372:     unless ($queryid=~/^\Q$host\E\_/) {
 5373:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5374:         return 'error: '.$queryid;
 5375:     }
 5376:     my $reply = &get_query_reply($queryid);
 5377:     my $tries = 1;
 5378:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5379:         $reply = &get_query_reply($queryid);
 5380:         $tries ++;
 5381:     }
 5382:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5383:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5384:     } else {
 5385:         my @responses = split(/:/,$reply);
 5386:         my $outcome = shift(@responses); 
 5387:         foreach my $item (@responses) {
 5388:             my ($key,$value) = split(/=/,$item);
 5389:             $$photo{$key} = $value;
 5390:         }
 5391:         return $outcome;
 5392:     }
 5393:     return 'error';
 5394: }
 5395: 
 5396: sub auto_instcode_format {
 5397:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5398: 	$cat_order) = @_;
 5399:     my $courses = '';
 5400:     my @homeservers;
 5401:     if ($caller eq 'global') {
 5402: 	my %servers = &get_servers($codedom,'library');
 5403: 	foreach my $tryserver (keys(%servers)) {
 5404: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5405: 		push(@homeservers,$tryserver);
 5406: 	    }
 5407:         }
 5408:     } else {
 5409:         push(@homeservers,&homeserver($caller,$codedom));
 5410:     }
 5411:     foreach my $code (keys(%{$instcodes})) {
 5412:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5413:     }
 5414:     chop($courses);
 5415:     my $ok_response = 0;
 5416:     my $response;
 5417:     while (@homeservers > 0 && $ok_response == 0) {
 5418:         my $server = shift(@homeservers); 
 5419:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5420:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5421:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5422: 		split(/:/,$response);
 5423:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5424:             push(@{$codetitles},&str2array($codetitles_str));
 5425:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5426:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5427:             $ok_response = 1;
 5428:         }
 5429:     }
 5430:     if ($ok_response) {
 5431:         return 'ok';
 5432:     } else {
 5433:         return $response;
 5434:     }
 5435: }
 5436: 
 5437: sub auto_instcode_defaults {
 5438:     my ($domain,$returnhash,$code_order) = @_;
 5439:     my @homeservers;
 5440: 
 5441:     my %servers = &get_servers($domain,'library');
 5442:     foreach my $tryserver (keys(%servers)) {
 5443: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5444: 	    push(@homeservers,$tryserver);
 5445: 	}
 5446:     }
 5447: 
 5448:     my $response;
 5449:     foreach my $server (@homeservers) {
 5450:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5451:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5452: 	
 5453: 	foreach my $pair (split(/\&/,$response)) {
 5454: 	    my ($name,$value)=split(/\=/,$pair);
 5455: 	    if ($name eq 'code_order') {
 5456: 		@{$code_order} = split(/\&/,&unescape($value));
 5457: 	    } else {
 5458: 		$returnhash->{&unescape($name)}=&unescape($value);
 5459: 	    }
 5460: 	}
 5461: 	return 'ok';
 5462:     }
 5463: 
 5464:     return $response;
 5465: } 
 5466: 
 5467: sub auto_validate_class_sec {
 5468:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5469:     my $homeserver = &homeserver($cnum,$cdom);
 5470:     my $ownerlist;
 5471:     if (ref($owners) eq 'ARRAY') {
 5472:         $ownerlist = join(',',@{$owners});
 5473:     } else {
 5474:         $ownerlist = $owners;
 5475:     }
 5476:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 5477:                         &escape($ownerlist).':'.$cdom,$homeserver);
 5478:     return $response;
 5479: }
 5480: 
 5481: # ------------------------------------------------------- Course Group routines
 5482: 
 5483: sub get_coursegroups {
 5484:     my ($cdom,$cnum,$group,$namespace) = @_;
 5485:     return(&dump($namespace,$cdom,$cnum,$group));
 5486: }
 5487: 
 5488: sub modify_coursegroup {
 5489:     my ($cdom,$cnum,$groupsettings) = @_;
 5490:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 5491: }
 5492: 
 5493: sub toggle_coursegroup_status {
 5494:     my ($cdom,$cnum,$group,$action) = @_;
 5495:     my ($from_namespace,$to_namespace);
 5496:     if ($action eq 'delete') {
 5497:         $from_namespace = 'coursegroups';
 5498:         $to_namespace = 'deleted_groups';
 5499:     } else {
 5500:         $from_namespace = 'deleted_groups';
 5501:         $to_namespace = 'coursegroups';
 5502:     }
 5503:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 5504:     if (my $tmp = &error(%curr_group)) {
 5505:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 5506:         return ('read error',$tmp);
 5507:     } else {
 5508:         my %savedsettings = %curr_group; 
 5509:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 5510:         my $deloutcome;
 5511:         if ($result eq 'ok') {
 5512:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 5513:         } else {
 5514:             return ('write error',$result);
 5515:         }
 5516:         if ($deloutcome eq 'ok') {
 5517:             return 'ok';
 5518:         } else {
 5519:             return ('delete error',$deloutcome);
 5520:         }
 5521:     }
 5522: }
 5523: 
 5524: sub modify_group_roles {
 5525:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 5526:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 5527:     my $role = 'gr/'.&escape($userprivs);
 5528:     my ($uname,$udom) = split(/:/,$user);
 5529:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 5530:     if ($result eq 'ok') {
 5531:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 5532:     }
 5533:     return $result;
 5534: }
 5535: 
 5536: sub modify_coursegroup_membership {
 5537:     my ($cdom,$cnum,$membership) = @_;
 5538:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 5539:     return $result;
 5540: }
 5541: 
 5542: sub get_active_groups {
 5543:     my ($udom,$uname,$cdom,$cnum) = @_;
 5544:     my $now = time;
 5545:     my %groups = ();
 5546:     foreach my $key (keys(%env)) {
 5547:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 5548:             my ($start,$end) = split(/\./,$env{$key});
 5549:             if (($end!=0) && ($end<$now)) { next; }
 5550:             if (($start!=0) && ($start>$now)) { next; }
 5551:             if ($1 eq $cdom && $2 eq $cnum) {
 5552:                 $groups{$3} = $env{$key} ;
 5553:             }
 5554:         }
 5555:     }
 5556:     return %groups;
 5557: }
 5558: 
 5559: sub get_group_membership {
 5560:     my ($cdom,$cnum,$group) = @_;
 5561:     return(&dump('groupmembership',$cdom,$cnum,$group));
 5562: }
 5563: 
 5564: sub get_users_groups {
 5565:     my ($udom,$uname,$courseid) = @_;
 5566:     my @usersgroups;
 5567:     my $cachetime=1800;
 5568: 
 5569:     my $hashid="$udom:$uname:$courseid";
 5570:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 5571:     if (defined($cached)) {
 5572:         @usersgroups = split(/:/,$grouplist);
 5573:     } else {  
 5574:         $grouplist = '';
 5575:         my $courseurl = &courseid_to_courseurl($courseid);
 5576:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 5577:         my $access_end = $env{'course.'.$courseid.
 5578:                               '.default_enrollment_end_date'};
 5579:         my $now = time;
 5580:         foreach my $key (keys(%roleshash)) {
 5581:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 5582:                 my $group = $1;
 5583:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 5584:                     my $start = $2;
 5585:                     my $end = $1;
 5586:                     if ($start == -1) { next; } # deleted from group
 5587:                     if (($start!=0) && ($start>$now)) { next; }
 5588:                     if (($end!=0) && ($end<$now)) {
 5589:                         if ($access_end && $access_end < $now) {
 5590:                             if ($access_end - $end < 86400) {
 5591:                                 push(@usersgroups,$group);
 5592:                             }
 5593:                         }
 5594:                         next;
 5595:                     }
 5596:                     push(@usersgroups,$group);
 5597:                 }
 5598:             }
 5599:         }
 5600:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 5601:         $grouplist = join(':',@usersgroups);
 5602:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 5603:     }
 5604:     return @usersgroups;
 5605: }
 5606: 
 5607: sub devalidate_getgroups_cache {
 5608:     my ($udom,$uname,$cdom,$cnum)=@_;
 5609:     my $courseid = $cdom.'_'.$cnum;
 5610: 
 5611:     my $hashid="$udom:$uname:$courseid";
 5612:     &devalidate_cache_new('getgroups',$hashid);
 5613: }
 5614: 
 5615: # ------------------------------------------------------------------ Plain Text
 5616: 
 5617: sub plaintext {
 5618:     my ($short,$type,$cid) = @_;
 5619:     if ($short =~ /^cr/) {
 5620: 	return (split('/',$short))[-1];
 5621:     }
 5622:     if (!defined($cid)) {
 5623:         $cid = $env{'request.course.id'};
 5624:     }
 5625:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 5626:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 5627:                                           '.plaintext'});
 5628:     }
 5629:     my %rolenames = (
 5630:                       Course => 'std',
 5631:                       Group => 'alt1',
 5632:                     );
 5633:     if (defined($type) && 
 5634:          defined($rolenames{$type}) && 
 5635:          defined($prp{$short}{$rolenames{$type}})) {
 5636:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 5637:     } else {
 5638:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 5639:     }
 5640: }
 5641: 
 5642: # ----------------------------------------------------------------- Assign Role
 5643: 
 5644: sub assignrole {
 5645:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 5646:         $context)=@_;
 5647:     my $mrole;
 5648:     if ($role =~ /^cr\//) {
 5649:         my $cwosec=$url;
 5650:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5651: 	unless (&allowed('ccr',$cwosec)) {
 5652:            &logthis('Refused custom assignrole: '.
 5653:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5654: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 5655:            return 'refused'; 
 5656:         }
 5657:         $mrole='cr';
 5658:     } elsif ($role =~ /^gr\//) {
 5659:         my $cwogrp=$url;
 5660:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 5661:         unless (&allowed('mdg',$cwogrp)) {
 5662:             &logthis('Refused group assignrole: '.
 5663:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5664:                     $env{'user.name'}.' at '.$env{'user.domain'});
 5665:             return 'refused';
 5666:         }
 5667:         $mrole='gr';
 5668:     } else {
 5669:         my $cwosec=$url;
 5670:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5671:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 5672:             my $refused;
 5673:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 5674:                 if (!(&allowed('c'.$role,$url))) {
 5675:                     $refused = 1;
 5676:                 }
 5677:             } else {
 5678:                 $refused = 1;
 5679:             }
 5680:             if ($refused) {
 5681:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5682:                     $refused = '';
 5683:                 } else {
 5684:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 5685:                              ' '.$role.' '.$end.' '.$start.' by '.
 5686: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 5687:                     return 'refused';
 5688:                 }
 5689:             }
 5690:         }
 5691:         $mrole=$role;
 5692:     }
 5693:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5694:                 "$udom:$uname:$url".'_'."$mrole=$role";
 5695:     if ($end) { $command.='_'.$end; }
 5696:     if ($start) {
 5697: 	if ($end) { 
 5698:            $command.='_'.$start; 
 5699:         } else {
 5700:            $command.='_0_'.$start;
 5701:         }
 5702:     }
 5703:     my $origstart = $start;
 5704:     my $origend = $end;
 5705:     my $delflag;
 5706: # actually delete
 5707:     if ($deleteflag) {
 5708: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 5709: # modify command to delete the role
 5710:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 5711:                 "$udom:$uname:$url".'_'."$mrole";
 5712: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 5713: # set start and finish to negative values for userrolelog
 5714:            $start=-1;
 5715:            $end=-1;
 5716:            $delflag = 1;
 5717:         }
 5718:     }
 5719: # send command
 5720:     my $answer=&reply($command,&homeserver($uname,$udom));
 5721: # log new user role if status is ok
 5722:     if ($answer eq 'ok') {
 5723: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 5724: # for course roles, perform group memberships changes triggered by role change.
 5725:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 5726:         unless ($role =~ /^gr/) {
 5727:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 5728:                                              $origstart,$selfenroll,$context);
 5729:         }
 5730:     }
 5731:     return $answer;
 5732: }
 5733: 
 5734: # -------------------------------------------------- Modify user authentication
 5735: # Overrides without validation
 5736: 
 5737: sub modifyuserauth {
 5738:     my ($udom,$uname,$umode,$upass)=@_;
 5739:     my $uhome=&homeserver($uname,$udom);
 5740:     unless (&allowed('mau',$udom)) { return 'refused'; }
 5741:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 5742:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5743:              ' in domain '.$env{'request.role.domain'});  
 5744:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 5745: 		     &escape($upass),$uhome);
 5746:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 5747:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 5748:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5749:     &log($udom,,$uname,$uhome,
 5750:         'Authentication changed by '.$env{'user.domain'}.', '.
 5751:                                      $env{'user.name'}.', '.$umode.
 5752:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5753:     unless ($reply eq 'ok') {
 5754:         &logthis('Authentication mode error: '.$reply);
 5755: 	return 'error: '.$reply;
 5756:     }   
 5757:     return 'ok';
 5758: }
 5759: 
 5760: # --------------------------------------------------------------- Modify a user
 5761: 
 5762: sub modifyuser {
 5763:     my ($udom,    $uname, $uid,
 5764:         $umode,   $upass, $first,
 5765:         $middle,  $last,  $gene,
 5766:         $forceid, $desiredhome, $email, $inststatus)=@_;
 5767:     $udom= &LONCAPA::clean_domain($udom);
 5768:     $uname=&LONCAPA::clean_username($uname);
 5769:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 5770:              $umode.', '.$first.', '.$middle.', '.
 5771: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 5772:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 5773:                                      ' desiredhome not specified'). 
 5774:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5775:              ' in domain '.$env{'request.role.domain'});
 5776:     my $uhome=&homeserver($uname,$udom,'true');
 5777: # ----------------------------------------------------------------- Create User
 5778:     if (($uhome eq 'no_host') && 
 5779: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 5780:         my $unhome='';
 5781:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 5782:             $unhome = $desiredhome;
 5783: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 5784: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 5785:         } else { # load balancing routine for determining $unhome
 5786:             my $loadm=10000000;
 5787: 	    my %servers = &get_servers($udom,'library');
 5788: 	    foreach my $tryserver (keys(%servers)) {
 5789: 		my $answer=reply('load',$tryserver);
 5790: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 5791: 		    $loadm=$answer;
 5792: 		    $unhome=$tryserver;
 5793: 		}
 5794: 	    }
 5795:         }
 5796:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 5797: 	    return 'error: unable to find a home server for '.$uname.
 5798:                    ' in domain '.$udom;
 5799:         }
 5800:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 5801:                          &escape($upass),$unhome);
 5802: 	unless ($reply eq 'ok') {
 5803:             return 'error: '.$reply;
 5804:         }   
 5805:         $uhome=&homeserver($uname,$udom,'true');
 5806:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 5807: 	    return 'error: unable verify users home machine.';
 5808:         }
 5809:     }   # End of creation of new user
 5810: # ---------------------------------------------------------------------- Add ID
 5811:     if ($uid) {
 5812:        $uid=~tr/A-Z/a-z/;
 5813:        my %uidhash=&idrget($udom,$uname);
 5814:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 5815:          && (!$forceid)) {
 5816: 	  unless ($uid eq $uidhash{$uname}) {
 5817: 	      return 'error: user id "'.$uid.'" does not match '.
 5818:                   'current user id "'.$uidhash{$uname}.'".';
 5819:           }
 5820:        } else {
 5821: 	  &idput($udom,($uname => $uid));
 5822:        }
 5823:     }
 5824: # -------------------------------------------------------------- Add names, etc
 5825:     my @tmp=&get('environment',
 5826: 		   ['firstname','middlename','lastname','generation','id',
 5827:                     'permanentemail','inststatus'],
 5828: 		   $udom,$uname);
 5829:     my %names;
 5830:     if ($tmp[0] =~ m/^error:.*/) { 
 5831:         %names=(); 
 5832:     } else {
 5833:         %names = @tmp;
 5834:     }
 5835: #
 5836: # Make sure to not trash student environment if instructor does not bother
 5837: # to supply name and email information
 5838: #
 5839:     if ($first)  { $names{'firstname'}  = $first; }
 5840:     if (defined($middle)) { $names{'middlename'} = $middle; }
 5841:     if ($last)   { $names{'lastname'}   = $last; }
 5842:     if (defined($gene))   { $names{'generation'} = $gene; }
 5843:     if ($email) {
 5844:        $email=~s/[^\w\@\.\-\,]//gs;
 5845:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 5846:     }
 5847:     if ($uid) { $names{'id'}  = $uid; }
 5848:     if (defined($inststatus)) { $names{'inststatus'} = $inststatus; } 
 5849:     my $reply = &put('environment', \%names, $udom,$uname);
 5850:     if ($reply ne 'ok') { return 'error: '.$reply; }
 5851:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 5852:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 5853:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 5854:                  $umode.', '.$first.', '.$middle.', '.
 5855: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
 5856:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 5857:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 5858:     } else {
 5859:         $logmsg .= ' during self creation';
 5860:     }
 5861:     &logthis($logmsg);
 5862:     return 'ok';
 5863: }
 5864: 
 5865: # -------------------------------------------------------------- Modify student
 5866: 
 5867: sub modifystudent {
 5868:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 5869:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 5870:         $selfenroll,$context)=@_;
 5871:     if (!$cid) {
 5872: 	unless ($cid=$env{'request.course.id'}) {
 5873: 	    return 'not_in_class';
 5874: 	}
 5875:     }
 5876: # --------------------------------------------------------------- Make the user
 5877:     my $reply=&modifyuser
 5878: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 5879:          $desiredhome,$email);
 5880:     unless ($reply eq 'ok') { return $reply; }
 5881:     # This will cause &modify_student_enrollment to get the uid from the
 5882:     # students environment
 5883:     $uid = undef if (!$forceid);
 5884:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 5885: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 5886:     return $reply;
 5887: }
 5888: 
 5889: sub modify_student_enrollment {
 5890:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 5891:     my ($cdom,$cnum,$chome);
 5892:     if (!$cid) {
 5893: 	unless ($cid=$env{'request.course.id'}) {
 5894: 	    return 'not_in_class';
 5895: 	}
 5896: 	$cdom=$env{'course.'.$cid.'.domain'};
 5897: 	$cnum=$env{'course.'.$cid.'.num'};
 5898:     } else {
 5899: 	($cdom,$cnum)=split(/_/,$cid);
 5900:     }
 5901:     $chome=$env{'course.'.$cid.'.home'};
 5902:     if (!$chome) {
 5903: 	$chome=&homeserver($cnum,$cdom);
 5904:     }
 5905:     if (!$chome) { return 'unknown_course'; }
 5906:     # Make sure the user exists
 5907:     my $uhome=&homeserver($uname,$udom);
 5908:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5909: 	return 'error: no such user';
 5910:     }
 5911:     # Get student data if we were not given enough information
 5912:     if (!defined($first)  || $first  eq '' || 
 5913:         !defined($last)   || $last   eq '' || 
 5914:         !defined($uid)    || $uid    eq '' || 
 5915:         !defined($middle) || $middle eq '' || 
 5916:         !defined($gene)   || $gene   eq '') {
 5917:         # They did not supply us with enough data to enroll the student, so
 5918:         # we need to pick up more information.
 5919:         my %tmp = &get('environment',
 5920:                        ['firstname','middlename','lastname', 'generation','id']
 5921:                        ,$udom,$uname);
 5922: 
 5923:         #foreach my $key (keys(%tmp)) {
 5924:         #    &logthis("key $key = ".$tmp{$key});
 5925:         #}
 5926:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 5927:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 5928:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 5929:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 5930:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 5931:     }
 5932:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 5933:     my $reply=cput('classlist',
 5934: 		   {"$uname:$udom" => 
 5935: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 5936: 		   $cdom,$cnum);
 5937:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 5938: 	return 'error: '.$reply;
 5939:     } else {
 5940: 	&devalidate_getsection_cache($udom,$uname,$cid);
 5941:     }
 5942:     # Add student role to user
 5943:     my $uurl='/'.$cid;
 5944:     $uurl=~s/\_/\//g;
 5945:     if ($usec) {
 5946: 	$uurl.='/'.$usec;
 5947:     }
 5948:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 5949: }
 5950: 
 5951: sub format_name {
 5952:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 5953:     my $name;
 5954:     if ($first ne 'lastname') {
 5955: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 5956:     } else {
 5957: 	if ($lastname=~/\S/) {
 5958: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 5959: 	    $name=~s/\s+,/,/;
 5960: 	} else {
 5961: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 5962: 	}
 5963:     }
 5964:     $name=~s/^\s+//;
 5965:     $name=~s/\s+$//;
 5966:     $name=~s/\s+/ /g;
 5967:     return $name;
 5968: }
 5969: 
 5970: # ------------------------------------------------- Write to course preferences
 5971: 
 5972: sub writecoursepref {
 5973:     my ($courseid,%prefs)=@_;
 5974:     $courseid=~s/^\///;
 5975:     $courseid=~s/\_/\//g;
 5976:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5977:     my $chome=homeserver($cnum,$cdomain);
 5978:     if (($chome eq '') || ($chome eq 'no_host')) { 
 5979: 	return 'error: no such course';
 5980:     }
 5981:     my $cstring='';
 5982:     foreach my $pref (keys(%prefs)) {
 5983: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 5984:     }
 5985:     $cstring=~s/\&$//;
 5986:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 5987: }
 5988: 
 5989: # ---------------------------------------------------------- Make/modify course
 5990: 
 5991: sub createcourse {
 5992:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 5993:         $course_owner,$crstype)=@_;
 5994:     $url=&declutter($url);
 5995:     my $cid='';
 5996:     unless (&allowed('ccc',$udom)) {
 5997:         return 'refused';
 5998:     }
 5999: # ------------------------------------------------------------------- Create ID
 6000:    my $uname=int(1+rand(9)).
 6001:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6002:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6003:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6004: # ----------------------------------------------- Make sure that does not exist
 6005:    my $uhome=&homeserver($uname,$udom,'true');
 6006:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6007:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6008:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6009:        $uhome=&homeserver($uname,$udom,'true');       
 6010:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6011:            return 'error: unable to generate unique course-ID';
 6012:        } 
 6013:    }
 6014: # ------------------------------------------------ Check supplied server name
 6015:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 6016:     if (! &is_library($course_server)) {
 6017:         return 'error:bad server name '.$course_server;
 6018:     }
 6019: # ------------------------------------------------------------- Make the course
 6020:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 6021:                       $course_server);
 6022:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 6023:     $uhome=&homeserver($uname,$udom,'true');
 6024:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6025: 	return 'error: no such course';
 6026:     }
 6027: # ----------------------------------------------------------------- Course made
 6028: # log existence
 6029:     my $newcourse = {
 6030:                     $udom.'_'.$uname => {
 6031:                                      description => $description,
 6032:                                      inst_code   => $inst_code,
 6033:                                      owner       => $course_owner,
 6034:                                      type        => $crstype,
 6035:                                                 },
 6036:                     };
 6037:     &courseidput($udom,$newcourse,$uhome,'notime');
 6038: # set toplevel url
 6039:     my $topurl=$url;
 6040:     unless ($nonstandard) {
 6041: # ------------------------------------------ For standard courses, make top url
 6042:         my $mapurl=&clutter($url);
 6043:         if ($mapurl eq '/res/') { $mapurl=''; }
 6044:         $env{'form.initmap'}=(<<ENDINITMAP);
 6045: <map>
 6046: <resource id="1" type="start"></resource>
 6047: <resource id="2" src="$mapurl"></resource>
 6048: <resource id="3" type="finish"></resource>
 6049: <link index="1" from="1" to="2"></link>
 6050: <link index="2" from="2" to="3"></link>
 6051: </map>
 6052: ENDINITMAP
 6053:         $topurl=&declutter(
 6054:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 6055:                           );
 6056:     }
 6057: # ----------------------------------------------------------- Write preferences
 6058:     &writecoursepref($udom.'_'.$uname,
 6059:                      ('description' => $description,
 6060:                       'url'         => $topurl));
 6061:     return '/'.$udom.'/'.$uname;
 6062: }
 6063: 
 6064: sub is_course {
 6065:     my ($cdom,$cnum) = @_;
 6066:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 6067: 				undef,'.');
 6068:     if (exists($courses{$cdom.'_'.$cnum})) {
 6069:         return 1;
 6070:     }
 6071:     return 0;
 6072: }
 6073: 
 6074: # ---------------------------------------------------------- Assign Custom Role
 6075: 
 6076: sub assigncustomrole {
 6077:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 6078:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 6079:                        $end,$start,$deleteflag,$selfenroll,$context);
 6080: }
 6081: 
 6082: # ----------------------------------------------------------------- Revoke Role
 6083: 
 6084: sub revokerole {
 6085:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 6086:     my $now=time;
 6087:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 6088: }
 6089: 
 6090: # ---------------------------------------------------------- Revoke Custom Role
 6091: 
 6092: sub revokecustomrole {
 6093:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 6094:     my $now=time;
 6095:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 6096:            $deleteflag,$selfenroll,$context);
 6097: }
 6098: 
 6099: # ------------------------------------------------------------ Disk usage
 6100: sub diskusage {
 6101:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 6102:     $directorypath =~ s/\/$//;
 6103:     my $listing=&reply('du2:'.&escape($directorypath).':'
 6104:                        .&escape($getpropath).':'.&escape($uname).':'
 6105:                        .&escape($udom),homeserver($uname,$udom));
 6106:     if ($listing eq 'unknown_cmd') {
 6107:         if ($getpropath) {
 6108:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 6109:         }
 6110:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 6111:     }
 6112:     return $listing;
 6113: }
 6114: 
 6115: sub is_locked {
 6116:     my ($file_name, $domain, $user) = @_;
 6117:     my @check;
 6118:     my $is_locked;
 6119:     push @check, $file_name;
 6120:     my %locked = &get('file_permissions',\@check,
 6121: 		      $env{'user.domain'},$env{'user.name'});
 6122:     my ($tmp)=keys(%locked);
 6123:     if ($tmp=~/^error:/) { undef(%locked); }
 6124:     
 6125:     if (ref($locked{$file_name}) eq 'ARRAY') {
 6126:         $is_locked = 'false';
 6127:         foreach my $entry (@{$locked{$file_name}}) {
 6128:            if (ref($entry) eq 'ARRAY') { 
 6129:                $is_locked = 'true';
 6130:                last;
 6131:            }
 6132:        }
 6133:     } else {
 6134:         $is_locked = 'false';
 6135:     }
 6136: }
 6137: 
 6138: sub declutter_portfile {
 6139:     my ($file) = @_;
 6140:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 6141:     return $file;
 6142: }
 6143: 
 6144: # ------------------------------------------------------------- Mark as Read Only
 6145: 
 6146: sub mark_as_readonly {
 6147:     my ($domain,$user,$files,$what) = @_;
 6148:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6149:     my ($tmp)=keys(%current_permissions);
 6150:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6151:     foreach my $file (@{$files}) {
 6152: 	$file = &declutter_portfile($file);
 6153:         push(@{$current_permissions{$file}},$what);
 6154:     }
 6155:     &put('file_permissions',\%current_permissions,$domain,$user);
 6156:     return;
 6157: }
 6158: 
 6159: # ------------------------------------------------------------Save Selected Files
 6160: 
 6161: sub save_selected_files {
 6162:     my ($user, $path, @files) = @_;
 6163:     my $filename = $user."savedfiles";
 6164:     my @other_files = &files_not_in_path($user, $path);
 6165:     open (OUT, '>'.$tmpdir.$filename);
 6166:     foreach my $file (@files) {
 6167:         print (OUT $env{'form.currentpath'}.$file."\n");
 6168:     }
 6169:     foreach my $file (@other_files) {
 6170:         print (OUT $file."\n");
 6171:     }
 6172:     close (OUT);
 6173:     return 'ok';
 6174: }
 6175: 
 6176: sub clear_selected_files {
 6177:     my ($user) = @_;
 6178:     my $filename = $user."savedfiles";
 6179:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6180:     print (OUT undef);
 6181:     close (OUT);
 6182:     return ("ok");    
 6183: }
 6184: 
 6185: sub files_in_path {
 6186:     my ($user, $path) = @_;
 6187:     my $filename = $user."savedfiles";
 6188:     my %return_files;
 6189:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6190:     while (my $line_in = <IN>) {
 6191:         chomp ($line_in);
 6192:         my @paths_and_file = split (m!/!, $line_in);
 6193:         my $file_part = pop (@paths_and_file);
 6194:         my $path_part = join ('/', @paths_and_file);
 6195:         $path_part.='/';
 6196:         my $path_and_file = $path_part.$file_part;
 6197:         if ($path_part eq $path) {
 6198:             $return_files{$file_part}= 'selected';
 6199:         }
 6200:     }
 6201:     close (IN);
 6202:     return (\%return_files);
 6203: }
 6204: 
 6205: # called in portfolio select mode, to show files selected NOT in current directory
 6206: sub files_not_in_path {
 6207:     my ($user, $path) = @_;
 6208:     my $filename = $user."savedfiles";
 6209:     my @return_files;
 6210:     my $path_part;
 6211:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6212:     while (my $line = <IN>) {
 6213:         #ok, I know it's clunky, but I want it to work
 6214:         my @paths_and_file = split(m|/|, $line);
 6215:         my $file_part = pop(@paths_and_file);
 6216:         chomp($file_part);
 6217:         my $path_part = join('/', @paths_and_file);
 6218:         $path_part .= '/';
 6219:         my $path_and_file = $path_part.$file_part;
 6220:         if ($path_part ne $path) {
 6221:             push(@return_files, ($path_and_file));
 6222:         }
 6223:     }
 6224:     close(OUT);
 6225:     return (@return_files);
 6226: }
 6227: 
 6228: #----------------------------------------------Get portfolio file permissions
 6229: 
 6230: sub get_portfile_permissions {
 6231:     my ($domain,$user) = @_;
 6232:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6233:     my ($tmp)=keys(%current_permissions);
 6234:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6235:     return \%current_permissions;
 6236: }
 6237: 
 6238: #---------------------------------------------Get portfolio file access controls
 6239: 
 6240: sub get_access_controls {
 6241:     my ($current_permissions,$group,$file) = @_;
 6242:     my %access;
 6243:     my $real_file = $file;
 6244:     $file =~ s/\.meta$//;
 6245:     if (defined($file)) {
 6246:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 6247:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 6248:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 6249:             }
 6250:         }
 6251:     } else {
 6252:         foreach my $key (keys(%{$current_permissions})) {
 6253:             if ($key =~ /\0accesscontrol$/) {
 6254:                 if (defined($group)) {
 6255:                     if ($key !~ m-^\Q$group\E/-) {
 6256:                         next;
 6257:                     }
 6258:                 }
 6259:                 my ($fullpath) = split(/\0/,$key);
 6260:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 6261:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 6262:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 6263:                     }
 6264:                 }
 6265:             }
 6266:         }
 6267:     }
 6268:     return %access;
 6269: }
 6270: 
 6271: sub modify_access_controls {
 6272:     my ($file_name,$changes,$domain,$user)=@_;
 6273:     my ($outcome,$deloutcome);
 6274:     my %store_permissions;
 6275:     my %new_values;
 6276:     my %new_control;
 6277:     my %translation;
 6278:     my @deletions = ();
 6279:     my $now = time;
 6280:     if (exists($$changes{'activate'})) {
 6281:         if (ref($$changes{'activate'}) eq 'HASH') {
 6282:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 6283:             my $numnew = scalar(@newitems);
 6284:             for (my $i=0; $i<$numnew; $i++) {
 6285:                 my $newkey = $newitems[$i];
 6286:                 my $newid = &Apache::loncommon::get_cgi_id();
 6287:                 if ($newkey =~ /^\d+:/) { 
 6288:                     $newkey =~ s/^(\d+)/$newid/;
 6289:                     $translation{$1} = $newid;
 6290:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 6291:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 6292:                     $translation{$1} = $newid;
 6293:                 }
 6294:                 $new_values{$file_name."\0".$newkey} = 
 6295:                                           $$changes{'activate'}{$newitems[$i]};
 6296:                 $new_control{$newkey} = $now;
 6297:             }
 6298:         }
 6299:     }
 6300:     my %todelete;
 6301:     my %changed_items;
 6302:     foreach my $action ('delete','update') {
 6303:         if (exists($$changes{$action})) {
 6304:             if (ref($$changes{$action}) eq 'HASH') {
 6305:                 foreach my $key (keys(%{$$changes{$action}})) {
 6306:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 6307:                     if ($action eq 'delete') { 
 6308:                         $todelete{$itemnum} = 1;
 6309:                     } else {
 6310:                         $changed_items{$itemnum} = $key;
 6311:                     }
 6312:                 }
 6313:             }
 6314:         }
 6315:     }
 6316:     # get lock on access controls for file.
 6317:     my $lockhash = {
 6318:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 6319:                                                        ':'.$env{'user.domain'},
 6320:                    }; 
 6321:     my $tries = 0;
 6322:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6323:    
 6324:     while (($gotlock ne 'ok') && $tries <3) {
 6325:         $tries ++;
 6326:         sleep 1;
 6327:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6328:     }
 6329:     if ($gotlock eq 'ok') {
 6330:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 6331:         my ($tmp)=keys(%curr_permissions);
 6332:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 6333:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 6334:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 6335:             if (ref($curr_controls) eq 'HASH') {
 6336:                 foreach my $control_item (keys(%{$curr_controls})) {
 6337:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 6338:                     if (defined($todelete{$itemnum})) {
 6339:                         push(@deletions,$file_name."\0".$control_item);
 6340:                     } else {
 6341:                         if (defined($changed_items{$itemnum})) {
 6342:                             $new_control{$changed_items{$itemnum}} = $now;
 6343:                             push(@deletions,$file_name."\0".$control_item);
 6344:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 6345:                         } else {
 6346:                             $new_control{$control_item} = $$curr_controls{$control_item};
 6347:                         }
 6348:                     }
 6349:                 }
 6350:             }
 6351:         }
 6352:         my ($group);
 6353:         if (&is_course($domain,$user)) {
 6354:             ($group,my $file) = split(/\//,$file_name,2);
 6355:         }
 6356:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 6357:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 6358:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 6359:         #  remove lock
 6360:         my @del_lock = ($file_name."\0".'locked_access_records');
 6361:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 6362:         my $sqlresult =
 6363:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 6364:                                     $group);
 6365:     } else {
 6366:         $outcome = "error: could not obtain lockfile\n";  
 6367:     }
 6368:     return ($outcome,$deloutcome,\%new_values,\%translation);
 6369: }
 6370: 
 6371: sub make_public_indefinitely {
 6372:     my ($requrl) = @_;
 6373:     my $now = time;
 6374:     my $action = 'activate';
 6375:     my $aclnum = 0;
 6376:     if (&is_portfolio_url($requrl)) {
 6377:         my (undef,$udom,$unum,$file_name,$group) =
 6378:             &parse_portfolio_url($requrl);
 6379:         my $current_perms = &get_portfile_permissions($udom,$unum);
 6380:         my %access_controls = &get_access_controls($current_perms,
 6381:                                                    $group,$file_name);
 6382:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 6383:             my ($num,$scope,$end,$start) = 
 6384:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6385:             if ($scope eq 'public') {
 6386:                 if ($start <= $now && $end == 0) {
 6387:                     $action = 'none';
 6388:                 } else {
 6389:                     $action = 'update';
 6390:                     $aclnum = $num;
 6391:                 }
 6392:                 last;
 6393:             }
 6394:         }
 6395:         if ($action eq 'none') {
 6396:              return 'ok';
 6397:         } else {
 6398:             my %changes;
 6399:             my $newend = 0;
 6400:             my $newstart = $now;
 6401:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 6402:             $changes{$action}{$newkey} = {
 6403:                 type => 'public',
 6404:                 time => {
 6405:                     start => $newstart,
 6406:                     end   => $newend,
 6407:                 },
 6408:             };
 6409:             my ($outcome,$deloutcome,$new_values,$translation) =
 6410:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 6411:             return $outcome;
 6412:         }
 6413:     } else {
 6414:         return 'invalid';
 6415:     }
 6416: }
 6417: 
 6418: #------------------------------------------------------Get Marked as Read Only
 6419: 
 6420: sub get_marked_as_readonly {
 6421:     my ($domain,$user,$what,$group) = @_;
 6422:     my $current_permissions = &get_portfile_permissions($domain,$user);
 6423:     my @readonly_files;
 6424:     my $cmp1=$what;
 6425:     if (ref($what)) { $cmp1=join('',@{$what}) };
 6426:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6427:         if (defined($group)) {
 6428:             if ($file_name !~ m-^\Q$group\E/-) {
 6429:                 next;
 6430:             }
 6431:         }
 6432:         if (ref($value) eq "ARRAY"){
 6433:             foreach my $stored_what (@{$value}) {
 6434:                 my $cmp2=$stored_what;
 6435:                 if (ref($stored_what) eq 'ARRAY') {
 6436:                     $cmp2=join('',@{$stored_what});
 6437:                 }
 6438:                 if ($cmp1 eq $cmp2) {
 6439:                     push(@readonly_files, $file_name);
 6440:                     last;
 6441:                 } elsif (!defined($what)) {
 6442:                     push(@readonly_files, $file_name);
 6443:                     last;
 6444:                 }
 6445:             }
 6446:         }
 6447:     }
 6448:     return @readonly_files;
 6449: }
 6450: #-----------------------------------------------------------Get Marked as Read Only Hash
 6451: 
 6452: sub get_marked_as_readonly_hash {
 6453:     my ($current_permissions,$group,$what) = @_;
 6454:     my %readonly_files;
 6455:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6456:         if (defined($group)) {
 6457:             if ($file_name !~ m-^\Q$group\E/-) {
 6458:                 next;
 6459:             }
 6460:         }
 6461:         if (ref($value) eq "ARRAY"){
 6462:             foreach my $stored_what (@{$value}) {
 6463:                 if (ref($stored_what) eq 'ARRAY') {
 6464:                     foreach my $lock_descriptor(@{$stored_what}) {
 6465:                         if ($lock_descriptor eq 'graded') {
 6466:                             $readonly_files{$file_name} = 'graded';
 6467:                         } elsif ($lock_descriptor eq 'handback') {
 6468:                             $readonly_files{$file_name} = 'handback';
 6469:                         } else {
 6470:                             if (!exists($readonly_files{$file_name})) {
 6471:                                 $readonly_files{$file_name} = 'locked';
 6472:                             }
 6473:                         }
 6474:                     }
 6475:                 } 
 6476:             }
 6477:         } 
 6478:     }
 6479:     return %readonly_files;
 6480: }
 6481: # ------------------------------------------------------------ Unmark as Read Only
 6482: 
 6483: sub unmark_as_readonly {
 6484:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 6485:     # for portfolio submissions, $what contains [$symb,$crsid] 
 6486:     my ($domain,$user,$what,$file_name,$group) = @_;
 6487:     $file_name = &declutter_portfile($file_name);
 6488:     my $symb_crs = $what;
 6489:     if (ref($what)) { $symb_crs=join('',@$what); }
 6490:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 6491:     my ($tmp)=keys(%current_permissions);
 6492:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6493:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 6494:     foreach my $file (@readonly_files) {
 6495: 	my $clean_file = &declutter_portfile($file);
 6496: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 6497: 	my $current_locks = $current_permissions{$file};
 6498:         my @new_locks;
 6499:         my @del_keys;
 6500:         if (ref($current_locks) eq "ARRAY"){
 6501:             foreach my $locker (@{$current_locks}) {
 6502:                 my $compare=$locker;
 6503:                 if (ref($locker) eq 'ARRAY') {
 6504:                     $compare=join('',@{$locker});
 6505:                     if ($compare ne $symb_crs) {
 6506:                         push(@new_locks, $locker);
 6507:                     }
 6508:                 }
 6509:             }
 6510:             if (scalar(@new_locks) > 0) {
 6511:                 $current_permissions{$file} = \@new_locks;
 6512:             } else {
 6513:                 push(@del_keys, $file);
 6514:                 &del('file_permissions',\@del_keys, $domain, $user);
 6515:                 delete($current_permissions{$file});
 6516:             }
 6517:         }
 6518:     }
 6519:     &put('file_permissions',\%current_permissions,$domain,$user);
 6520:     return;
 6521: }
 6522: 
 6523: # ------------------------------------------------------------ Directory lister
 6524: 
 6525: sub dirlist {
 6526:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 6527:     $uri=~s/^\///;
 6528:     $uri=~s/\/$//;
 6529:     my ($udom, $uname);
 6530:     if ($getuserdir) {
 6531:         $udom = $userdomain;
 6532:         $uname = $username;
 6533:     } else {
 6534:         (undef,$udom,$uname)=split(/\//,$uri);
 6535:         if(defined($userdomain)) {
 6536:             $udom = $userdomain;
 6537:         }
 6538:         if(defined($username)) {
 6539:             $uname = $username;
 6540:         }
 6541:     }
 6542:     my ($dirRoot,$listing,@listing_results);
 6543: 
 6544:     $dirRoot = $perlvar{'lonDocRoot'};
 6545:     if (defined($getpropath)) {
 6546:         $dirRoot = &propath($udom,$uname);
 6547:         $dirRoot =~ s/\/$//;
 6548:     } elsif (defined($getuserdir)) {
 6549:         my $subdir=$uname.'__';
 6550:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 6551:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 6552:                    ."/$udom/$subdir/$uname";
 6553:     } elsif (defined($alternateRoot)) {
 6554:         $dirRoot = $alternateRoot;
 6555:     }
 6556: 
 6557:     if($udom) {
 6558:         if($uname) {
 6559:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 6560:                               .$getuserdir.':'.&escape($dirRoot)
 6561:                               .':'.&escape($uname).':'.&escape($udom),
 6562:                               &homeserver($uname,$udom));
 6563:             if ($listing eq 'unknown_cmd') {
 6564:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 6565:                                   &homeserver($uname,$udom));
 6566:             } else {
 6567:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6568:             }
 6569:             if ($listing eq 'unknown_cmd') {
 6570:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 6571: 				  &homeserver($uname,$udom));
 6572:                 @listing_results = split(/:/,$listing);
 6573:             } else {
 6574:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6575:             }
 6576:             return @listing_results;
 6577:         } elsif(!$alternateRoot) {
 6578:             my %allusers;
 6579: 	    my %servers = &get_servers($udom,'library');
 6580:  	    foreach my $tryserver (keys(%servers)) {
 6581:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 6582:                                   &escape($udom),$tryserver);
 6583:                 if ($listing eq 'unknown_cmd') {
 6584: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 6585: 				      $udom, $tryserver);
 6586:                 } else {
 6587:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 6588:                 }
 6589: 		if ($listing eq 'unknown_cmd') {
 6590: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 6591: 				      $udom, $tryserver);
 6592: 		    @listing_results = split(/:/,$listing);
 6593: 		} else {
 6594: 		    @listing_results =
 6595: 			map { &unescape($_); } split(/:/,$listing);
 6596: 		}
 6597: 		if ($listing_results[0] ne 'no_such_dir' && 
 6598: 		    $listing_results[0] ne 'empty'       &&
 6599: 		    $listing_results[0] ne 'con_lost') {
 6600: 		    foreach my $line (@listing_results) {
 6601: 			my ($entry) = split(/&/,$line,2);
 6602: 			$allusers{$entry} = 1;
 6603: 		    }
 6604: 		}
 6605:             }
 6606:             my $alluserstr='';
 6607:             foreach my $user (sort(keys(%allusers))) {
 6608:                 $alluserstr.=$user.'&user:';
 6609:             }
 6610:             $alluserstr=~s/:$//;
 6611:             return split(/:/,$alluserstr);
 6612:         } else {
 6613:             return ('missing user name');
 6614:         }
 6615:     } elsif(!defined($getpropath)) {
 6616:         my @all_domains = sort(&all_domains());
 6617:         foreach my $domain (@all_domains) {
 6618:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 6619:         }
 6620:         return @all_domains;
 6621:     } else {
 6622:         return ('missing domain');
 6623:     }
 6624: }
 6625: 
 6626: # --------------------------------------------- GetFileTimestamp
 6627: # This function utilizes dirlist and returns the date stamp for
 6628: # when it was last modified.  It will also return an error of -1
 6629: # if an error occurs
 6630: 
 6631: sub GetFileTimestamp {
 6632:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 6633:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 6634:     $studentName   = &LONCAPA::clean_username($studentName);
 6635:     my ($fileStat) = 
 6636:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
 6637:                                  undef,$getuserdir);
 6638:     my @stats = split('&', $fileStat);
 6639:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6640:         # @stats contains first the filename, then the stat output
 6641:         return $stats[10]; # so this is 10 instead of 9.
 6642:     } else {
 6643:         return -1;
 6644:     }
 6645: }
 6646: 
 6647: sub stat_file {
 6648:     my ($uri) = @_;
 6649:     $uri = &clutter_with_no_wrapper($uri);
 6650: 
 6651:     my ($udom,$uname,$file);
 6652:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 6653: 	($udom,$uname,$file) =
 6654: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 6655: 	$file = 'userfiles/'.$file;
 6656:     }
 6657:     if ($uri =~ m-^/res/-) {
 6658: 	($udom,$uname) = 
 6659: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 6660: 	$file = $uri;
 6661:     }
 6662: 
 6663:     if (!$udom || !$uname || !$file) {
 6664: 	# unable to handle the uri
 6665: 	return ();
 6666:     }
 6667:     my $getpropath;
 6668:     if ($file =~ /^userfiles\//) {
 6669:         $getpropath = 1;
 6670:     }
 6671:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
 6672:     my @stats = split('&', $result);
 6673:     
 6674:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6675: 	shift(@stats); #filename is first
 6676: 	return @stats;
 6677:     }
 6678:     return ();
 6679: }
 6680: 
 6681: # -------------------------------------------------------- Value of a Condition
 6682: 
 6683: # gets the value of a specific preevaluated condition
 6684: #    stored in the string  $env{user.state.<cid>}
 6685: # or looks up a condition reference in the bighash and if if hasn't
 6686: # already been evaluated recurses into docondval to get the value of
 6687: # the condition, then memoizing it to 
 6688: #   $env{user.state.<cid>.<condition>}
 6689: sub directcondval {
 6690:     my $number=shift;
 6691:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 6692: 	&Apache::lonuserstate::evalstate();
 6693:     }
 6694:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 6695: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 6696:     } elsif ($number =~ /^_/) {
 6697: 	my $sub_condition;
 6698: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6699: 		&GDBM_READER(),0640)) {
 6700: 	    $sub_condition=$bighash{'conditions'.$number};
 6701: 	    untie(%bighash);
 6702: 	}
 6703: 	my $value = &docondval($sub_condition);
 6704: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 6705: 	return $value;
 6706:     }
 6707:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 6708:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 6709:     } else {
 6710:        return 2;
 6711:     }
 6712: }
 6713: 
 6714: # get the collection of conditions for this resource
 6715: sub condval {
 6716:     my $condidx=shift;
 6717:     my $allpathcond='';
 6718:     foreach my $cond (split(/\|/,$condidx)) {
 6719: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 6720: 	    $allpathcond.=
 6721: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 6722: 	}
 6723:     }
 6724:     $allpathcond=~s/\|$//;
 6725:     return &docondval($allpathcond);
 6726: }
 6727: 
 6728: #evaluates an expression of conditions
 6729: sub docondval {
 6730:     my ($allpathcond) = @_;
 6731:     my $result=0;
 6732:     if ($env{'request.course.id'}
 6733: 	&& defined($allpathcond)) {
 6734: 	my $operand='|';
 6735: 	my @stack;
 6736: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 6737: 	    if ($chunk eq '(') {
 6738: 		push @stack,($operand,$result);
 6739: 	    } elsif ($chunk eq ')') {
 6740: 		my $before=pop @stack;
 6741: 		if (pop @stack eq '&') {
 6742: 		    $result=$result>$before?$before:$result;
 6743: 		} else {
 6744: 		    $result=$result>$before?$result:$before;
 6745: 		}
 6746: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 6747: 		$operand=$chunk;
 6748: 	    } else {
 6749: 		my $new=directcondval($chunk);
 6750: 		if ($operand eq '&') {
 6751: 		    $result=$result>$new?$new:$result;
 6752: 		} else {
 6753: 		    $result=$result>$new?$result:$new;
 6754: 		}
 6755: 	    }
 6756: 	}
 6757:     }
 6758:     return $result;
 6759: }
 6760: 
 6761: # ---------------------------------------------------- Devalidate courseresdata
 6762: 
 6763: sub devalidatecourseresdata {
 6764:     my ($coursenum,$coursedomain)=@_;
 6765:     my $hashid=$coursenum.':'.$coursedomain;
 6766:     &devalidate_cache_new('courseres',$hashid);
 6767: }
 6768: 
 6769: 
 6770: # --------------------------------------------------- Course Resourcedata Query
 6771: #
 6772: #  Parameters:
 6773: #      $coursenum    - Number of the course.
 6774: #      $coursedomain - Domain at which the course was created.
 6775: #  Returns:
 6776: #     A hash of the course parameters along (I think) with timestamps
 6777: #     and version info.
 6778: 
 6779: sub get_courseresdata {
 6780:     my ($coursenum,$coursedomain)=@_;
 6781:     my $coursehom=&homeserver($coursenum,$coursedomain);
 6782:     my $hashid=$coursenum.':'.$coursedomain;
 6783:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 6784:     my %dumpreply;
 6785:     unless (defined($cached)) {
 6786: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 6787: 	$result=\%dumpreply;
 6788: 	my ($tmp) = keys(%dumpreply);
 6789: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6790: 	    &do_cache_new('courseres',$hashid,$result,600);
 6791: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 6792: 	    return $tmp;
 6793: 	} elsif ($tmp =~ /^(error)/) {
 6794: 	    $result=undef;
 6795: 	    &do_cache_new('courseres',$hashid,$result,600);
 6796: 	}
 6797:     }
 6798:     return $result;
 6799: }
 6800: 
 6801: sub devalidateuserresdata {
 6802:     my ($uname,$udom)=@_;
 6803:     my $hashid="$udom:$uname";
 6804:     &devalidate_cache_new('userres',$hashid);
 6805: }
 6806: 
 6807: sub get_userresdata {
 6808:     my ($uname,$udom)=@_;
 6809:     #most student don\'t have any data set, check if there is some data
 6810:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 6811: 
 6812:     my $hashid="$udom:$uname";
 6813:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 6814:     if (!defined($cached)) {
 6815: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 6816: 	$result=\%resourcedata;
 6817: 	&do_cache_new('userres',$hashid,$result,600);
 6818:     }
 6819:     my ($tmp)=keys(%$result);
 6820:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 6821: 	return $result;
 6822:     }
 6823:     #error 2 occurs when the .db doesn't exist
 6824:     if ($tmp!~/error: 2 /) {
 6825: 	&logthis("<font color=\"blue\">WARNING:".
 6826: 		 " Trying to get resource data for ".
 6827: 		 $uname." at ".$udom.": ".
 6828: 		 $tmp."</font>");
 6829:     } elsif ($tmp=~/error: 2 /) {
 6830: 	#&EXT_cache_set($udom,$uname);
 6831: 	&do_cache_new('userres',$hashid,undef,600);
 6832: 	undef($tmp); # not really an error so don't send it back
 6833:     }
 6834:     return $tmp;
 6835: }
 6836: #----------------------------------------------- resdata - return resource data
 6837: #  Purpose:
 6838: #    Return resource data for either users or for a course.
 6839: #  Parameters:
 6840: #     $name      - Course/user name.
 6841: #     $domain    - Name of the domain the user/course is registered on.
 6842: #     $type      - Type of thing $name is (must be 'course' or 'user'
 6843: #     @which     - Array of names of resources desired.
 6844: #  Returns:
 6845: #     The value of the first reasource in @which that is found in the
 6846: #     resource hash.
 6847: #  Exceptional Conditions:
 6848: #     If the $type passed in is not valid (not the string 'course' or 
 6849: #     'user', an undefined  reference is returned.
 6850: #     If none of the resources are found, an undef is returned
 6851: sub resdata {
 6852:     my ($name,$domain,$type,@which)=@_;
 6853:     my $result;
 6854:     if ($type eq 'course') {
 6855: 	$result=&get_courseresdata($name,$domain);
 6856:     } elsif ($type eq 'user') {
 6857: 	$result=&get_userresdata($name,$domain);
 6858:     }
 6859:     if (!ref($result)) { return $result; }    
 6860:     foreach my $item (@which) {
 6861: 	if (defined($result->{$item->[0]})) {
 6862: 	    return [$result->{$item->[0]},$item->[1]];
 6863: 	}
 6864:     }
 6865:     return undef;
 6866: }
 6867: 
 6868: #
 6869: # EXT resource caching routines
 6870: #
 6871: 
 6872: sub clear_EXT_cache_status {
 6873:     &delenv('cache.EXT.');
 6874: }
 6875: 
 6876: sub EXT_cache_status {
 6877:     my ($target_domain,$target_user) = @_;
 6878:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6879:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 6880:         # We know already the user has no data
 6881:         return 1;
 6882:     } else {
 6883:         return 0;
 6884:     }
 6885: }
 6886: 
 6887: sub EXT_cache_set {
 6888:     my ($target_domain,$target_user) = @_;
 6889:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6890:     #&appenv({$cachename => time});
 6891: }
 6892: 
 6893: # --------------------------------------------------------- Value of a Variable
 6894: sub EXT {
 6895: 
 6896:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 6897:     unless ($varname) { return ''; }
 6898:     #get real user name/domain, courseid and symb
 6899:     my $courseid;
 6900:     my $publicuser;
 6901:     if ($symbparm) {
 6902: 	$symbparm=&get_symb_from_alias($symbparm);
 6903:     }
 6904:     if (!($uname && $udom)) {
 6905:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 6906:       if (!$symbparm) {	$symbparm=$cursymb; }
 6907:     } else {
 6908: 	$courseid=$env{'request.course.id'};
 6909:     }
 6910:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 6911:     my $rest;
 6912:     if (defined($therest[0])) {
 6913:        $rest=join('.',@therest);
 6914:     } else {
 6915:        $rest='';
 6916:     }
 6917: 
 6918:     my $qualifierrest=$qualifier;
 6919:     if ($rest) { $qualifierrest.='.'.$rest; }
 6920:     my $spacequalifierrest=$space;
 6921:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 6922:     if ($realm eq 'user') {
 6923: # --------------------------------------------------------------- user.resource
 6924: 	if ($space eq 'resource') {
 6925: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 6926: 		  || defined($Apache::lonhomework::parsing_a_task))
 6927: 		 &&
 6928: 		 ($symbparm eq &symbread()) ) {	
 6929: 		# if we are in the middle of processing the resource the
 6930: 		# get the value we are planning on committing
 6931:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 6932:                     return $Apache::lonhomework::results{$qualifierrest};
 6933:                 } else {
 6934:                     return $Apache::lonhomework::history{$qualifierrest};
 6935:                 }
 6936: 	    } else {
 6937: 		my %restored;
 6938: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 6939: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 6940: 		} else {
 6941: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 6942: 		}
 6943: 		return $restored{$qualifierrest};
 6944: 	    }
 6945: # ----------------------------------------------------------------- user.access
 6946:         } elsif ($space eq 'access') {
 6947: 	    # FIXME - not supporting calls for a specific user
 6948:             return &allowed($qualifier,$rest);
 6949: # ------------------------------------------ user.preferences, user.environment
 6950:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 6951: 	    if (($uname eq $env{'user.name'}) &&
 6952: 		($udom eq $env{'user.domain'})) {
 6953: 		return $env{join('.',('environment',$qualifierrest))};
 6954: 	    } else {
 6955: 		my %returnhash;
 6956: 		if (!$publicuser) {
 6957: 		    %returnhash=&userenvironment($udom,$uname,
 6958: 						 $qualifierrest);
 6959: 		}
 6960: 		return $returnhash{$qualifierrest};
 6961: 	    }
 6962: # ----------------------------------------------------------------- user.course
 6963:         } elsif ($space eq 'course') {
 6964: 	    # FIXME - not supporting calls for a specific user
 6965:             return $env{join('.',('request.course',$qualifier))};
 6966: # ------------------------------------------------------------------- user.role
 6967:         } elsif ($space eq 'role') {
 6968: 	    # FIXME - not supporting calls for a specific user
 6969:             my ($role,$where)=split(/\./,$env{'request.role'});
 6970:             if ($qualifier eq 'value') {
 6971: 		return $role;
 6972:             } elsif ($qualifier eq 'extent') {
 6973:                 return $where;
 6974:             }
 6975: # ----------------------------------------------------------------- user.domain
 6976:         } elsif ($space eq 'domain') {
 6977:             return $udom;
 6978: # ------------------------------------------------------------------- user.name
 6979:         } elsif ($space eq 'name') {
 6980:             return $uname;
 6981: # ---------------------------------------------------- Any other user namespace
 6982:         } else {
 6983: 	    my %reply;
 6984: 	    if (!$publicuser) {
 6985: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 6986: 	    }
 6987: 	    return $reply{$qualifierrest};
 6988:         }
 6989:     } elsif ($realm eq 'query') {
 6990: # ---------------------------------------------- pull stuff out of query string
 6991:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 6992: 						[$spacequalifierrest]);
 6993: 	return $env{'form.'.$spacequalifierrest}; 
 6994:    } elsif ($realm eq 'request') {
 6995: # ------------------------------------------------------------- request.browser
 6996:         if ($space eq 'browser') {
 6997: 	    if ($qualifier eq 'textremote') {
 6998: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 6999: 		    return 1;
 7000: 		} else {
 7001: 		    return 0;
 7002: 		}
 7003: 	    } else {
 7004: 		return $env{'browser.'.$qualifier};
 7005: 	    }
 7006: # ------------------------------------------------------------ request.filename
 7007:         } else {
 7008:             return $env{'request.'.$spacequalifierrest};
 7009:         }
 7010:     } elsif ($realm eq 'course') {
 7011: # ---------------------------------------------------------- course.description
 7012:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 7013:     } elsif ($realm eq 'resource') {
 7014: 
 7015: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 7016: 	    if (!$symbparm) { $symbparm=&symbread(); }
 7017: 	}
 7018: 
 7019: 	if ($space eq 'title') {
 7020: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 7021: 	    return &gettitle($symbparm);
 7022: 	}
 7023: 	
 7024: 	if ($space eq 'map') {
 7025: 	    my ($map) = &decode_symb($symbparm);
 7026: 	    return &symbread($map);
 7027: 	}
 7028: 	if ($space eq 'filename') {
 7029: 	    if ($symbparm) {
 7030: 		return &clutter((&decode_symb($symbparm))[2]);
 7031: 	    }
 7032: 	    return &hreflocation('',$env{'request.filename'});
 7033: 	}
 7034: 
 7035: 	my ($section, $group, @groups);
 7036: 	my ($courselevelm,$courselevel);
 7037: 	if ($symbparm && defined($courseid) && 
 7038: 	    $courseid eq $env{'request.course.id'}) {
 7039: 
 7040: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 7041: 
 7042: # ----------------------------------------------------- Cascading lookup scheme
 7043: 	    my $symbp=$symbparm;
 7044: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 7045: 
 7046: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 7047: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 7048: 
 7049: 	    if (($env{'user.name'} eq $uname) &&
 7050: 		($env{'user.domain'} eq $udom)) {
 7051: 		$section=$env{'request.course.sec'};
 7052:                 @groups = split(/:/,$env{'request.course.groups'});  
 7053:                 @groups=&sort_course_groups($courseid,@groups); 
 7054: 	    } else {
 7055: 		if (! defined($usection)) {
 7056: 		    $section=&getsection($udom,$uname,$courseid);
 7057: 		} else {
 7058: 		    $section = $usection;
 7059: 		}
 7060:                 @groups = &get_users_groups($udom,$uname,$courseid);
 7061: 	    }
 7062: 
 7063: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 7064: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 7065: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 7066: 
 7067: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 7068: 	    my $courselevelr=$courseid.'.'.$symbparm;
 7069: 	    $courselevelm=$courseid.'.'.$mapparm;
 7070: 
 7071: # ----------------------------------------------------------- first, check user
 7072: 
 7073: 	    my $userreply=&resdata($uname,$udom,'user',
 7074: 				       ([$courselevelr,'resource'],
 7075: 					[$courselevelm,'map'     ],
 7076: 					[$courselevel, 'course'  ]));
 7077: 	    if (defined($userreply)) { return &get_reply($userreply); }
 7078: 
 7079: # ------------------------------------------------ second, check some of course
 7080:             my $coursereply;
 7081:             if (@groups > 0) {
 7082:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 7083:                                        $mapparm,$spacequalifierrest);
 7084:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 7085:             }
 7086: 
 7087: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7088: 				  $env{'course.'.$courseid.'.domain'},
 7089: 				  'course',
 7090: 				  ([$seclevelr,   'resource'],
 7091: 				   [$seclevelm,   'map'     ],
 7092: 				   [$seclevel,    'course'  ],
 7093: 				   [$courselevelr,'resource']));
 7094: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7095: 
 7096: # ------------------------------------------------------ third, check map parms
 7097: 	    my %parmhash=();
 7098: 	    my $thisparm='';
 7099: 	    if (tie(%parmhash,'GDBM_File',
 7100: 		    $env{'request.course.fn'}.'_parms.db',
 7101: 		    &GDBM_READER(),0640)) {
 7102: 		$thisparm=$parmhash{$symbparm};
 7103: 		untie(%parmhash);
 7104: 	    }
 7105: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 7106: 	}
 7107: # ------------------------------------------ fourth, look in resource metadata
 7108: 
 7109: 	$spacequalifierrest=~s/\./\_/;
 7110: 	my $filename;
 7111: 	if (!$symbparm) { $symbparm=&symbread(); }
 7112: 	if ($symbparm) {
 7113: 	    $filename=(&decode_symb($symbparm))[2];
 7114: 	} else {
 7115: 	    $filename=$env{'request.filename'};
 7116: 	}
 7117: 	my $metadata=&metadata($filename,$spacequalifierrest);
 7118: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7119: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 7120: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7121: 
 7122: # ---------------------------------------------- fourth, look in rest of course
 7123: 	if ($symbparm && defined($courseid) && 
 7124: 	    $courseid eq $env{'request.course.id'}) {
 7125: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7126: 				     $env{'course.'.$courseid.'.domain'},
 7127: 				     'course',
 7128: 				     ([$courselevelm,'map'   ],
 7129: 				      [$courselevel, 'course']));
 7130: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7131: 	}
 7132: # ------------------------------------------------------------------ Cascade up
 7133: 	unless ($space eq '0') {
 7134: 	    my @parts=split(/_/,$space);
 7135: 	    my $id=pop(@parts);
 7136: 	    my $part=join('_',@parts);
 7137: 	    if ($part eq '') { $part='0'; }
 7138: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 7139: 				 $symbparm,$udom,$uname,$section,1);
 7140: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 7141: 	}
 7142: 	if ($recurse) { return undef; }
 7143: 	my $pack_def=&packages_tab_default($filename,$varname);
 7144: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 7145: # ---------------------------------------------------- Any other user namespace
 7146:     } elsif ($realm eq 'environment') {
 7147: # ----------------------------------------------------------------- environment
 7148: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 7149: 	    return $env{'environment.'.$spacequalifierrest};
 7150: 	} else {
 7151: 	    if ($uname eq 'anonymous' && $udom eq '') {
 7152: 		return '';
 7153: 	    }
 7154: 	    my %returnhash=&userenvironment($udom,$uname,
 7155: 					    $spacequalifierrest);
 7156: 	    return $returnhash{$spacequalifierrest};
 7157: 	}
 7158:     } elsif ($realm eq 'system') {
 7159: # ----------------------------------------------------------------- system.time
 7160: 	if ($space eq 'time') {
 7161: 	    return time;
 7162:         }
 7163:     } elsif ($realm eq 'server') {
 7164: # ----------------------------------------------------------------- system.time
 7165: 	if ($space eq 'name') {
 7166: 	    return $ENV{'SERVER_NAME'};
 7167:         }
 7168:     }
 7169:     return '';
 7170: }
 7171: 
 7172: sub get_reply {
 7173:     my ($reply_value) = @_;
 7174:     if (ref($reply_value) eq 'ARRAY') {
 7175:         if (wantarray) {
 7176: 	    return @$reply_value;
 7177:         }
 7178:         return $reply_value->[0];
 7179:     } else {
 7180:         return $reply_value;
 7181:     }
 7182: }
 7183: 
 7184: sub check_group_parms {
 7185:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 7186:     my @groupitems = ();
 7187:     my $resultitem;
 7188:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 7189:     foreach my $group (@{$groups}) {
 7190:         foreach my $level (@levels) {
 7191:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 7192:              push(@groupitems,[$item,$level->[1]]);
 7193:         }
 7194:     }
 7195:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 7196:                             $env{'course.'.$courseid.'.domain'},
 7197:                                      'course',@groupitems);
 7198:     return $coursereply;
 7199: }
 7200: 
 7201: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 7202:     my ($courseid,@groups) = @_;
 7203:     @groups = sort(@groups);
 7204:     return @groups;
 7205: }
 7206: 
 7207: sub packages_tab_default {
 7208:     my ($uri,$varname)=@_;
 7209:     my (undef,$part,$name)=split(/\./,$varname);
 7210: 
 7211:     my (@extension,@specifics,$do_default);
 7212:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 7213: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 7214: 	if ($pack_type eq 'default') {
 7215: 	    $do_default=1;
 7216: 	} elsif ($pack_type eq 'extension') {
 7217: 	    push(@extension,[$package,$pack_type,$pack_part]);
 7218: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 7219: 	    # only look at packages defaults for packages that this id is
 7220: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 7221: 	}
 7222:     }
 7223:     # first look for a package that matches the requested part id
 7224:     foreach my $package (@specifics) {
 7225: 	my (undef,$pack_type,$pack_part)=@{$package};
 7226: 	next if ($pack_part ne $part);
 7227: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7228: 	    return $packagetab{"$pack_type&$name&default"};
 7229: 	}
 7230:     }
 7231:     # look for any possible matching non extension_ package
 7232:     foreach my $package (@specifics) {
 7233: 	my (undef,$pack_type,$pack_part)=@{$package};
 7234: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7235: 	    return $packagetab{"$pack_type&$name&default"};
 7236: 	}
 7237: 	if ($pack_type eq 'part') { $pack_part='0'; }
 7238: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 7239: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 7240: 	}
 7241:     }
 7242:     # look for any posible extension_ match
 7243:     foreach my $package (@extension) {
 7244: 	my ($package,$pack_type)=@{$package};
 7245: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7246: 	    return $packagetab{"$pack_type&$name&default"};
 7247: 	}
 7248: 	if (defined($packagetab{$package."&$name&default"})) {
 7249: 	    return $packagetab{$package."&$name&default"};
 7250: 	}
 7251:     }
 7252:     # look for a global default setting
 7253:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 7254: 	return $packagetab{"default&$name&default"};
 7255:     }
 7256:     return undef;
 7257: }
 7258: 
 7259: sub add_prefix_and_part {
 7260:     my ($prefix,$part)=@_;
 7261:     my $keyroot;
 7262:     if (defined($prefix) && $prefix !~ /^__/) {
 7263: 	# prefix that has a part already
 7264: 	$keyroot=$prefix;
 7265:     } elsif (defined($prefix)) {
 7266: 	# prefix that is missing a part
 7267: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 7268:     } else {
 7269: 	# no prefix at all
 7270: 	if (defined($part)) { $keyroot='_'.$part; }
 7271:     }
 7272:     return $keyroot;
 7273: }
 7274: 
 7275: # ---------------------------------------------------------------- Get metadata
 7276: 
 7277: my %metaentry;
 7278: sub metadata {
 7279:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 7280:     $uri=&declutter($uri);
 7281:     # if it is a non metadata possible uri return quickly
 7282:     if (($uri eq '') || 
 7283: 	(($uri =~ m|^/*adm/|) && 
 7284: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 7285:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 7286: 	return undef;
 7287:     }
 7288:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 7289: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 7290: 	return undef;
 7291:     }
 7292:     my $filename=$uri;
 7293:     $uri=~s/\.meta$//;
 7294: #
 7295: # Is the metadata already cached?
 7296: # Look at timestamp of caching
 7297: # Everything is cached by the main uri, libraries are never directly cached
 7298: #
 7299:     if (!defined($liburi)) {
 7300: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 7301: 	if (defined($cached)) { return $result->{':'.$what}; }
 7302:     }
 7303:     {
 7304: #
 7305: # Is this a recursive call for a library?
 7306: #
 7307: #	if (! exists($metacache{$uri})) {
 7308: #	    $metacache{$uri}={};
 7309: #	}
 7310: 	my $cachetime = 60*60;
 7311:         if ($liburi) {
 7312: 	    $liburi=&declutter($liburi);
 7313:             $filename=$liburi;
 7314:         } else {
 7315: 	    &devalidate_cache_new('meta',$uri);
 7316: 	    undef(%metaentry);
 7317: 	}
 7318:         my %metathesekeys=();
 7319:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 7320: 	my $metastring;
 7321: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 7322: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 7323: 	    $metastring = 
 7324: 		&Apache::lonnet::ssi_body($which,
 7325: 					  ('grade_target' => 'meta'));
 7326: 	    $cachetime = 1; # only want this cached in the child not long term
 7327: 	} elsif ($uri !~ m -^(editupload)/-) {
 7328: 	    my $file=&filelocation('',&clutter($filename));
 7329: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 7330: 	    $metastring=&getfile($file);
 7331: 	}
 7332:         my $parser=HTML::LCParser->new(\$metastring);
 7333:         my $token;
 7334:         undef %metathesekeys;
 7335:         while ($token=$parser->get_token) {
 7336: 	    if ($token->[0] eq 'S') {
 7337: 		if (defined($token->[2]->{'package'})) {
 7338: #
 7339: # This is a package - get package info
 7340: #
 7341: 		    my $package=$token->[2]->{'package'};
 7342: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7343: 		    if (defined($token->[2]->{'id'})) { 
 7344: 			$keyroot.='_'.$token->[2]->{'id'}; 
 7345: 		    }
 7346: 		    if ($metaentry{':packages'}) {
 7347: 			$metaentry{':packages'}.=','.$package.$keyroot;
 7348: 		    } else {
 7349: 			$metaentry{':packages'}=$package.$keyroot;
 7350: 		    }
 7351: 		    foreach my $pack_entry (keys(%packagetab)) {
 7352: 			my $part=$keyroot;
 7353: 			$part=~s/^\_//;
 7354: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 7355: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 7356: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 7357: 			    # ignore package.tab specified default values
 7358:                             # here &package_tab_default() will fetch those
 7359: 			    if ($subp eq 'default') { next; }
 7360: 			    my $value=$packagetab{$pack_entry};
 7361: 			    my $unikey;
 7362: 			    if ($pack =~ /_0$/) {
 7363: 				$unikey='parameter_0_'.$name;
 7364: 				$part=0;
 7365: 			    } else {
 7366: 				$unikey='parameter'.$keyroot.'_'.$name;
 7367: 			    }
 7368: 			    if ($subp eq 'display') {
 7369: 				$value.=' [Part: '.$part.']';
 7370: 			    }
 7371: 			    $metaentry{':'.$unikey.'.part'}=$part;
 7372: 			    $metathesekeys{$unikey}=1;
 7373: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7374: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 7375: 			    }
 7376: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 7377: 				$metaentry{':'.$unikey}=
 7378: 				    $metaentry{':'.$unikey.'.default'};
 7379: 			    }
 7380: 			}
 7381: 		    }
 7382: 		} else {
 7383: #
 7384: # This is not a package - some other kind of start tag
 7385: #
 7386: 		    my $entry=$token->[1];
 7387: 		    my $unikey;
 7388: 		    if ($entry eq 'import') {
 7389: 			$unikey='';
 7390: 		    } else {
 7391: 			$unikey=$entry;
 7392: 		    }
 7393: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7394: 
 7395: 		    if (defined($token->[2]->{'id'})) { 
 7396: 			$unikey.='_'.$token->[2]->{'id'}; 
 7397: 		    }
 7398: 
 7399: 		    if ($entry eq 'import') {
 7400: #
 7401: # Importing a library here
 7402: #
 7403: 			if ($depthcount<20) {
 7404: 			    my $location=$parser->get_text('/import');
 7405: 			    my $dir=$filename;
 7406: 			    $dir=~s|[^/]*$||;
 7407: 			    $location=&filelocation($dir,$location);
 7408: 			    my $metadata = 
 7409: 				&metadata($uri,'keys', $location,$unikey,
 7410: 					  $depthcount+1);
 7411: 			    foreach my $meta (split(',',$metadata)) {
 7412: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 7413: 				$metathesekeys{$meta}=1;
 7414: 			    }
 7415: 			}
 7416: 		    } else { 
 7417: 			
 7418: 			if (defined($token->[2]->{'name'})) { 
 7419: 			    $unikey.='_'.$token->[2]->{'name'}; 
 7420: 			}
 7421: 			$metathesekeys{$unikey}=1;
 7422: 			foreach my $param (@{$token->[3]}) {
 7423: 			    $metaentry{':'.$unikey.'.'.$param} =
 7424: 				$token->[2]->{$param};
 7425: 			}
 7426: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 7427: 			my $default=$metaentry{':'.$unikey.'.default'};
 7428: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 7429: 		 # only ws inside the tag, and not in default, so use default
 7430: 		 # as value
 7431: 			    $metaentry{':'.$unikey}=$default;
 7432: 			} elsif ( $internaltext =~ /\S/ ) {
 7433: 		  # something interesting inside the tag
 7434: 			    $metaentry{':'.$unikey}=$internaltext;
 7435: 			} else {
 7436: 		  # no interesting values, don't set a default
 7437: 			}
 7438: # end of not-a-package not-a-library import
 7439: 		    }
 7440: # end of not-a-package start tag
 7441: 		}
 7442: # the next is the end of "start tag"
 7443: 	    }
 7444: 	}
 7445: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 7446: 	$extension = lc($extension);
 7447: 	if ($extension eq 'htm') { $extension='html'; }
 7448: 
 7449: 	foreach my $key (keys(%packagetab)) {
 7450: 	    #no specific packages #how's our extension
 7451: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 7452: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 7453: 					 \%metathesekeys);
 7454: 	}
 7455: 
 7456: 	if (!exists($metaentry{':packages'})
 7457: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 7458: 	    foreach my $key (keys(%packagetab)) {
 7459: 		#no specific packages well let's get default then
 7460: 		if ($key!~/^default&/) { next; }
 7461: 		&metadata_create_package_def($uri,$key,'default',
 7462: 					     \%metathesekeys);
 7463: 	    }
 7464: 	}
 7465: # are there custom rights to evaluate
 7466: 	if ($metaentry{':copyright'} eq 'custom') {
 7467: 
 7468:     #
 7469:     # Importing a rights file here
 7470:     #
 7471: 	    unless ($depthcount) {
 7472: 		my $location=$metaentry{':customdistributionfile'};
 7473: 		my $dir=$filename;
 7474: 		$dir=~s|[^/]*$||;
 7475: 		$location=&filelocation($dir,$location);
 7476: 		my $rights_metadata =
 7477: 		    &metadata($uri,'keys',$location,'_rights',
 7478: 			      $depthcount+1);
 7479: 		foreach my $rights (split(',',$rights_metadata)) {
 7480: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 7481: 		    $metathesekeys{$rights}=1;
 7482: 		}
 7483: 	    }
 7484: 	}
 7485: 	# uniqifiy package listing
 7486: 	my %seen;
 7487: 	my @uniq_packages =
 7488: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 7489: 	$metaentry{':packages'} = join(',',@uniq_packages);
 7490: 
 7491: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 7492: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 7493: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 7494: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 7495: # this is the end of "was not already recently cached
 7496:     }
 7497:     return $metaentry{':'.$what};
 7498: }
 7499: 
 7500: sub metadata_create_package_def {
 7501:     my ($uri,$key,$package,$metathesekeys)=@_;
 7502:     my ($pack,$name,$subp)=split(/\&/,$key);
 7503:     if ($subp eq 'default') { next; }
 7504:     
 7505:     if (defined($metaentry{':packages'})) {
 7506: 	$metaentry{':packages'}.=','.$package;
 7507:     } else {
 7508: 	$metaentry{':packages'}=$package;
 7509:     }
 7510:     my $value=$packagetab{$key};
 7511:     my $unikey;
 7512:     $unikey='parameter_0_'.$name;
 7513:     $metaentry{':'.$unikey.'.part'}=0;
 7514:     $$metathesekeys{$unikey}=1;
 7515:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7516: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 7517:     }
 7518:     if (defined($metaentry{':'.$unikey.'.default'})) {
 7519: 	$metaentry{':'.$unikey}=
 7520: 	    $metaentry{':'.$unikey.'.default'};
 7521:     }
 7522: }
 7523: 
 7524: sub metadata_generate_part0 {
 7525:     my ($metadata,$metacache,$uri) = @_;
 7526:     my %allnames;
 7527:     foreach my $metakey (keys(%$metadata)) {
 7528: 	if ($metakey=~/^parameter\_(.*)/) {
 7529: 	  my $part=$$metacache{':'.$metakey.'.part'};
 7530: 	  my $name=$$metacache{':'.$metakey.'.name'};
 7531: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 7532: 	    $allnames{$name}=$part;
 7533: 	  }
 7534: 	}
 7535:     }
 7536:     foreach my $name (keys(%allnames)) {
 7537:       $$metadata{"parameter_0_$name"}=1;
 7538:       my $key=":parameter_0_$name";
 7539:       $$metacache{"$key.part"}='0';
 7540:       $$metacache{"$key.name"}=$name;
 7541:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 7542: 					   $allnames{$name}.'_'.$name.
 7543: 					   '.type'};
 7544:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 7545: 			     '.display'};
 7546:       my $expr='[Part: '.$allnames{$name}.']';
 7547:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 7548:       $$metacache{"$key.display"}=$olddis;
 7549:     }
 7550: }
 7551: 
 7552: # ------------------------------------------------------ Devalidate title cache
 7553: 
 7554: sub devalidate_title_cache {
 7555:     my ($url)=@_;
 7556:     if (!$env{'request.course.id'}) { return; }
 7557:     my $symb=&symbread($url);
 7558:     if (!$symb) { return; }
 7559:     my $key=$env{'request.course.id'}."\0".$symb;
 7560:     &devalidate_cache_new('title',$key);
 7561: }
 7562: 
 7563: # ------------------------------------------------- Get the title of a resource
 7564: 
 7565: sub gettitle {
 7566:     my $urlsymb=shift;
 7567:     my $symb=&symbread($urlsymb);
 7568:     if ($symb) {
 7569: 	my $key=$env{'request.course.id'}."\0".$symb;
 7570: 	my ($result,$cached)=&is_cached_new('title',$key);
 7571: 	if (defined($cached)) { 
 7572: 	    return $result;
 7573: 	}
 7574: 	my ($map,$resid,$url)=&decode_symb($symb);
 7575: 	my $title='';
 7576: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 7577: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 7578: 	} else {
 7579: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7580: 		    &GDBM_READER(),0640)) {
 7581: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 7582: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 7583: 		untie(%bighash);
 7584: 	    }
 7585: 	}
 7586: 	$title=~s/\&colon\;/\:/gs;
 7587: 	if ($title) {
 7588: 	    return &do_cache_new('title',$key,$title,600);
 7589: 	}
 7590: 	$urlsymb=$url;
 7591:     }
 7592:     my $title=&metadata($urlsymb,'title');
 7593:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 7594:     return $title;
 7595: }
 7596: 
 7597: sub get_slot {
 7598:     my ($which,$cnum,$cdom)=@_;
 7599:     if (!$cnum || !$cdom) {
 7600: 	(undef,my $courseid)=&whichuser();
 7601: 	$cdom=$env{'course.'.$courseid.'.domain'};
 7602: 	$cnum=$env{'course.'.$courseid.'.num'};
 7603:     }
 7604:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 7605:     my %slotinfo;
 7606:     if (exists($remembered{$key})) {
 7607: 	$slotinfo{$which} = $remembered{$key};
 7608:     } else {
 7609: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 7610: 	&Apache::lonhomework::showhash(%slotinfo);
 7611: 	my ($tmp)=keys(%slotinfo);
 7612: 	if ($tmp=~/^error:/) { return (); }
 7613: 	$remembered{$key} = $slotinfo{$which};
 7614:     }
 7615:     if (ref($slotinfo{$which}) eq 'HASH') {
 7616: 	return %{$slotinfo{$which}};
 7617:     }
 7618:     return $slotinfo{$which};
 7619: }
 7620: # ------------------------------------------------- Update symbolic store links
 7621: 
 7622: sub symblist {
 7623:     my ($mapname,%newhash)=@_;
 7624:     $mapname=&deversion(&declutter($mapname));
 7625:     my %hash;
 7626:     if (($env{'request.course.fn'}) && (%newhash)) {
 7627:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7628:                       &GDBM_WRCREAT(),0640)) {
 7629: 	    foreach my $url (keys %newhash) {
 7630: 		next if ($url eq 'last_known'
 7631: 			 && $env{'form.no_update_last_known'});
 7632: 		$hash{declutter($url)}=&encode_symb($mapname,
 7633: 						    $newhash{$url}->[1],
 7634: 						    $newhash{$url}->[0]);
 7635:             }
 7636:             if (untie(%hash)) {
 7637: 		return 'ok';
 7638:             }
 7639:         }
 7640:     }
 7641:     return 'error';
 7642: }
 7643: 
 7644: # --------------------------------------------------------------- Verify a symb
 7645: 
 7646: sub symbverify {
 7647:     my ($symb,$thisurl)=@_;
 7648:     my $thisfn=$thisurl;
 7649:     $thisfn=&declutter($thisfn);
 7650: # direct jump to resource in page or to a sequence - will construct own symbs
 7651:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 7652: # check URL part
 7653:     my ($map,$resid,$url)=&decode_symb($symb);
 7654: 
 7655:     unless ($url eq $thisfn) { return 0; }
 7656: 
 7657:     $symb=&symbclean($symb);
 7658:     $thisurl=&deversion($thisurl);
 7659:     $thisfn=&deversion($thisfn);
 7660: 
 7661:     my %bighash;
 7662:     my $okay=0;
 7663: 
 7664:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7665:                             &GDBM_READER(),0640)) {
 7666:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 7667:         unless ($ids) { 
 7668:            $ids=$bighash{'ids_/'.$thisurl};
 7669:         }
 7670:         if ($ids) {
 7671: # ------------------------------------------------------------------- Has ID(s)
 7672: 	    foreach my $id (split(/\,/,$ids)) {
 7673: 	       my ($mapid,$resid)=split(/\./,$id);
 7674:                if (
 7675:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 7676:    eq $symb) { 
 7677: 		   if (($env{'request.role.adv'}) ||
 7678: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 7679: 		       $okay=1; 
 7680: 		   }
 7681: 	       }
 7682: 	   }
 7683:         }
 7684: 	untie(%bighash);
 7685:     }
 7686:     return $okay;
 7687: }
 7688: 
 7689: # --------------------------------------------------------------- Clean-up symb
 7690: 
 7691: sub symbclean {
 7692:     my $symb=shift;
 7693:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7694: # remove version from map
 7695:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 7696: 
 7697: # remove version from URL
 7698:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 7699: 
 7700: # remove wrapper
 7701: 
 7702:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 7703:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 7704:     return $symb;
 7705: }
 7706: 
 7707: # ---------------------------------------------- Split symb to find map and url
 7708: 
 7709: sub encode_symb {
 7710:     my ($map,$resid,$url)=@_;
 7711:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 7712: }
 7713: 
 7714: sub decode_symb {
 7715:     my $symb=shift;
 7716:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7717:     my ($map,$resid,$url)=split(/___/,$symb);
 7718:     return (&fixversion($map),$resid,&fixversion($url));
 7719: }
 7720: 
 7721: sub fixversion {
 7722:     my $fn=shift;
 7723:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 7724:     my %bighash;
 7725:     my $uri=&clutter($fn);
 7726:     my $key=$env{'request.course.id'}.'_'.$uri;
 7727: # is this cached?
 7728:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 7729:     if (defined($cached)) { return $result; }
 7730: # unfortunately not cached, or expired
 7731:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7732: 	    &GDBM_READER(),0640)) {
 7733:  	if ($bighash{'version_'.$uri}) {
 7734:  	    my $version=$bighash{'version_'.$uri};
 7735:  	    unless (($version eq 'mostrecent') || 
 7736: 		    ($version==&getversion($uri))) {
 7737:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 7738:  	    }
 7739:  	}
 7740:  	untie %bighash;
 7741:     }
 7742:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 7743: }
 7744: 
 7745: sub deversion {
 7746:     my $url=shift;
 7747:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 7748:     return $url;
 7749: }
 7750: 
 7751: # ------------------------------------------------------ Return symb list entry
 7752: 
 7753: sub symbread {
 7754:     my ($thisfn,$donotrecurse)=@_;
 7755:     my $cache_str='request.symbread.cached.'.$thisfn;
 7756:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 7757: # no filename provided? try from environment
 7758:     unless ($thisfn) {
 7759:         if ($env{'request.symb'}) {
 7760: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 7761: 	}
 7762: 	$thisfn=$env{'request.filename'};
 7763:     }
 7764:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7765: # is that filename actually a symb? Verify, clean, and return
 7766:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 7767: 	if (&symbverify($thisfn,$1)) {
 7768: 	    return $env{$cache_str}=&symbclean($thisfn);
 7769: 	}
 7770:     }
 7771:     $thisfn=declutter($thisfn);
 7772:     my %hash;
 7773:     my %bighash;
 7774:     my $syval='';
 7775:     if (($env{'request.course.fn'}) && ($thisfn)) {
 7776:         my $targetfn = $thisfn;
 7777:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 7778:             $targetfn = 'adm/wrapper/'.$thisfn;
 7779:         }
 7780: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 7781: 	    $targetfn=$1;
 7782: 	}
 7783:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7784:                       &GDBM_READER(),0640)) {
 7785: 	    $syval=$hash{$targetfn};
 7786:             untie(%hash);
 7787:         }
 7788: # ---------------------------------------------------------- There was an entry
 7789:         if ($syval) {
 7790: 	    #unless ($syval=~/\_\d+$/) {
 7791: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 7792: 		    #&appenv({'request.ambiguous' => $thisfn});
 7793: 		    #return $env{$cache_str}='';
 7794: 		#}    
 7795: 		#$syval.=$1;
 7796: 	    #}
 7797:         } else {
 7798: # ------------------------------------------------------- Was not in symb table
 7799:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7800:                             &GDBM_READER(),0640)) {
 7801: # ---------------------------------------------- Get ID(s) for current resource
 7802:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 7803:               unless ($ids) { 
 7804:                  $ids=$bighash{'ids_/'.$thisfn};
 7805:               }
 7806:               unless ($ids) {
 7807: # alias?
 7808: 		  $ids=$bighash{'mapalias_'.$thisfn};
 7809:               }
 7810:               if ($ids) {
 7811: # ------------------------------------------------------------------- Has ID(s)
 7812:                  my @possibilities=split(/\,/,$ids);
 7813:                  if ($#possibilities==0) {
 7814: # ----------------------------------------------- There is only one possibility
 7815: 		     my ($mapid,$resid)=split(/\./,$ids);
 7816: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7817: 						    $resid,$thisfn);
 7818:                  } elsif (!$donotrecurse) {
 7819: # ------------------------------------------ There is more than one possibility
 7820:                      my $realpossible=0;
 7821:                      foreach my $id (@possibilities) {
 7822: 			 my $file=$bighash{'src_'.$id};
 7823:                          if (&allowed('bre',$file)) {
 7824:          		    my ($mapid,$resid)=split(/\./,$id);
 7825:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 7826: 				$realpossible++;
 7827:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7828: 						    $resid,$thisfn);
 7829:                             }
 7830: 			 }
 7831:                      }
 7832: 		     if ($realpossible!=1) { $syval=''; }
 7833:                  } else {
 7834:                      $syval='';
 7835:                  }
 7836: 	      }
 7837:               untie(%bighash)
 7838:            }
 7839:         }
 7840:         if ($syval) {
 7841: 	    return $env{$cache_str}=$syval;
 7842:         }
 7843:     }
 7844:     &appenv({'request.ambiguous' => $thisfn});
 7845:     return $env{$cache_str}='';
 7846: }
 7847: 
 7848: # ---------------------------------------------------------- Return random seed
 7849: 
 7850: sub numval {
 7851:     my $txt=shift;
 7852:     $txt=~tr/A-J/0-9/;
 7853:     $txt=~tr/a-j/0-9/;
 7854:     $txt=~tr/K-T/0-9/;
 7855:     $txt=~tr/k-t/0-9/;
 7856:     $txt=~tr/U-Z/0-5/;
 7857:     $txt=~tr/u-z/0-5/;
 7858:     $txt=~s/\D//g;
 7859:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 7860:     return int($txt);
 7861: }
 7862: 
 7863: sub numval2 {
 7864:     my $txt=shift;
 7865:     $txt=~tr/A-J/0-9/;
 7866:     $txt=~tr/a-j/0-9/;
 7867:     $txt=~tr/K-T/0-9/;
 7868:     $txt=~tr/k-t/0-9/;
 7869:     $txt=~tr/U-Z/0-5/;
 7870:     $txt=~tr/u-z/0-5/;
 7871:     $txt=~s/\D//g;
 7872:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7873:     my $total;
 7874:     foreach my $val (@txts) { $total+=$val; }
 7875:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 7876:     return int($total);
 7877: }
 7878: 
 7879: sub numval3 {
 7880:     use integer;
 7881:     my $txt=shift;
 7882:     $txt=~tr/A-J/0-9/;
 7883:     $txt=~tr/a-j/0-9/;
 7884:     $txt=~tr/K-T/0-9/;
 7885:     $txt=~tr/k-t/0-9/;
 7886:     $txt=~tr/U-Z/0-5/;
 7887:     $txt=~tr/u-z/0-5/;
 7888:     $txt=~s/\D//g;
 7889:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7890:     my $total;
 7891:     foreach my $val (@txts) { $total+=$val; }
 7892:     if ($_64bit) { $total=(($total<<32)>>32); }
 7893:     return $total;
 7894: }
 7895: 
 7896: sub digest {
 7897:     my ($data)=@_;
 7898:     my $digest=&Digest::MD5::md5($data);
 7899:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 7900:     my ($e,$f);
 7901:     {
 7902:         use integer;
 7903:         $e=($a+$b);
 7904:         $f=($c+$d);
 7905:         if ($_64bit) {
 7906:             $e=(($e<<32)>>32);
 7907:             $f=(($f<<32)>>32);
 7908:         }
 7909:     }
 7910:     if (wantarray) {
 7911: 	return ($e,$f);
 7912:     } else {
 7913: 	my $g;
 7914: 	{
 7915: 	    use integer;
 7916: 	    $g=($e+$f);
 7917: 	    if ($_64bit) {
 7918: 		$g=(($g<<32)>>32);
 7919: 	    }
 7920: 	}
 7921: 	return $g;
 7922:     }
 7923: }
 7924: 
 7925: sub latest_rnd_algorithm_id {
 7926:     return '64bit5';
 7927: }
 7928: 
 7929: sub get_rand_alg {
 7930:     my ($courseid)=@_;
 7931:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 7932:     if ($courseid) {
 7933: 	return $env{"course.$courseid.rndseed"};
 7934:     }
 7935:     return &latest_rnd_algorithm_id();
 7936: }
 7937: 
 7938: sub validCODE {
 7939:     my ($CODE)=@_;
 7940:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 7941:     return 0;
 7942: }
 7943: 
 7944: sub getCODE {
 7945:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 7946:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 7947: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 7948: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 7949: 	return $Apache::lonhomework::history{'resource.CODE'};
 7950:     }
 7951:     return undef;
 7952: }
 7953: 
 7954: sub rndseed {
 7955:     my ($symb,$courseid,$domain,$username)=@_;
 7956:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 7957:     if (!defined($symb)) {
 7958: 	unless ($symb=$wsymb) { return time; }
 7959:     }
 7960:     if (!$courseid) { $courseid=$wcourseid; }
 7961:     if (!$domain) { $domain=$wdomain; }
 7962:     if (!$username) { $username=$wusername }
 7963:     my $which=&get_rand_alg();
 7964: 
 7965:     if (defined(&getCODE())) {
 7966: 	if ($which eq '64bit5') {
 7967: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 7968: 	} elsif ($which eq '64bit4') {
 7969: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 7970: 	} else {
 7971: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 7972: 	}
 7973:     } elsif ($which eq '64bit5') {
 7974: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 7975:     } elsif ($which eq '64bit4') {
 7976: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 7977:     } elsif ($which eq '64bit3') {
 7978: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 7979:     } elsif ($which eq '64bit2') {
 7980: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 7981:     } elsif ($which eq '64bit') {
 7982: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 7983:     }
 7984:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 7985: }
 7986: 
 7987: sub rndseed_32bit {
 7988:     my ($symb,$courseid,$domain,$username)=@_;
 7989:     {
 7990: 	use integer;
 7991: 	my $symbchck=unpack("%32C*",$symb) << 27;
 7992: 	my $symbseed=numval($symb) << 22;
 7993: 	my $namechck=unpack("%32C*",$username) << 17;
 7994: 	my $nameseed=numval($username) << 12;
 7995: 	my $domainseed=unpack("%32C*",$domain) << 7;
 7996: 	my $courseseed=unpack("%32C*",$courseid);
 7997: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 7998: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7999: 	#&logthis("rndseed :$num:$symb");
 8000: 	if ($_64bit) { $num=(($num<<32)>>32); }
 8001: 	return $num;
 8002:     }
 8003: }
 8004: 
 8005: sub rndseed_64bit {
 8006:     my ($symb,$courseid,$domain,$username)=@_;
 8007:     {
 8008: 	use integer;
 8009: 	my $symbchck=unpack("%32S*",$symb) << 21;
 8010: 	my $symbseed=numval($symb) << 10;
 8011: 	my $namechck=unpack("%32S*",$username);
 8012: 	
 8013: 	my $nameseed=numval($username) << 21;
 8014: 	my $domainseed=unpack("%32S*",$domain) << 10;
 8015: 	my $courseseed=unpack("%32S*",$courseid);
 8016: 	
 8017: 	my $num1=$symbchck+$symbseed+$namechck;
 8018: 	my $num2=$nameseed+$domainseed+$courseseed;
 8019: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8020: 	#&logthis("rndseed :$num:$symb");
 8021: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8022: 	return "$num1,$num2";
 8023:     }
 8024: }
 8025: 
 8026: sub rndseed_64bit2 {
 8027:     my ($symb,$courseid,$domain,$username)=@_;
 8028:     {
 8029: 	use integer;
 8030: 	# strings need to be an even # of cahracters long, it it is odd the
 8031:         # last characters gets thrown away
 8032: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8033: 	my $symbseed=numval($symb) << 10;
 8034: 	my $namechck=unpack("%32S*",$username.' ');
 8035: 	
 8036: 	my $nameseed=numval($username) << 21;
 8037: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8038: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8039: 	
 8040: 	my $num1=$symbchck+$symbseed+$namechck;
 8041: 	my $num2=$nameseed+$domainseed+$courseseed;
 8042: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8043: 	#&logthis("rndseed :$num:$symb");
 8044: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8045: 	return "$num1,$num2";
 8046:     }
 8047: }
 8048: 
 8049: sub rndseed_64bit3 {
 8050:     my ($symb,$courseid,$domain,$username)=@_;
 8051:     {
 8052: 	use integer;
 8053: 	# strings need to be an even # of cahracters long, it it is odd the
 8054:         # last characters gets thrown away
 8055: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8056: 	my $symbseed=numval2($symb) << 10;
 8057: 	my $namechck=unpack("%32S*",$username.' ');
 8058: 	
 8059: 	my $nameseed=numval2($username) << 21;
 8060: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8061: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8062: 	
 8063: 	my $num1=$symbchck+$symbseed+$namechck;
 8064: 	my $num2=$nameseed+$domainseed+$courseseed;
 8065: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8066: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8067: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8068: 	
 8069: 	return "$num1:$num2";
 8070:     }
 8071: }
 8072: 
 8073: sub rndseed_64bit4 {
 8074:     my ($symb,$courseid,$domain,$username)=@_;
 8075:     {
 8076: 	use integer;
 8077: 	# strings need to be an even # of cahracters long, it it is odd the
 8078:         # last characters gets thrown away
 8079: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8080: 	my $symbseed=numval3($symb) << 10;
 8081: 	my $namechck=unpack("%32S*",$username.' ');
 8082: 	
 8083: 	my $nameseed=numval3($username) << 21;
 8084: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8085: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8086: 	
 8087: 	my $num1=$symbchck+$symbseed+$namechck;
 8088: 	my $num2=$nameseed+$domainseed+$courseseed;
 8089: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8090: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8091: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8092: 	
 8093: 	return "$num1:$num2";
 8094:     }
 8095: }
 8096: 
 8097: sub rndseed_64bit5 {
 8098:     my ($symb,$courseid,$domain,$username)=@_;
 8099:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 8100:     return "$num1:$num2";
 8101: }
 8102: 
 8103: sub rndseed_CODE_64bit {
 8104:     my ($symb,$courseid,$domain,$username)=@_;
 8105:     {
 8106: 	use integer;
 8107: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8108: 	my $symbseed=numval2($symb);
 8109: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8110: 	my $CODEseed=numval(&getCODE());
 8111: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8112: 	my $num1=$symbseed+$CODEchck;
 8113: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8114: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8115: 	#&logthis("rndseed :$num1:$num2:$symb");
 8116: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8117: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8118: 	return "$num1:$num2";
 8119:     }
 8120: }
 8121: 
 8122: sub rndseed_CODE_64bit4 {
 8123:     my ($symb,$courseid,$domain,$username)=@_;
 8124:     {
 8125: 	use integer;
 8126: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8127: 	my $symbseed=numval3($symb);
 8128: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8129: 	my $CODEseed=numval3(&getCODE());
 8130: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8131: 	my $num1=$symbseed+$CODEchck;
 8132: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8133: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8134: 	#&logthis("rndseed :$num1:$num2:$symb");
 8135: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8136: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8137: 	return "$num1:$num2";
 8138:     }
 8139: }
 8140: 
 8141: sub rndseed_CODE_64bit5 {
 8142:     my ($symb,$courseid,$domain,$username)=@_;
 8143:     my $code = &getCODE();
 8144:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 8145:     return "$num1:$num2";
 8146: }
 8147: 
 8148: sub setup_random_from_rndseed {
 8149:     my ($rndseed)=@_;
 8150:     if ($rndseed =~/([,:])/) {
 8151: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 8152: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 8153:     } else {
 8154: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 8155:     }
 8156: }
 8157: 
 8158: sub latest_receipt_algorithm_id {
 8159:     return 'receipt3';
 8160: }
 8161: 
 8162: sub recunique {
 8163:     my $fucourseid=shift;
 8164:     my $unique;
 8165:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 8166: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8167: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 8168:     } else {
 8169: 	$unique=$perlvar{'lonReceipt'};
 8170:     }
 8171:     return unpack("%32C*",$unique);
 8172: }
 8173: 
 8174: sub recprefix {
 8175:     my $fucourseid=shift;
 8176:     my $prefix;
 8177:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 8178: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8179: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 8180:     } else {
 8181: 	$prefix=$perlvar{'lonHostID'};
 8182:     }
 8183:     return unpack("%32C*",$prefix);
 8184: }
 8185: 
 8186: sub ireceipt {
 8187:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 8188: 
 8189:     my $return =&recprefix($fucourseid).'-';
 8190: 
 8191:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 8192: 	$env{'request.state'} eq 'construct') {
 8193: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 8194: 	return $return;
 8195:     }
 8196: 
 8197:     my $cuname=unpack("%32C*",$funame);
 8198:     my $cudom=unpack("%32C*",$fudom);
 8199:     my $cucourseid=unpack("%32C*",$fucourseid);
 8200:     my $cusymb=unpack("%32C*",$fusymb);
 8201:     my $cunique=&recunique($fucourseid);
 8202:     my $cpart=unpack("%32S*",$part);
 8203:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 8204: 
 8205: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 8206: 			       
 8207: 	$return.= ($cunique%$cuname+
 8208: 		   $cunique%$cudom+
 8209: 		   $cusymb%$cuname+
 8210: 		   $cusymb%$cudom+
 8211: 		   $cucourseid%$cuname+
 8212: 		   $cucourseid%$cudom+
 8213: 		   $cpart%$cuname+
 8214: 		   $cpart%$cudom);
 8215:     } else {
 8216: 	$return.= ($cunique%$cuname+
 8217: 		   $cunique%$cudom+
 8218: 		   $cusymb%$cuname+
 8219: 		   $cusymb%$cudom+
 8220: 		   $cucourseid%$cuname+
 8221: 		   $cucourseid%$cudom);
 8222:     }
 8223:     return $return;
 8224: }
 8225: 
 8226: sub receipt {
 8227:     my ($part)=@_;
 8228:     my ($symb,$courseid,$domain,$name) = &whichuser();
 8229:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 8230: }
 8231: 
 8232: sub whichuser {
 8233:     my ($passedsymb)=@_;
 8234:     my ($symb,$courseid,$domain,$name,$publicuser);
 8235:     if (defined($env{'form.grade_symb'})) {
 8236: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 8237: 	my $allowed=&allowed('vgr',$tmp_courseid);
 8238: 	if (!$allowed &&
 8239: 	    exists($env{'request.course.sec'}) &&
 8240: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 8241: 	    $allowed=&allowed('vgr',$tmp_courseid.
 8242: 			      '/'.$env{'request.course.sec'});
 8243: 	}
 8244: 	if ($allowed) {
 8245: 	    ($symb)=&get_env_multiple('form.grade_symb');
 8246: 	    $courseid=$tmp_courseid;
 8247: 	    ($domain)=&get_env_multiple('form.grade_domain');
 8248: 	    ($name)=&get_env_multiple('form.grade_username');
 8249: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 8250: 	}
 8251:     }
 8252:     if (!$passedsymb) {
 8253: 	$symb=&symbread();
 8254:     } else {
 8255: 	$symb=$passedsymb;
 8256:     }
 8257:     $courseid=$env{'request.course.id'};
 8258:     $domain=$env{'user.domain'};
 8259:     $name=$env{'user.name'};
 8260:     if ($name eq 'public' && $domain eq 'public') {
 8261: 	if (!defined($env{'form.username'})) {
 8262: 	    $env{'form.username'}.=time.rand(10000000);
 8263: 	}
 8264: 	$name.=$env{'form.username'};
 8265:     }
 8266:     return ($symb,$courseid,$domain,$name,$publicuser);
 8267: 
 8268: }
 8269: 
 8270: # ------------------------------------------------------------ Serves up a file
 8271: # returns either the contents of the file or 
 8272: # -1 if the file doesn't exist
 8273: #
 8274: # if the target is a file that was uploaded via DOCS, 
 8275: # a check will be made to see if a current copy exists on the local server,
 8276: # if it does this will be served, otherwise a copy will be retrieved from
 8277: # the home server for the course and stored in /home/httpd/html/userfiles on
 8278: # the local server.   
 8279: 
 8280: sub getfile {
 8281:     my ($file) = @_;
 8282:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8283:     &repcopy($file);
 8284:     return &readfile($file);
 8285: }
 8286: 
 8287: sub repcopy_userfile {
 8288:     my ($file)=@_;
 8289:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8290:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 8291:     my ($cdom,$cnum,$filename) = 
 8292: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 8293:     my $uri="/uploaded/$cdom/$cnum/$filename";
 8294:     if (-e "$file") {
 8295: # we already have a local copy, check it out
 8296: 	my @fileinfo = stat($file);
 8297: 	my $rtncode;
 8298: 	my $info;
 8299: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 8300: 	if ($lwpresp ne 'ok') {
 8301: # there is no such file anymore, even though we had a local copy
 8302: 	    if ($rtncode eq '404') {
 8303: 		unlink($file);
 8304: 	    }
 8305: 	    return -1;
 8306: 	}
 8307: 	if ($info < $fileinfo[9]) {
 8308: # nice, the file we have is up-to-date, just say okay
 8309: 	    return 'ok';
 8310: 	} else {
 8311: # the file is outdated, get rid of it
 8312: 	    unlink($file);
 8313: 	}
 8314:     }
 8315: # one way or the other, at this point, we don't have the file
 8316: # construct the correct path for the file
 8317:     my @parts = ($cdom,$cnum); 
 8318:     if ($filename =~ m|^(.+)/[^/]+$|) {
 8319: 	push @parts, split(/\//,$1);
 8320:     }
 8321:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 8322:     foreach my $part (@parts) {
 8323: 	$path .= '/'.$part;
 8324: 	if (!-e $path) {
 8325: 	    mkdir($path,0770);
 8326: 	}
 8327:     }
 8328: # now the path exists for sure
 8329: # get a user agent
 8330:     my $ua=new LWP::UserAgent;
 8331:     my $transferfile=$file.'.in.transfer';
 8332: # FIXME: this should flock
 8333:     if (-e $transferfile) { return 'ok'; }
 8334:     my $request;
 8335:     $uri=~s/^\///;
 8336:     my $homeserver = &homeserver($cnum,$cdom);
 8337:     my $protocol = $protocol{$homeserver};
 8338:     $protocol = 'http' if ($protocol ne 'https');
 8339:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
 8340:     my $response=$ua->request($request,$transferfile);
 8341: # did it work?
 8342:     if ($response->is_error()) {
 8343: 	unlink($transferfile);
 8344: 	&logthis("Userfile repcopy failed for $uri");
 8345: 	return -1;
 8346:     }
 8347: # worked, rename the transfer file
 8348:     rename($transferfile,$file);
 8349:     return 'ok';
 8350: }
 8351: 
 8352: sub tokenwrapper {
 8353:     my $uri=shift;
 8354:     $uri=~s|^https?\://([^/]+)||;
 8355:     $uri=~s|^/||;
 8356:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 8357:     my $token=$1;
 8358:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 8359:     if ($udom && $uname && $file) {
 8360: 	$file=~s|(\?\.*)*$||;
 8361:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 8362:         my $homeserver = &homeserver($uname,$udom);
 8363:         my $protocol = $protocol{$homeserver};
 8364:         $protocol = 'http' if ($protocol ne 'https');
 8365:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
 8366:                (($uri=~/\?/)?'&':'?').'token='.$token.
 8367:                                '&tokenissued='.$perlvar{'lonHostID'};
 8368:     } else {
 8369:         return '/adm/notfound.html';
 8370:     }
 8371: }
 8372: 
 8373: # call with reqtype HEAD: get last modification time
 8374: # call with reqtype GET: get the file contents
 8375: # Do not call this with reqtype GET for large files! It loads everything into memory
 8376: #
 8377: sub getuploaded {
 8378:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 8379:     $uri=~s/^\///;
 8380:     my $homeserver = &homeserver($cnum,$cdom);
 8381:     my $protocol = $protocol{$homeserver};
 8382:     $protocol = 'http' if ($protocol ne 'https');
 8383:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
 8384:     my $ua=new LWP::UserAgent;
 8385:     my $request=new HTTP::Request($reqtype,$uri);
 8386:     my $response=$ua->request($request);
 8387:     $$rtncode = $response->code;
 8388:     if (! $response->is_success()) {
 8389: 	return 'failed';
 8390:     }      
 8391:     if ($reqtype eq 'HEAD') {
 8392: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 8393:     } elsif ($reqtype eq 'GET') {
 8394: 	$$info = $response->content;
 8395:     }
 8396:     return 'ok';
 8397: }
 8398: 
 8399: sub readfile {
 8400:     my $file = shift;
 8401:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 8402:     my $fh;
 8403:     open($fh,"<$file");
 8404:     my $a='';
 8405:     while (my $line = <$fh>) { $a .= $line; }
 8406:     return $a;
 8407: }
 8408: 
 8409: sub filelocation {
 8410:     my ($dir,$file) = @_;
 8411:     my $location;
 8412:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 8413: 
 8414:     if ($file =~ m-^/adm/-) {
 8415: 	$file=~s-^/adm/wrapper/-/-;
 8416: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8417:     }
 8418: 
 8419:     if ($file=~m:^/~:) { # is a contruction space reference
 8420:         $location = $file;
 8421:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 8422:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 8423: 	# is a correct contruction space reference
 8424:         $location = $file;
 8425:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
 8426:         $location = $file;
 8427:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 8428:         my ($udom,$uname,$filename)=
 8429:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 8430:         my $home=&homeserver($uname,$udom);
 8431:         my $is_me=0;
 8432:         my @ids=&current_machine_ids();
 8433:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 8434:         if ($is_me) {
 8435:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
 8436:         } else {
 8437:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 8438:   	      $udom.'/'.$uname.'/'.$filename;
 8439:         }
 8440:     } elsif ($file =~ m-^/adm/-) {
 8441: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 8442:     } else {
 8443:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8444:         $file=~s:^/res/:/:;
 8445:         if ( !( $file =~ m:^/:) ) {
 8446:             $location = $dir. '/'.$file;
 8447:         } else {
 8448:             $location = '/home/httpd/html/res'.$file;
 8449:         }
 8450:     }
 8451:     $location=~s://+:/:g; # remove duplicate /
 8452:     while ($location=~m{/\.\./}) {
 8453: 	if ($location =~ m{/[^/]+/\.\./}) {
 8454: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 8455: 	} else {
 8456: 	    $location=~ s{/\.\./}{/}g;
 8457: 	}
 8458:     } #remove dir/..
 8459:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 8460:     return $location;
 8461: }
 8462: 
 8463: sub hreflocation {
 8464:     my ($dir,$file)=@_;
 8465:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
 8466: 	$file=filelocation($dir,$file);
 8467:     } elsif ($file=~m-^/adm/-) {
 8468: 	$file=~s-^/adm/wrapper/-/-;
 8469: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8470:     }
 8471:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 8472: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 8473:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 8474: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 8475:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 8476: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 8477: 	    -/uploaded/$1/$2/-x;
 8478:     }
 8479:     if ($file=~ m{^/userfiles/}) {
 8480: 	$file =~ s{^/userfiles/}{/uploaded/};
 8481:     }
 8482:     return $file;
 8483: }
 8484: 
 8485: sub current_machine_domains {
 8486:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 8487: }
 8488: 
 8489: sub machine_domains {
 8490:     my ($hostname) = @_;
 8491:     my @domains;
 8492:     my %hostname = &all_hostnames();
 8493:     while( my($id, $name) = each(%hostname)) {
 8494: #	&logthis("-$id-$name-$hostname-");
 8495: 	if ($hostname eq $name) {
 8496: 	    push(@domains,&host_domain($id));
 8497: 	}
 8498:     }
 8499:     return @domains;
 8500: }
 8501: 
 8502: sub current_machine_ids {
 8503:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 8504: }
 8505: 
 8506: sub machine_ids {
 8507:     my ($hostname) = @_;
 8508:     $hostname ||= &hostname($perlvar{'lonHostID'});
 8509:     my @ids;
 8510:     my %name_to_host = &all_names();
 8511:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 8512: 	return @{ $name_to_host{$hostname} };
 8513:     }
 8514:     return;
 8515: }
 8516: 
 8517: sub additional_machine_domains {
 8518:     my @domains;
 8519:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 8520:     while( my $line = <$fh>) {
 8521:         $line =~ s/\s//g;
 8522:         push(@domains,$line);
 8523:     }
 8524:     return @domains;
 8525: }
 8526: 
 8527: sub default_login_domain {
 8528:     my $domain = $perlvar{'lonDefDomain'};
 8529:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 8530:     foreach my $posdom (&current_machine_domains(),
 8531:                         &additional_machine_domains()) {
 8532:         if (lc($posdom) eq lc($testdomain)) {
 8533:             $domain=$posdom;
 8534:             last;
 8535:         }
 8536:     }
 8537:     return $domain;
 8538: }
 8539: 
 8540: # ------------------------------------------------------------- Declutters URLs
 8541: 
 8542: sub declutter {
 8543:     my $thisfn=shift;
 8544:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8545:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8546:     $thisfn=~s/^\///;
 8547:     $thisfn=~s|^adm/wrapper/||;
 8548:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 8549:     $thisfn=~s/^res\///;
 8550:     $thisfn=~s/\?.+$//;
 8551:     return $thisfn;
 8552: }
 8553: 
 8554: # ------------------------------------------------------------- Clutter up URLs
 8555: 
 8556: sub clutter {
 8557:     my $thisfn='/'.&declutter(shift);
 8558:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 8559: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 8560:        $thisfn='/res'.$thisfn; 
 8561:     }
 8562:     if ($thisfn !~m|/adm|) {
 8563: 	if ($thisfn =~ m|/ext/|) {
 8564: 	    $thisfn='/adm/wrapper'.$thisfn;
 8565: 	} else {
 8566: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 8567: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 8568: 	    if ($embstyle eq 'ssi'
 8569: 		|| ($embstyle eq 'hdn')
 8570: 		|| ($embstyle eq 'rat')
 8571: 		|| ($embstyle eq 'prv')
 8572: 		|| ($embstyle eq 'ign')) {
 8573: 		#do nothing with these
 8574: 	    } elsif (($embstyle eq 'img') 
 8575: 		|| ($embstyle eq 'emb')
 8576: 		|| ($embstyle eq 'wrp')) {
 8577: 		$thisfn='/adm/wrapper'.$thisfn;
 8578: 	    } elsif ($embstyle eq 'unk'
 8579: 		     && $thisfn!~/\.(sequence|page)$/) {
 8580: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 8581: 	    } else {
 8582: #		&logthis("Got a blank emb style");
 8583: 	    }
 8584: 	}
 8585:     }
 8586:     return $thisfn;
 8587: }
 8588: 
 8589: sub clutter_with_no_wrapper {
 8590:     my $uri = &clutter(shift);
 8591:     if ($uri =~ m-^/adm/-) {
 8592: 	$uri =~ s-^/adm/wrapper/-/-;
 8593: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 8594:     }
 8595:     return $uri;
 8596: }
 8597: 
 8598: sub freeze_escape {
 8599:     my ($value)=@_;
 8600:     if (ref($value)) {
 8601: 	$value=&nfreeze($value);
 8602: 	return '__FROZEN__'.&escape($value);
 8603:     }
 8604:     return &escape($value);
 8605: }
 8606: 
 8607: 
 8608: sub thaw_unescape {
 8609:     my ($value)=@_;
 8610:     if ($value =~ /^__FROZEN__/) {
 8611: 	substr($value,0,10,undef);
 8612: 	$value=&unescape($value);
 8613: 	return &thaw($value);
 8614:     }
 8615:     return &unescape($value);
 8616: }
 8617: 
 8618: sub correct_line_ends {
 8619:     my ($result)=@_;
 8620:     $$result =~s/\r\n/\n/mg;
 8621:     $$result =~s/\r/\n/mg;
 8622: }
 8623: # ================================================================ Main Program
 8624: 
 8625: sub goodbye {
 8626:    &logthis("Starting Shut down");
 8627: #not converted to using infrastruture and probably shouldn't be
 8628:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 8629: #converted
 8630: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 8631:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 8632: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 8633: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 8634: #1.1 only
 8635: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 8636: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 8637: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 8638: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 8639:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 8640:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 8641:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 8642:    &flushcourselogs();
 8643:    &logthis("Shutting down");
 8644: }
 8645: 
 8646: sub get_dns {
 8647:     my ($url,$func,$ignore_cache) = @_;
 8648:     if (!$ignore_cache) {
 8649: 	my ($content,$cached)=
 8650: 	    &Apache::lonnet::is_cached_new('dns',$url);
 8651: 	if ($cached) {
 8652: 	    &$func($content);
 8653: 	    return;
 8654: 	}
 8655:     }
 8656: 
 8657:     my %alldns;
 8658:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8659:     foreach my $dns (<$config>) {
 8660: 	next if ($dns !~ /^\^(\S*)/x);
 8661:         my $line = $1;
 8662:         my ($host,$protocol) = split(/:/,$line);
 8663:         if ($protocol ne 'https') {
 8664:             $protocol = 'http';
 8665:         }
 8666: 	$alldns{$host} = $protocol;
 8667:     }
 8668:     while (%alldns) {
 8669: 	my ($dns) = keys(%alldns);
 8670: 	my $ua=new LWP::UserAgent;
 8671: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
 8672: 	my $response=$ua->request($request);
 8673:         delete($alldns{$dns});
 8674: 	next if ($response->is_error());
 8675: 	my @content = split("\n",$response->content);
 8676: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 8677: 	&$func(\@content);
 8678: 	return;
 8679:     }
 8680:     close($config);
 8681:     my $which = (split('/',$url))[3];
 8682:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 8683:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 8684:     my @content = <$config>;
 8685:     &$func(\@content);
 8686:     return;
 8687: }
 8688: # ------------------------------------------------------------ Read domain file
 8689: {
 8690:     my $loaded;
 8691:     my %domain;
 8692: 
 8693:     sub parse_domain_tab {
 8694: 	my ($lines) = @_;
 8695: 	foreach my $line (@$lines) {
 8696: 	    next if ($line =~ /^(\#|\s*$ )/x);
 8697: 
 8698: 	    chomp($line);
 8699: 	    my ($name,@elements) = split(/:/,$line,9);
 8700: 	    my %this_domain;
 8701: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 8702: 			       'lang_def', 'city', 'longi', 'lati',
 8703: 			       'primary') {
 8704: 		$this_domain{$field} = shift(@elements);
 8705: 	    }
 8706: 	    $domain{$name} = \%this_domain;
 8707: 	}
 8708:     }
 8709: 
 8710:     sub reset_domain_info {
 8711: 	undef($loaded);
 8712: 	undef(%domain);
 8713:     }
 8714: 
 8715:     sub load_domain_tab {
 8716: 	my ($ignore_cache) = @_;
 8717: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 8718: 	my $fh;
 8719: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 8720: 	    my @lines = <$fh>;
 8721: 	    &parse_domain_tab(\@lines);
 8722: 	}
 8723: 	close($fh);
 8724: 	$loaded = 1;
 8725:     }
 8726: 
 8727:     sub domain {
 8728: 	&load_domain_tab() if (!$loaded);
 8729: 
 8730: 	my ($name,$what) = @_;
 8731: 	return if ( !exists($domain{$name}) );
 8732: 
 8733: 	if (!$what) {
 8734: 	    return $domain{$name}{'description'};
 8735: 	}
 8736: 	return $domain{$name}{$what};
 8737:     }
 8738: 
 8739:     sub domain_info {
 8740:         &load_domain_tab() if (!$loaded);
 8741:         return %domain;
 8742:     }
 8743: 
 8744: }
 8745: 
 8746: 
 8747: # ------------------------------------------------------------- Read hosts file
 8748: {
 8749:     my %hostname;
 8750:     my %hostdom;
 8751:     my %libserv;
 8752:     my $loaded;
 8753:     my %name_to_host;
 8754: 
 8755:     sub parse_hosts_tab {
 8756: 	my ($file) = @_;
 8757: 	foreach my $configline (@$file) {
 8758: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 8759: 	    next if ($configline =~ /^\^/);
 8760: 	    chomp($configline);
 8761: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
 8762: 	    $name=~s/\s//g;
 8763: 	    if ($id && $domain && $role && $name) {
 8764: 		$hostname{$id}=$name;
 8765: 		push(@{$name_to_host{$name}}, $id);
 8766: 		$hostdom{$id}=$domain;
 8767: 		if ($role eq 'library') { $libserv{$id}=$name; }
 8768:                 if (defined($protocol)) {
 8769:                     if ($protocol eq 'https') {
 8770:                         $protocol{$id} = $protocol;
 8771:                     } else {
 8772:                         $protocol{$id} = 'http'; 
 8773:                     }
 8774:                 } else {
 8775:                     $protocol{$id} = 'http';
 8776:                 }
 8777: 	    }
 8778: 	}
 8779:     }
 8780:     
 8781:     sub reset_hosts_info {
 8782: 	&purge_remembered();
 8783: 	&reset_domain_info();
 8784: 	&reset_hosts_ip_info();
 8785: 	undef(%name_to_host);
 8786: 	undef(%hostname);
 8787: 	undef(%hostdom);
 8788: 	undef(%libserv);
 8789: 	undef($loaded);
 8790:     }
 8791: 
 8792:     sub load_hosts_tab {
 8793: 	my ($ignore_cache) = @_;
 8794: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 8795: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8796: 	my @config = <$config>;
 8797: 	&parse_hosts_tab(\@config);
 8798: 	close($config);
 8799: 	$loaded=1;
 8800:     }
 8801: 
 8802:     sub hostname {
 8803: 	&load_hosts_tab() if (!$loaded);
 8804: 
 8805: 	my ($lonid) = @_;
 8806: 	return $hostname{$lonid};
 8807:     }
 8808: 
 8809:     sub all_hostnames {
 8810: 	&load_hosts_tab() if (!$loaded);
 8811: 
 8812: 	return %hostname;
 8813:     }
 8814: 
 8815:     sub all_names {
 8816: 	&load_hosts_tab() if (!$loaded);
 8817: 
 8818: 	return %name_to_host;
 8819:     }
 8820: 
 8821:     sub all_host_domain {
 8822:         &load_hosts_tab() if (!$loaded);
 8823:         return %hostdom;
 8824:     }
 8825: 
 8826:     sub is_library {
 8827: 	&load_hosts_tab() if (!$loaded);
 8828: 
 8829: 	return exists($libserv{$_[0]});
 8830:     }
 8831: 
 8832:     sub all_library {
 8833: 	&load_hosts_tab() if (!$loaded);
 8834: 
 8835: 	return %libserv;
 8836:     }
 8837: 
 8838:     sub get_servers {
 8839: 	&load_hosts_tab() if (!$loaded);
 8840: 
 8841: 	my ($domain,$type) = @_;
 8842: 	my %possible_hosts = ($type eq 'library') ? %libserv
 8843: 	                                          : %hostname;
 8844: 	my %result;
 8845: 	if (ref($domain) eq 'ARRAY') {
 8846: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8847: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 8848: 		    $result{$host} = $hostname;
 8849: 		}
 8850: 	    }
 8851: 	} else {
 8852: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8853: 		if ($hostdom{$host} eq $domain) {
 8854: 		    $result{$host} = $hostname;
 8855: 		}
 8856: 	    }
 8857: 	}
 8858: 	return %result;
 8859:     }
 8860: 
 8861:     sub host_domain {
 8862: 	&load_hosts_tab() if (!$loaded);
 8863: 
 8864: 	my ($lonid) = @_;
 8865: 	return $hostdom{$lonid};
 8866:     }
 8867: 
 8868:     sub all_domains {
 8869: 	&load_hosts_tab() if (!$loaded);
 8870: 
 8871: 	my %seen;
 8872: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 8873: 	return @uniq;
 8874:     }
 8875: }
 8876: 
 8877: { 
 8878:     my %iphost;
 8879:     my %name_to_ip;
 8880:     my %lonid_to_ip;
 8881: 
 8882:     sub get_hosts_from_ip {
 8883: 	my ($ip) = @_;
 8884: 	my %iphosts = &get_iphost();
 8885: 	if (ref($iphosts{$ip})) {
 8886: 	    return @{$iphosts{$ip}};
 8887: 	}
 8888: 	return;
 8889:     }
 8890:     
 8891:     sub reset_hosts_ip_info {
 8892: 	undef(%iphost);
 8893: 	undef(%name_to_ip);
 8894: 	undef(%lonid_to_ip);
 8895:     }
 8896: 
 8897:     sub get_host_ip {
 8898: 	my ($lonid) = @_;
 8899: 	if (exists($lonid_to_ip{$lonid})) {
 8900: 	    return $lonid_to_ip{$lonid};
 8901: 	}
 8902: 	my $name=&hostname($lonid);
 8903:    	my $ip = gethostbyname($name);
 8904: 	return if (!$ip || length($ip) ne 4);
 8905: 	$ip=inet_ntoa($ip);
 8906: 	$name_to_ip{$name}   = $ip;
 8907: 	$lonid_to_ip{$lonid} = $ip;
 8908: 	return $ip;
 8909:     }
 8910:     
 8911:     sub get_iphost {
 8912: 	my ($ignore_cache) = @_;
 8913: 
 8914: 	if (!$ignore_cache) {
 8915: 	    if (%iphost) {
 8916: 		return %iphost;
 8917: 	    }
 8918: 	    my ($ip_info,$cached)=
 8919: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 8920: 	    if ($cached) {
 8921: 		%iphost      = %{$ip_info->[0]};
 8922: 		%name_to_ip  = %{$ip_info->[1]};
 8923: 		%lonid_to_ip = %{$ip_info->[2]};
 8924: 		return %iphost;
 8925: 	    }
 8926: 	}
 8927: 
 8928: 	# get yesterday's info for fallback
 8929: 	my %old_name_to_ip;
 8930: 	my ($ip_info,$cached)=
 8931: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 8932: 	if ($cached) {
 8933: 	    %old_name_to_ip = %{$ip_info->[1]};
 8934: 	}
 8935: 
 8936: 	my %name_to_host = &all_names();
 8937: 	foreach my $name (keys(%name_to_host)) {
 8938: 	    my $ip;
 8939: 	    if (!exists($name_to_ip{$name})) {
 8940: 		$ip = gethostbyname($name);
 8941: 		if (!$ip || length($ip) ne 4) {
 8942: 		    if (defined($old_name_to_ip{$name})) {
 8943: 			$ip = $old_name_to_ip{$name};
 8944: 			&logthis("Can't find $name defaulting to old $ip");
 8945: 		    } else {
 8946: 			&logthis("Name $name no IP found");
 8947: 			next;
 8948: 		    }
 8949: 		} else {
 8950: 		    $ip=inet_ntoa($ip);
 8951: 		}
 8952: 		$name_to_ip{$name} = $ip;
 8953: 	    } else {
 8954: 		$ip = $name_to_ip{$name};
 8955: 	    }
 8956: 	    foreach my $id (@{ $name_to_host{$name} }) {
 8957: 		$lonid_to_ip{$id} = $ip;
 8958: 	    }
 8959: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 8960: 	}
 8961: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 8962: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 8963: 				      48*60*60);
 8964: 
 8965: 	return %iphost;
 8966:     }
 8967: }
 8968: 
 8969: BEGIN {
 8970: 
 8971: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 8972:     unless ($readit) {
 8973: {
 8974:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 8975:     %perlvar = (%perlvar,%{$configvars});
 8976: }
 8977: 
 8978: 
 8979: # ------------------------------------------------------ Read spare server file
 8980: {
 8981:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 8982: 
 8983:     while (my $configline=<$config>) {
 8984:        chomp($configline);
 8985:        if ($configline) {
 8986: 	   my ($host,$type) = split(':',$configline,2);
 8987: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 8988: 	   push(@{ $spareid{$type} }, $host);
 8989:        }
 8990:     }
 8991:     close($config);
 8992: }
 8993: # ------------------------------------------------------------ Read permissions
 8994: {
 8995:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 8996: 
 8997:     while (my $configline=<$config>) {
 8998: 	chomp($configline);
 8999: 	if ($configline) {
 9000: 	    my ($role,$perm)=split(/ /,$configline);
 9001: 	    if ($perm ne '') { $pr{$role}=$perm; }
 9002: 	}
 9003:     }
 9004:     close($config);
 9005: }
 9006: 
 9007: # -------------------------------------------- Read plain texts for permissions
 9008: {
 9009:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 9010: 
 9011:     while (my $configline=<$config>) {
 9012: 	chomp($configline);
 9013: 	if ($configline) {
 9014: 	    my ($short,@plain)=split(/:/,$configline);
 9015:             %{$prp{$short}} = ();
 9016: 	    if (@plain > 0) {
 9017:                 $prp{$short}{'std'} = $plain[0];
 9018:                 for (my $i=1; $i<@plain; $i++) {
 9019:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 9020:                 }
 9021:             }
 9022: 	}
 9023:     }
 9024:     close($config);
 9025: }
 9026: 
 9027: # ---------------------------------------------------------- Read package table
 9028: {
 9029:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 9030: 
 9031:     while (my $configline=<$config>) {
 9032: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 9033: 	chomp($configline);
 9034: 	my ($short,$plain)=split(/:/,$configline);
 9035: 	my ($pack,$name)=split(/\&/,$short);
 9036: 	if ($plain ne '') {
 9037: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 9038: 	    $packagetab{$short}=$plain; 
 9039: 	}
 9040:     }
 9041:     close($config);
 9042: }
 9043: 
 9044: # ------------- set up temporary directory
 9045: {
 9046:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 9047: 
 9048: }
 9049: 
 9050: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 9051: 				'compress_threshold'=> 20_000,
 9052:  			        });
 9053: 
 9054: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 9055: $dumpcount=0;
 9056: $locknum=0;
 9057: 
 9058: &logtouch();
 9059: &logthis('<font color="yellow">INFO: Read configuration</font>');
 9060: $readit=1;
 9061:     {
 9062: 	use integer;
 9063: 	my $test=(2**32)+1;
 9064: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 9065: 	&logthis(" Detected 64bit platform ($_64bit)");
 9066:     }
 9067: }
 9068: }
 9069: 
 9070: 1;
 9071: __END__
 9072: 
 9073: =pod
 9074: 
 9075: =head1 NAME
 9076: 
 9077: Apache::lonnet - Subroutines to ask questions about things in the network.
 9078: 
 9079: =head1 SYNOPSIS
 9080: 
 9081: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 9082: 
 9083:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 9084: 
 9085: Common parameters:
 9086: 
 9087: =over 4
 9088: 
 9089: =item *
 9090: 
 9091: $uname : an internal username (if $cname expecting a course Id specifically)
 9092: 
 9093: =item *
 9094: 
 9095: $udom : a domain (if $cdom expecting a course's domain specifically)
 9096: 
 9097: =item *
 9098: 
 9099: $symb : a resource instance identifier
 9100: 
 9101: =item *
 9102: 
 9103: $namespace : the name of a .db file that contains the data needed or
 9104: being set.
 9105: 
 9106: =back
 9107: 
 9108: =head1 OVERVIEW
 9109: 
 9110: lonnet provides subroutines which interact with the
 9111: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 9112: about classes, users, and resources.
 9113: 
 9114: For many of these objects you can also use this to store data about
 9115: them or modify them in various ways.
 9116: 
 9117: =head2 Symbs
 9118: 
 9119: To identify a specific instance of a resource, LON-CAPA uses symbols
 9120: or "symbs"X<symb>. These identifiers are built from the URL of the
 9121: map, the resource number of the resource in the map, and the URL of
 9122: the resource itself. The latter is somewhat redundant, but might help
 9123: if maps change.
 9124: 
 9125: An example is
 9126: 
 9127:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 9128: 
 9129: The respective map entry is
 9130: 
 9131:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 9132:   title="Problem 2">
 9133:  </resource>
 9134: 
 9135: Symbs are used by the random number generator, as well as to store and
 9136: restore data specific to a certain instance of for example a problem.
 9137: 
 9138: =head2 Storing And Retrieving Data
 9139: 
 9140: X<store()>X<cstore()>X<restore()>Three of the most important functions
 9141: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 9142: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 9143: is is the non-critical message twin of cstore. These functions are for
 9144: handlers to store a perl hash to a user's permanent data space in an
 9145: easy manner, and to retrieve it again on another call. It is expected
 9146: that a handler would use this once at the beginning to retrieve data,
 9147: and then again once at the end to send only the new data back.
 9148: 
 9149: The data is stored in the user's data directory on the user's
 9150: homeserver under the ID of the course.
 9151: 
 9152: The hash that is returned by restore will have all of the previous
 9153: value for all of the elements of the hash.
 9154: 
 9155: Example:
 9156: 
 9157:  #creating a hash
 9158:  my %hash;
 9159:  $hash{'foo'}='bar';
 9160: 
 9161:  #storing it
 9162:  &Apache::lonnet::cstore(\%hash);
 9163: 
 9164:  #changing a value
 9165:  $hash{'foo'}='notbar';
 9166: 
 9167:  #adding a new value
 9168:  $hash{'bar'}='foo';
 9169:  &Apache::lonnet::cstore(\%hash);
 9170: 
 9171:  #retrieving the hash
 9172:  my %history=&Apache::lonnet::restore();
 9173: 
 9174:  #print the hash
 9175:  foreach my $key (sort(keys(%history))) {
 9176:    print("\%history{$key} = $history{$key}");
 9177:  }
 9178: 
 9179: Will print out:
 9180: 
 9181:  %history{1:foo} = bar
 9182:  %history{1:keys} = foo:timestamp
 9183:  %history{1:timestamp} = 990455579
 9184:  %history{2:bar} = foo
 9185:  %history{2:foo} = notbar
 9186:  %history{2:keys} = foo:bar:timestamp
 9187:  %history{2:timestamp} = 990455580
 9188:  %history{bar} = foo
 9189:  %history{foo} = notbar
 9190:  %history{timestamp} = 990455580
 9191:  %history{version} = 2
 9192: 
 9193: Note that the special hash entries C<keys>, C<version> and
 9194: C<timestamp> were added to the hash. C<version> will be equal to the
 9195: total number of versions of the data that have been stored. The
 9196: C<timestamp> attribute will be the UNIX time the hash was
 9197: stored. C<keys> is available in every historical section to list which
 9198: keys were added or changed at a specific historical revision of a
 9199: hash.
 9200: 
 9201: B<Warning>: do not store the hash that restore returns directly. This
 9202: will cause a mess since it will restore the historical keys as if the
 9203: were new keys. I.E. 1:foo will become 1:1:foo etc.
 9204: 
 9205: Calling convention:
 9206: 
 9207:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 9208:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 9209: 
 9210: For more detailed information, see lonnet specific documentation.
 9211: 
 9212: =head1 RETURN MESSAGES
 9213: 
 9214: =over 4
 9215: 
 9216: =item * B<con_lost>: unable to contact remote host
 9217: 
 9218: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 9219: when the connection is brought back up
 9220: 
 9221: =item * B<con_failed>: unable to contact remote host and unable to save message
 9222: for later delivery
 9223: 
 9224: =item * B<error:>: an error a occurred, a description of the error follows the :
 9225: 
 9226: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 9227: that was requested
 9228: 
 9229: =back
 9230: 
 9231: =head1 PUBLIC SUBROUTINES
 9232: 
 9233: =head2 Session Environment Functions
 9234: 
 9235: =over 4
 9236: 
 9237: =item * 
 9238: X<appenv()>
 9239: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
 9240: the user envirnoment file, and will be restored for each access this
 9241: user makes during this session, also modifies the %env for the current
 9242: process. Optional rolesarrayref - if defined contains a reference to an array
 9243: of roles which are exempt from the restriction on modifying user.role entries 
 9244: in the user's environment.db and in %env.    
 9245: 
 9246: =item *
 9247: X<delenv()>
 9248: B<delenv($regexp)>: removes all items from the session
 9249: environment file that matches the regular expression in $regexp. The
 9250: values are also delted from the current processes %env.
 9251: 
 9252: =item * get_env_multiple($name) 
 9253: 
 9254: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9255: values may be defined and end up as an array ref.
 9256: 
 9257: returns an array of values
 9258: 
 9259: =back
 9260: 
 9261: =head2 User Information
 9262: 
 9263: =over 4
 9264: 
 9265: =item *
 9266: X<queryauthenticate()>
 9267: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 9268: authentication scheme
 9269: 
 9270: =item *
 9271: X<authenticate()>
 9272: B<authenticate($uname,$upass,$udom)>: try to
 9273: authenticate user from domain's lib servers (first use the current
 9274: one). C<$upass> should be the users password.
 9275: 
 9276: =item *
 9277: X<homeserver()>
 9278: B<homeserver($uname,$udom)>: find the server which has
 9279: the user's directory and files (there must be only one), this caches
 9280: the answer, and also caches if there is a borken connection.
 9281: 
 9282: =item *
 9283: X<idget()>
 9284: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 9285: (IDs are a unique resource in a domain, there must be only 1 ID per
 9286: username, and only 1 username per ID in a specific domain) (returns
 9287: hash: id=>name,id=>name)
 9288: 
 9289: =item *
 9290: X<idrget()>
 9291: B<idrget($udom,@unames)>: find the IDs behind a list of
 9292: usernames (returns hash: name=>id,name=>id)
 9293: 
 9294: =item *
 9295: X<idput()>
 9296: B<idput($udom,%ids)>: store away a list of names and associated IDs
 9297: 
 9298: =item *
 9299: X<rolesinit()>
 9300: B<rolesinit($udom,$username,$authhost)>: get user privileges
 9301: 
 9302: =item *
 9303: X<getsection()>
 9304: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 9305: course $cname, return section name/number or '' for "not in course"
 9306: and '-1' for "no section"
 9307: 
 9308: =item *
 9309: X<userenvironment()>
 9310: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 9311: passed in @what from the requested user's environment, returns a hash
 9312: 
 9313: =item * 
 9314: X<userlog_query()>
 9315: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 9316: activity.log file. %filters defines filters applied when parsing the
 9317: log file. These can be start or end timestamps, or the type of action
 9318: - log to look for Login or Logout events, check for Checkin or
 9319: Checkout, role for role selection. The response is in the form
 9320: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 9321: escaped strings of the action recorded in the activity.log file.
 9322: 
 9323: =back
 9324: 
 9325: =head2 User Roles
 9326: 
 9327: =over 4
 9328: 
 9329: =item *
 9330: 
 9331: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 9332:  F: full access
 9333:  U,I,K: authentication modes (cxx only)
 9334:  '': forbidden
 9335:  1: user needs to choose course
 9336:  2: browse allowed
 9337:  A: passphrase authentication needed
 9338: 
 9339: =item *
 9340: 
 9341: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 9342: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 9343: and course level
 9344: 
 9345: =item *
 9346: 
 9347: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 9348: explanation of a user role term
 9349: 
 9350: =item *
 9351: 
 9352: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
 9353: All arguments are optional. Returns a hash of a roles, either for
 9354: co-author/assistant author roles for a user's Construction Space
 9355: (default), or if $context is 'userroles', roles for the user himself,
 9356: In the hash, keys are set to colon-separated $uname,$udom,$role, and
 9357: (optionally) if $withsec is true, a fourth colon-separated item - $section.
 9358: For each key, value is set to colon-separated start and end times for
 9359: the role.  If no username and domain are specified, will default to
 9360: current user/domain. Types, roles, and roledoms are references to arrays
 9361: of role statuses (active, future or previous), roles 
 9362: (e.g., cc,in, st etc.) and domains of the roles which can be used
 9363: to restrict the list of roles reported. If no array ref is 
 9364: provided for types, will default to return only active roles.
 9365: 
 9366: =back
 9367: 
 9368: =head2 User Modification
 9369: 
 9370: =over 4
 9371: 
 9372: =item *
 9373: 
 9374: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
 9375: user for the level given by URL.  Optional start and end dates (leave empty
 9376: string or zero for "no date")
 9377: 
 9378: =item *
 9379: 
 9380: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 9381: change a users, password, possible return values are: ok,
 9382: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 9383: refused
 9384: 
 9385: =item *
 9386: 
 9387: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 9388: 
 9389: =item *
 9390: 
 9391: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
 9392:            $forceid,$desiredhome,$email,$inststatus) : 
 9393: modify user
 9394: 
 9395: =item *
 9396: 
 9397: modifystudent
 9398: 
 9399: modify a student's enrollment and identification information.
 9400: The course id is resolved based on the current users environment.  
 9401: This means the envoking user must be a course coordinator or otherwise
 9402: associated with a course.
 9403: 
 9404: This call is essentially a wrapper for lonnet::modifyuser and
 9405: lonnet::modify_student_enrollment
 9406: 
 9407: Inputs: 
 9408: 
 9409: =over 4
 9410: 
 9411: =item B<$udom> Student's loncapa domain
 9412: 
 9413: =item B<$uname> Student's loncapa login name
 9414: 
 9415: =item B<$uid> Student/Employee ID
 9416: 
 9417: =item B<$umode> Student's authentication mode
 9418: 
 9419: =item B<$upass> Student's password
 9420: 
 9421: =item B<$first> Student's first name
 9422: 
 9423: =item B<$middle> Student's middle name
 9424: 
 9425: =item B<$last> Student's last name
 9426: 
 9427: =item B<$gene> Student's generation
 9428: 
 9429: =item B<$usec> Student's section in course
 9430: 
 9431: =item B<$end> Unix time of the roles expiration
 9432: 
 9433: =item B<$start> Unix time of the roles start date
 9434: 
 9435: =item B<$forceid> If defined, allow $uid to be changed
 9436: 
 9437: =item B<$desiredhome> server to use as home server for student
 9438: 
 9439: =item B<$email> Student's permanent e-mail address
 9440: 
 9441: =item B<$type> Type of enrollment (auto or manual)
 9442: 
 9443: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
 9444: 
 9445: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
 9446: 
 9447: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
 9448: 
 9449: =item B<$context> role change context (shown in User Management Logs display in a course)
 9450: 
 9451: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
 9452: 
 9453: =back
 9454: 
 9455: =item *
 9456: 
 9457: modify_student_enrollment
 9458: 
 9459: Change a students enrollment status in a class.  The environment variable
 9460: 'role.request.course' must be defined for this function to proceed.
 9461: 
 9462: Inputs:
 9463: 
 9464: =over 4
 9465: 
 9466: =item $udom, students domain
 9467: 
 9468: =item $uname, students name
 9469: 
 9470: =item $uid, students user id
 9471: 
 9472: =item $first, students first name
 9473: 
 9474: =item $middle
 9475: 
 9476: =item $last
 9477: 
 9478: =item $gene
 9479: 
 9480: =item $usec
 9481: 
 9482: =item $end
 9483: 
 9484: =item $start
 9485: 
 9486: =item $type
 9487: 
 9488: =item $locktype
 9489: 
 9490: =item $cid
 9491: 
 9492: =item $selfenroll
 9493: 
 9494: =item $context
 9495: 
 9496: =back
 9497: 
 9498: 
 9499: =item *
 9500: 
 9501: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 9502: custom role; give a custom role to a user for the level given by URL.  Specify
 9503: name and domain of role author, and role name
 9504: 
 9505: =item *
 9506: 
 9507: revokerole($udom,$uname,$url,$role) : revoke a role for url
 9508: 
 9509: =item *
 9510: 
 9511: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 9512: 
 9513: =back
 9514: 
 9515: =head2 Course Infomation
 9516: 
 9517: =over 4
 9518: 
 9519: =item *
 9520: 
 9521: coursedescription($courseid) : returns a hash of information about the
 9522: specified course id, including all environment settings for the
 9523: course, the description of the course will be in the hash under the
 9524: key 'description'
 9525: 
 9526: =item *
 9527: 
 9528: resdata($name,$domain,$type,@which) : request for current parameter
 9529: setting for a specific $type, where $type is either 'course' or 'user',
 9530: @what should be a list of parameters to ask about. This routine caches
 9531: answers for 5 minutes.
 9532: 
 9533: =item *
 9534: 
 9535: get_courseresdata($courseid, $domain) : dump the entire course resource
 9536: data base, returning a hash that is keyed by the resource name and has
 9537: values that are the resource value.  I believe that the timestamps and
 9538: versions are also returned.
 9539: 
 9540: 
 9541: =back
 9542: 
 9543: =head2 Course Modification
 9544: 
 9545: =over 4
 9546: 
 9547: =item *
 9548: 
 9549: writecoursepref($courseid,%prefs) : write preferences (environment
 9550: database) for a course
 9551: 
 9552: =item *
 9553: 
 9554: createcourse($udom,$description,$url) : make/modify course
 9555: 
 9556: =back
 9557: 
 9558: =head2 Resource Subroutines
 9559: 
 9560: =over 4
 9561: 
 9562: =item *
 9563: 
 9564: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 9565: 
 9566: =item *
 9567: 
 9568: repcopy($filename) : subscribes to the requested file, and attempts to
 9569: replicate from the owning library server, Might return
 9570: 'unavailable', 'not_found', 'forbidden', 'ok', or
 9571: 'bad_request', also attempts to grab the metadata for the
 9572: resource. Expects the local filesystem pathname
 9573: (/home/httpd/html/res/....)
 9574: 
 9575: =back
 9576: 
 9577: =head2 Resource Information
 9578: 
 9579: =over 4
 9580: 
 9581: =item *
 9582: 
 9583: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 9584: a vairety of different possible values, $varname should be a request
 9585: string, and the other parameters can be used to specify who and what
 9586: one is asking about.
 9587: 
 9588: Possible values for $varname are environment.lastname (or other item
 9589: from the envirnment hash), user.name (or someother aspect about the
 9590: user), resource.0.maxtries (or some other part and parameter of a
 9591: resource)
 9592: 
 9593: =item *
 9594: 
 9595: directcondval($number) : get current value of a condition; reads from a state
 9596: string
 9597: 
 9598: =item *
 9599: 
 9600: condval($condidx) : value of condition index based on state
 9601: 
 9602: =item *
 9603: 
 9604: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 9605: resource's metadata, $what should be either a specific key, or either
 9606: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 9607: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 9608: 
 9609: this function automatically caches all requests
 9610: 
 9611: =item *
 9612: 
 9613: metadata_query($query,$custom,$customshow) : make a metadata query against the
 9614: network of library servers; returns file handle of where SQL and regex results
 9615: will be stored for query
 9616: 
 9617: =item *
 9618: 
 9619: symbread($filename) : return symbolic list entry (filename argument optional);
 9620: returns the data handle
 9621: 
 9622: =item *
 9623: 
 9624: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 9625: a possible symb for the URL in $thisfn, and if is an encryypted
 9626: resource that the user accessed using /enc/ returns a 1 on success, 0
 9627: on failure, user must be in a course, as it assumes the existance of
 9628: the course initial hash, and uses $env('request.course.id'}
 9629: 
 9630: 
 9631: =item *
 9632: 
 9633: symbclean($symb) : removes versions numbers from a symb, returns the
 9634: cleaned symb
 9635: 
 9636: =item *
 9637: 
 9638: is_on_map($uri) : checks if the $uri is somewhere on the current
 9639: course map, user must be in a course for it to work.
 9640: 
 9641: =item *
 9642: 
 9643: numval($salt) : return random seed value (addend for rndseed)
 9644: 
 9645: =item *
 9646: 
 9647: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 9648: a random seed, all arguments are optional, if they aren't sent it uses the
 9649: environment to derive them. Note: if symb isn't sent and it can't get one
 9650: from &symbread it will use the current time as its return value
 9651: 
 9652: =item *
 9653: 
 9654: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 9655: unfakeable, receipt
 9656: 
 9657: =item *
 9658: 
 9659: receipt() : API to ireceipt working off of env values; given out to users
 9660: 
 9661: =item *
 9662: 
 9663: countacc($url) : count the number of accesses to a given URL
 9664: 
 9665: =item *
 9666: 
 9667: 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
 9668: 
 9669: =item *
 9670: 
 9671: 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)
 9672: 
 9673: =item *
 9674: 
 9675: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 9676: 
 9677: =item *
 9678: 
 9679: devalidate($symb) : devalidate temporary spreadsheet calculations,
 9680: forcing spreadsheet to reevaluate the resource scores next time.
 9681: 
 9682: =back
 9683: 
 9684: =head2 Storing/Retreiving Data
 9685: 
 9686: =over 4
 9687: 
 9688: =item *
 9689: 
 9690: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 9691: for this url; hashref needs to be given and should be a \%hashname; the
 9692: remaining args aren't required and if they aren't passed or are '' they will
 9693: be derived from the env
 9694: 
 9695: =item *
 9696: 
 9697: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 9698: uses critical subroutine
 9699: 
 9700: =item *
 9701: 
 9702: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 9703: all args are optional
 9704: 
 9705: =item *
 9706: 
 9707: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 9708: dumps the complete (or key matching regexp) namespace into a hash
 9709: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 9710: normally &store()ed into
 9711: 
 9712: $range should be either an integer '100' (give me the first 100
 9713:                                            matching records)
 9714:               or be  two integers sperated by a - with no spaces
 9715:                  '30-50' (give me the 30th through the 50th matching
 9716:                           records)
 9717: 
 9718: 
 9719: =item *
 9720: 
 9721: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 9722: replaces a &store() version of data with a replacement set of data
 9723: for a particular resource in a namespace passed in the $storehash hash 
 9724: reference
 9725: 
 9726: =item *
 9727: 
 9728: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 9729: works very similar to store/cstore, but all data is stored in a
 9730: temporary location and can be reset using tmpreset, $storehash should
 9731: be a hash reference, returns nothing on success
 9732: 
 9733: =item *
 9734: 
 9735: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 9736: similar to restore, but all data is stored in a temporary location and
 9737: can be reset using tmpreset. Returns a hash of values on success,
 9738: error string otherwise.
 9739: 
 9740: =item *
 9741: 
 9742: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 9743: deltes all keys for $symb form the temporary storage hash.
 9744: 
 9745: =item *
 9746: 
 9747: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9748: reference filled in from namesp ($udom and $uname are optional)
 9749: 
 9750: =item *
 9751: 
 9752: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 9753: namesp ($udom and $uname are optional)
 9754: 
 9755: =item *
 9756: 
 9757: dump($namespace,$udom,$uname,$regexp,$range) : 
 9758: dumps the complete (or key matching regexp) namespace into a hash
 9759: ($udom, $uname, $regexp, $range are optional)
 9760: 
 9761: $range should be either an integer '100' (give me the first 100
 9762:                                            matching records)
 9763:               or be  two integers sperated by a - with no spaces
 9764:                  '30-50' (give me the 30th through the 50th matching
 9765:                           records)
 9766: =item *
 9767: 
 9768: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 9769: $store can be a scalar, an array reference, or if the amount to be 
 9770: incremented is > 1, a hash reference.
 9771: 
 9772: ($udom and $uname are optional)
 9773: 
 9774: =item *
 9775: 
 9776: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 9777: ($udom and $uname are optional)
 9778: 
 9779: =item *
 9780: 
 9781: cput($namespace,$storehash,$udom,$uname) : critical put
 9782: ($udom and $uname are optional)
 9783: 
 9784: =item *
 9785: 
 9786: newput($namespace,$storehash,$udom,$uname) :
 9787: 
 9788: Attempts to store the items in the $storehash, but only if they don't
 9789: currently exist, if this succeeds you can be certain that you have 
 9790: successfully created a new key value pair in the $namespace db.
 9791: 
 9792: 
 9793: Args:
 9794:  $namespace: name of database to store values to
 9795:  $storehash: hashref to store to the db
 9796:  $udom: (optional) domain of user containing the db
 9797:  $uname: (optional) name of user caontaining the db
 9798: 
 9799: Returns:
 9800:  'ok' -> succeeded in storing all keys of $storehash
 9801:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 9802:                         least <key> already existed in the db (other
 9803:                         requested keys may also already exist)
 9804:  'error: <msg>' -> unable to tie the DB or other error occurred
 9805:  'con_lost' -> unable to contact request server
 9806:  'refused' -> action was not allowed by remote machine
 9807: 
 9808: 
 9809: =item *
 9810: 
 9811: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9812: reference filled in from namesp (encrypts the return communication)
 9813: ($udom and $uname are optional)
 9814: 
 9815: =item *
 9816: 
 9817: log($udom,$name,$home,$message) : write to permanent log for user; use
 9818: critical subroutine
 9819: 
 9820: =item *
 9821: 
 9822: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
 9823: array reference filled in from namespace found in domain level on either
 9824: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
 9825: 
 9826: =item *
 9827: 
 9828: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
 9829: domain level either on specified domain server ($uhome) or primary domain 
 9830: server ($udom and $uhome are optional)
 9831: 
 9832: =item * 
 9833: 
 9834: get_domain_defaults($target_domain) : returns hash with defaults for
 9835: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
 9836: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
 9837: or localauth), initial password or a kerberos realm, language (e.g., en-us).
 9838: Values are retrieved from cache (if current), or from domain's configuration.db
 9839: (if available), or lastly from values in lonTabs/dns_domain,tab, 
 9840: or lonTabs/domain.tab. 
 9841: 
 9842: %domdefaults = &get_auth_defaults($target_domain);
 9843: 
 9844: =back
 9845: 
 9846: =head2 Network Status Functions
 9847: 
 9848: =over 4
 9849: 
 9850: =item *
 9851: 
 9852: dirlist($uri) : return directory list based on URI
 9853: 
 9854: =item *
 9855: 
 9856: spareserver() : find server with least workload from spare.tab
 9857: 
 9858: =back
 9859: 
 9860: =head2 Apache Request
 9861: 
 9862: =over 4
 9863: 
 9864: =item *
 9865: 
 9866: ssi($url,%hash) : server side include, does a complete request cycle on url to
 9867: localhost, posts hash
 9868: 
 9869: =back
 9870: 
 9871: =head2 Data to String to Data
 9872: 
 9873: =over 4
 9874: 
 9875: =item *
 9876: 
 9877: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 9878: and '&' separators, supports elements that are arrayrefs and hashrefs
 9879: 
 9880: =item *
 9881: 
 9882: hashref2str($hashref) : convert a hashref into a string complete with
 9883: escaping and '=' and '&' separators, supports elements that are
 9884: arrayrefs and hashrefs
 9885: 
 9886: =item *
 9887: 
 9888: arrayref2str($arrayref) : convert an arrayref into a string complete
 9889: with escaping and '&' separators, supports elements that are arrayrefs
 9890: and hashrefs
 9891: 
 9892: =item *
 9893: 
 9894: str2hash($string) : convert string to hash using unescaping and
 9895: splitting on '=' and '&', supports elements that are arrayrefs and
 9896: hashrefs
 9897: 
 9898: =item *
 9899: 
 9900: str2array($string) : convert string to hash using unescaping and
 9901: splitting on '&', supports elements that are arrayrefs and hashrefs
 9902: 
 9903: =back
 9904: 
 9905: =head2 Logging Routines
 9906: 
 9907: =over 4
 9908: 
 9909: These routines allow one to make log messages in the lonnet.log and
 9910: lonnet.perm logfiles.
 9911: 
 9912: =item *
 9913: 
 9914: logtouch() : make sure the logfile, lonnet.log, exists
 9915: 
 9916: =item *
 9917: 
 9918: logthis() : append message to the normal lonnet.log file, it gets
 9919: preiodically rolled over and deleted.
 9920: 
 9921: =item *
 9922: 
 9923: logperm() : append a permanent message to lonnet.perm.log, this log
 9924: file never gets deleted by any automated portion of the system, only
 9925: messages of critical importance should go in here.
 9926: 
 9927: =back
 9928: 
 9929: =head2 General File Helper Routines
 9930: 
 9931: =over 4
 9932: 
 9933: =item *
 9934: 
 9935: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 9936: (a) files in /uploaded
 9937:   (i) If a local copy of the file exists - 
 9938:       compares modification date of local copy with last-modified date for 
 9939:       definitive version stored on home server for course. If local copy is 
 9940:       stale, requests a new version from the home server and stores it. 
 9941:       If the original has been removed from the home server, then local copy 
 9942:       is unlinked.
 9943:   (ii) If local copy does not exist -
 9944:       requests the file from the home server and stores it. 
 9945:   
 9946:   If $caller is 'uploadrep':  
 9947:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 9948:     for request for files originally uploaded via DOCS. 
 9949:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 9950:   
 9951:   Otherwise:
 9952:      This indicates a call from the content generation phase of the request.
 9953:      -  returns the entire contents of the file or -1.
 9954:      
 9955: (b) files in /res
 9956:    - returns the entire contents of a file or -1; 
 9957:    it properly subscribes to and replicates the file if neccessary.
 9958: 
 9959: 
 9960: =item *
 9961: 
 9962: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 9963:                   reference
 9964: 
 9965: returns either a stat() list of data about the file or an empty list
 9966: if the file doesn't exist or couldn't find out about it (connection
 9967: problems or user unknown)
 9968: 
 9969: =item *
 9970: 
 9971: filelocation($dir,$file) : returns file system location of a file
 9972: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 9973: directory that relative $file lookups are to looked in ($dir of /a/dir
 9974: and a file of ../bob will become /a/bob)
 9975: 
 9976: =item *
 9977: 
 9978: hreflocation($dir,$file) : returns file system location or a URL; same as
 9979: filelocation except for hrefs
 9980: 
 9981: =item *
 9982: 
 9983: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 9984: 
 9985: =back
 9986: 
 9987: =head2 Usererfile file routines (/uploaded*)
 9988: 
 9989: =over 4
 9990: 
 9991: =item *
 9992: 
 9993: userfileupload(): main rotine for putting a file in a user or course's
 9994:                   filespace, arguments are,
 9995: 
 9996:  formname - required - this is the name of the element in $env where the
 9997:            filename, and the contents of the file to create/modifed exist
 9998:            the filename is in $env{'form.'.$formname.'.filename'} and the
 9999:            contents of the file is located in $env{'form.'.$formname}
10000:  coursedoc - if true, store the file in the course of the active role
10001:              of the current user
10002:  subdir - required - subdirectory to put the file in under ../userfiles/
10003:          if undefined, it will be placed in "unknown"
10004: 
10005:  (This routine calls clean_filename() to remove any dangerous
10006:  characters from the filename, and then calls finuserfileupload() to
10007:  complete the transaction)
10008: 
10009:  returns either the url of the uploaded file (/uploaded/....) if successful
10010:  and /adm/notfound.html if unsuccessful
10011: 
10012: =item *
10013: 
10014: clean_filename(): routine for cleaing a filename up for storage in
10015:                  userfile space, argument is:
10016: 
10017:  filename - proposed filename
10018: 
10019: returns: the new clean filename
10020: 
10021: =item *
10022: 
10023: finishuserfileupload(): routine that creaes and sends the file to
10024: userspace, probably shouldn't be called directly
10025: 
10026:   docuname: username or courseid of destination for the file
10027:   docudom: domain of user/course of destination for the file
10028:   formname: same as for userfileupload()
10029:   fname: filename (inculding subdirectories) for the file
10030: 
10031:  returns either the url of the uploaded file (/uploaded/....) if successful
10032:  and /adm/notfound.html if unsuccessful
10033: 
10034: =item *
10035: 
10036: renameuserfile(): renames an existing userfile to a new name
10037: 
10038:   Args:
10039:    docuname: username or courseid of destination for the file
10040:    docudom: domain of user/course of destination for the file
10041:    old: current file name (including any subdirs under userfiles)
10042:    new: desired file name (including any subdirs under userfiles)
10043: 
10044: =item *
10045: 
10046: mkdiruserfile(): creates a directory is a userfiles dir
10047: 
10048:   Args:
10049:    docuname: username or courseid of destination for the file
10050:    docudom: domain of user/course of destination for the file
10051:    dir: dir to create (including any subdirs under userfiles)
10052: 
10053: =item *
10054: 
10055: removeuserfile(): removes a file that exists in userfiles
10056: 
10057:   Args:
10058:    docuname: username or courseid of destination for the file
10059:    docudom: domain of user/course of destination for the file
10060:    fname: filname to delete (including any subdirs under userfiles)
10061: 
10062: =item *
10063: 
10064: removeuploadedurl(): convience function for removeuserfile()
10065: 
10066:   Args:
10067:    url:  a full /uploaded/... url to delete
10068: 
10069: =item * 
10070: 
10071: get_portfile_permissions():
10072:   Args:
10073:     domain: domain of user or course contain the portfolio files
10074:     user: name of user or num of course contain the portfolio files
10075:   Returns:
10076:     hashref of a dump of the proper file_permissions.db
10077:    
10078: 
10079: =item * 
10080: 
10081: get_access_controls():
10082: 
10083: Args:
10084:   current_permissions: the hash ref returned from get_portfile_permissions()
10085:   group: (optional) the group you want the files associated with
10086:   file: (optional) the file you want access info on
10087: 
10088: Returns:
10089:     a hash (keys are file names) of hashes containing
10090:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10091:         values are XML containing access control settings (see below) 
10092: 
10093: Internal notes:
10094: 
10095:  access controls are stored in file_permissions.db as key=value pairs.
10096:     key -> path to file/file_name\0uniqueID:scope_end_start
10097:         where scope -> public,guest,course,group,domains or users.
10098:               end -> UNIX time for end of access (0 -> no end date)
10099:               start -> UNIX time for start of access
10100: 
10101:     value -> XML description of access control
10102:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10103:             <start></start>
10104:             <end></end>
10105: 
10106:             <password></password>  for scope type = guest
10107: 
10108:             <domain></domain>     for scope type = course or group
10109:             <number></number>
10110:             <roles id="">
10111:              <role></role>
10112:              <access></access>
10113:              <section></section>
10114:              <group></group>
10115:             </roles>
10116: 
10117:             <dom></dom>         for scope type = domains
10118: 
10119:             <users>             for scope type = users
10120:              <user>
10121:               <uname></uname>
10122:               <udom></udom>
10123:              </user>
10124:             </users>
10125:            </scope> 
10126:               
10127:  Access data is also aggregated for each file in an additional key=value pair:
10128:  key -> path to file/file_name\0accesscontrol 
10129:  value -> reference to hash
10130:           hash contains key = value pairs
10131:           where key = uniqueID:scope_end_start
10132:                 value = UNIX time record was last updated
10133: 
10134:           Used to improve speed of look-ups of access controls for each file.  
10135:  
10136:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10137: 
10138: modify_access_controls():
10139: 
10140: Modifies access controls for a portfolio file
10141: Args
10142: 1. file name
10143: 2. reference to hash of required changes,
10144: 3. domain
10145: 4. username
10146:   where domain,username are the domain of the portfolio owner 
10147:   (either a user or a course) 
10148: 
10149: Returns:
10150: 1. result of additions or updates ('ok' or 'error', with error message). 
10151: 2. result of deletions ('ok' or 'error', with error message).
10152: 3. reference to hash of any new or updated access controls.
10153: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10154:    key = integer (inbound ID)
10155:    value = uniqueID  
10156: 
10157: =back
10158: 
10159: =head2 HTTP Helper Routines
10160: 
10161: =over 4
10162: 
10163: =item *
10164: 
10165: escape() : unpack non-word characters into CGI-compatible hex codes
10166: 
10167: =item *
10168: 
10169: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10170: 
10171: =back
10172: 
10173: =head1 PRIVATE SUBROUTINES
10174: 
10175: =head2 Underlying communication routines (Shouldn't call)
10176: 
10177: =over 4
10178: 
10179: =item *
10180: 
10181: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10182: 
10183: =item *
10184: 
10185: reply() : uses subreply to send a message to remote machine, logs all failures
10186: 
10187: =item *
10188: 
10189: critical() : passes a critical message to another server; if cannot
10190: get through then place message in connection buffer directory and
10191: returns con_delayed, if incapable of saving message, returns
10192: con_failed
10193: 
10194: =item *
10195: 
10196: reconlonc() : tries to reconnect lonc client processes.
10197: 
10198: =back
10199: 
10200: =head2 Resource Access Logging
10201: 
10202: =over 4
10203: 
10204: =item *
10205: 
10206: flushcourselogs() : flush (save) buffer logs and access logs
10207: 
10208: =item *
10209: 
10210: courselog($what) : save message for course in hash
10211: 
10212: =item *
10213: 
10214: courseacclog($what) : save message for course using &courselog().  Perform
10215: special processing for specific resource types (problems, exams, quizzes, etc).
10216: 
10217: =item *
10218: 
10219: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10220: as a PerlChildExitHandler
10221: 
10222: =back
10223: 
10224: =head2 Other
10225: 
10226: =over 4
10227: 
10228: =item *
10229: 
10230: symblist($mapname,%newhash) : update symbolic storage links
10231: 
10232: =back
10233: 
10234: =cut
10235: 

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