File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.994: download - view: text, annotated - select for diffs
Sat Apr 11 21:43:02 2009 UTC (15 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Bug 5842.
 - "Edit this resource" link is displayed in inline menu if user is a DC in domain of resource author, and author has not blocked DC access to CSTR.
 - request for /priv/$author sets ad hoc co-author privs for user (if no existing privs) if user is a DC in author's CSTR, and if DC access is not blocked by author's user prefs.

&check_privs(), &set_privileges(), and &role_status() moved from lonroles.pm to lonnet.pm -- first two renamed as: check_adhoc_privs(), set_adhoc_privileges().

&is_active_dc() added to loncacc.pm to check if user has active DC role in resource author's domain.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.994 2009/04/11 21:43:02 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use LWP::UserAgent();
   75: use HTTP::Date;
   76: use Image::Magick;
   77: 
   78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   79:             $_64bit %env %protocol);
   80: 
   81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   82:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   83:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   84:     %courseownerbuf, %coursetypebuf,$locknum);
   85: 
   86: use IO::Socket;
   87: use GDBM_File;
   88: use HTML::LCParser;
   89: use Fcntl qw(:flock);
   90: use Storable qw(thaw nfreeze);
   91: use Time::HiRes qw( gettimeofday tv_interval );
   92: use Cache::Memcached;
   93: use Digest::MD5;
   94: use Math::Random;
   95: use LONCAPA qw(:DEFAULT :match);
   96: use LONCAPA::Configuration;
   97: 
   98: my $readit;
   99: my $max_connection_retries = 10;     # Or some such value.
  100: 
  101: my $upload_photo_form = 0; #Variable to check  when user upload a photo 0=not 1=true
  102: 
  103: require Exporter;
  104: 
  105: our @ISA = qw (Exporter);
  106: our @EXPORT = qw(%env);
  107: 
  108: 
  109: # --------------------------------------------------------------------- Logging
  110: {
  111:     my $logid;
  112:     sub instructor_log {
  113: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  114:         if (($cnum eq '') || ($cdom eq '')) {
  115:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  116:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  117:         }
  118: 	$logid++;
  119:         my $now = time();
  120: 	my $id=$now.'00000'.$$.'00000'.$logid;
  121: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  122: 				    { $id => {
  123: 					'exe_uname' => $env{'user.name'},
  124: 					'exe_udom'  => $env{'user.domain'},
  125: 					'exe_time'  => $now,
  126: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  127: 					'delflag'   => $delflag,
  128: 					'logentry'  => $storehash,
  129: 					'uname'     => $uname,
  130: 					'udom'      => $udom,
  131: 				    }
  132: 				  },$cdom,$cnum);
  133:     }
  134: }
  135: 
  136: sub logtouch {
  137:     my $execdir=$perlvar{'lonDaemons'};
  138:     unless (-e "$execdir/logs/lonnet.log") {	
  139: 	open(my $fh,">>$execdir/logs/lonnet.log");
  140: 	close $fh;
  141:     }
  142:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  143:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  144: }
  145: 
  146: sub logthis {
  147:     my $message=shift;
  148:     my $execdir=$perlvar{'lonDaemons'};
  149:     my $now=time;
  150:     my $local=localtime($now);
  151:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  152: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  153: 	print $fh $logstring;
  154: 	close($fh);
  155:     }
  156:     return 1;
  157: }
  158: 
  159: sub logperm {
  160:     my $message=shift;
  161:     my $execdir=$perlvar{'lonDaemons'};
  162:     my $now=time;
  163:     my $local=localtime($now);
  164:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  165: 	print $fh "$now:$message:$local\n";
  166: 	close($fh);
  167:     }
  168:     return 1;
  169: }
  170: 
  171: sub create_connection {
  172:     my ($hostname,$lonid) = @_;
  173:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  174: 				     Type    => SOCK_STREAM,
  175: 				     Timeout => 10);
  176:     return 0 if (!$client);
  177:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  178:     my $result = <$client>;
  179:     chomp($result);
  180:     return 1 if ($result eq 'done');
  181:     return 0;
  182: }
  183: 
  184: sub get_server_timezone {
  185:     my ($cnum,$cdom) = @_;
  186:     my $home=&homeserver($cnum,$cdom);
  187:     if ($home ne 'no_host') {
  188:         my $cachetime = 24*3600;
  189:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  190:         if (defined($cached)) {
  191:             return $timezone;
  192:         } else {
  193:             my $timezone = &reply('servertimezone',$home);
  194:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  195:         }
  196:     }
  197: }
  198: 
  199: sub get_server_loncaparev {
  200:     my ($dom,$lonhost) = @_;
  201:     if (defined($lonhost)) {
  202:         if (!defined(&hostname($lonhost))) {
  203:             undef($lonhost);
  204:         }
  205:     }
  206:     if (!defined($lonhost)) {
  207:         if (defined(&domain($dom,'primary'))) {
  208:             $lonhost=&domain($dom,'primary');
  209:             if ($lonhost eq 'no_host') {
  210:                 undef($lonhost);
  211:             }
  212:         }
  213:     }
  214:     if (defined($lonhost)) {
  215:         my $cachetime = 24*3600;
  216:         my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  217:         if (defined($cached)) {
  218:             return $loncaparev;
  219:         } else {
  220:             my $loncaparev = &reply('serverloncaparev',$lonhost);
  221:             return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  222:         }
  223:     }
  224: }
  225: 
  226: # -------------------------------------------------- Non-critical communication
  227: sub subreply {
  228:     my ($cmd,$server)=@_;
  229:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  230:     #
  231:     #  With loncnew process trimming, there's a timing hole between lonc server
  232:     #  process exit and the master server picking up the listen on the AF_UNIX
  233:     #  socket.  In that time interval, a lock file will exist:
  234: 
  235:     my $lockfile=$peerfile.".lock";
  236:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  237: 	sleep(1);
  238:     }
  239:     # At this point, either a loncnew parent is listening or an old lonc
  240:     # or loncnew child is listening so we can connect or everything's dead.
  241:     #
  242:     #   We'll give the connection a few tries before abandoning it.  If
  243:     #   connection is not possible, we'll con_lost back to the client.
  244:     #   
  245:     my $client;
  246:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  247: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  248: 				      Type    => SOCK_STREAM,
  249: 				      Timeout => 10);
  250: 	if ($client) {
  251: 	    last;		# Connected!
  252: 	} else {
  253: 	    &create_connection(&hostname($server),$server);
  254: 	}
  255:         sleep(1);		# Try again later if failed connection.
  256:     }
  257:     my $answer;
  258:     if ($client) {
  259: 	print $client "sethost:$server:$cmd\n";
  260: 	$answer=<$client>;
  261: 	if (!$answer) { $answer="con_lost"; }
  262: 	chomp($answer);
  263:     } else {
  264: 	$answer = 'con_lost';	# Failed connection.
  265:     }
  266:     return $answer;
  267: }
  268: 
  269: sub reply {
  270:     my ($cmd,$server)=@_;
  271:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  272:     my $answer=subreply($cmd,$server);
  273:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  274:        &logthis("<font color=\"blue\">WARNING:".
  275:                 " $cmd to $server returned $answer</font>");
  276:     }
  277:     return $answer;
  278: }
  279: 
  280: # ----------------------------------------------------------- Send USR1 to lonc
  281: 
  282: sub reconlonc {
  283:     my ($lonid) = @_;
  284:     my $hostname = &hostname($lonid);
  285:     if ($lonid) {
  286: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  287: 	if ($hostname && -e $peerfile) {
  288: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  289: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  290: 					     Type    => SOCK_STREAM,
  291: 					     Timeout => 10);
  292: 	    if ($client) {
  293: 		print $client ("reset_retries\n");
  294: 		my $answer=<$client>;
  295: 		#reset just this one.
  296: 	    }
  297: 	}
  298: 	return;
  299:     }
  300: 
  301:     &logthis("Trying to reconnect lonc");
  302:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  303:     if (open(my $fh,"<$loncfile")) {
  304: 	my $loncpid=<$fh>;
  305:         chomp($loncpid);
  306:         if (kill 0 => $loncpid) {
  307: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  308:             kill USR1 => $loncpid;
  309:             sleep 1;
  310:          } else {
  311: 	    &logthis(
  312:                "<font color=\"blue\">WARNING:".
  313:                " lonc at pid $loncpid not responding, giving up</font>");
  314:         }
  315:     } else {
  316: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  317:     }
  318: }
  319: 
  320: # ------------------------------------------------------ Critical communication
  321: 
  322: sub critical {
  323:     my ($cmd,$server)=@_;
  324:     unless (&hostname($server)) {
  325:         &logthis("<font color=\"blue\">WARNING:".
  326:                " Critical message to unknown server ($server)</font>");
  327:         return 'no_such_host';
  328:     }
  329:     my $answer=reply($cmd,$server);
  330:     if ($answer eq 'con_lost') {
  331: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  332: 	my $answer=reply($cmd,$server);
  333:         if ($answer eq 'con_lost') {
  334:             my $now=time;
  335:             my $middlename=$cmd;
  336:             $middlename=substr($middlename,0,16);
  337:             $middlename=~s/\W//g;
  338:             my $dfilename=
  339:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  340:             $dumpcount++;
  341:             {
  342: 		my $dfh;
  343: 		if (open($dfh,">$dfilename")) {
  344: 		    print $dfh "$cmd\n"; 
  345: 		    close($dfh);
  346: 		}
  347:             }
  348:             sleep 2;
  349:             my $wcmd='';
  350:             {
  351: 		my $dfh;
  352: 		if (open($dfh,"<$dfilename")) {
  353: 		    $wcmd=<$dfh>; 
  354: 		    close($dfh);
  355: 		}
  356:             }
  357:             chomp($wcmd);
  358:             if ($wcmd eq $cmd) {
  359: 		&logthis("<font color=\"blue\">WARNING: ".
  360:                          "Connection buffer $dfilename: $cmd</font>");
  361:                 &logperm("D:$server:$cmd");
  362: 	        return 'con_delayed';
  363:             } else {
  364:                 &logthis("<font color=\"red\">CRITICAL:"
  365:                         ." Critical connection failed: $server $cmd</font>");
  366:                 &logperm("F:$server:$cmd");
  367:                 return 'con_failed';
  368:             }
  369:         }
  370:     }
  371:     return $answer;
  372: }
  373: 
  374: # ------------------------------------------- check if return value is an error
  375: 
  376: sub error {
  377:     my ($result) = @_;
  378:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  379: 	if ($2 == 2) { return undef; }
  380: 	return $1;
  381:     }
  382:     return undef;
  383: }
  384: 
  385: sub convert_and_load_session_env {
  386:     my ($lonidsdir,$handle)=@_;
  387:     my @profile;
  388:     {
  389: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  390: 	if (!$opened) {
  391: 	    return 0;
  392: 	}
  393: 	flock($idf,LOCK_SH);
  394: 	@profile=<$idf>;
  395: 	close($idf);
  396:     }
  397:     my %temp_env;
  398:     foreach my $line (@profile) {
  399: 	if ($line !~ m/=/) {
  400: 	    return 0;
  401: 	}
  402: 	chomp($line);
  403: 	my ($envname,$envvalue)=split(/=/,$line,2);
  404: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  405:     }
  406:     unlink("$lonidsdir/$handle.id");
  407:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  408: 	    0640)) {
  409: 	%disk_env = %temp_env;
  410: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  411: 	untie(%disk_env);
  412:     }
  413:     return 1;
  414: }
  415: 
  416: # ------------------------------------------- Transfer profile into environment
  417: my $env_loaded;
  418: sub transfer_profile_to_env {
  419:     my ($lonidsdir,$handle,$force_transfer) = @_;
  420:     if (!$force_transfer && $env_loaded) { return; } 
  421: 
  422:     if (!defined($lonidsdir)) {
  423: 	$lonidsdir = $perlvar{'lonIDsDir'};
  424:     }
  425:     if (!defined($handle)) {
  426:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  427:     }
  428: 
  429:     my $convert;
  430:     {
  431:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  432: 	if (!$opened) {
  433: 	    return;
  434: 	}
  435: 	flock($idf,LOCK_SH);
  436: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  437: 		&GDBM_READER(),0640)) {
  438: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  439: 	    untie(%disk_env);
  440: 	} else {
  441: 	    $convert = 1;
  442: 	}
  443:     }
  444:     if ($convert) {
  445: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  446: 	    &logthis("Failed to load session, or convert session.");
  447: 	}
  448:     }
  449: 
  450:     my %remove;
  451:     while ( my $envname = each(%env) ) {
  452:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  453:             if ($time < time-300) {
  454:                 $remove{$key}++;
  455:             }
  456:         }
  457:     }
  458: 
  459:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  460:     $env_loaded=1;
  461:     foreach my $expired_key (keys(%remove)) {
  462:         &delenv($expired_key);
  463:     }
  464: }
  465: 
  466: # ---------------------------------------------------- Check for valid session 
  467: sub check_for_valid_session {
  468:     my ($r) = @_;
  469:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  470:     my $lonid=$cookies{'lonID'};
  471:     return undef if (!$lonid);
  472: 
  473:     my $handle=&LONCAPA::clean_handle($lonid->value);
  474:     my $lonidsdir=$r->dir_config('lonIDsDir');
  475:     return undef if (!-e "$lonidsdir/$handle.id");
  476: 
  477:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  478:     return undef if (!$opened);
  479: 
  480:     flock($idf,LOCK_SH);
  481:     my %disk_env;
  482:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  483: 	    &GDBM_READER(),0640)) {
  484: 	return undef;	
  485:     }
  486: 
  487:     if (!defined($disk_env{'user.name'})
  488: 	|| !defined($disk_env{'user.domain'})) {
  489: 	return undef;
  490:     }
  491:     return $handle;
  492: }
  493: 
  494: sub timed_flock {
  495:     my ($file,$lock_type) = @_;
  496:     my $failed=0;
  497:     eval {
  498: 	local $SIG{__DIE__}='DEFAULT';
  499: 	local $SIG{ALRM}=sub {
  500: 	    $failed=1;
  501: 	    die("failed lock");
  502: 	};
  503: 	alarm(13);
  504: 	flock($file,$lock_type);
  505: 	alarm(0);
  506:     };
  507:     if ($failed) {
  508: 	return undef;
  509:     } else {
  510: 	return 1;
  511:     }
  512: }
  513: 
  514: # ---------------------------------------------------------- Append Environment
  515: 
  516: sub appenv {
  517:     my ($newenv,$roles) = @_;
  518:     if (ref($newenv) eq 'HASH') {
  519:         foreach my $key (keys(%{$newenv})) {
  520:             my $refused = 0;
  521: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  522:                 $refused = 1;
  523:                 if (ref($roles) eq 'ARRAY') {
  524:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  525:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  526:                         $refused = 0;
  527:                     }
  528:                 }
  529:             }
  530:             if ($refused) {
  531:                 &logthis("<font color=\"blue\">WARNING: ".
  532:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  533:                          .'</font>');
  534: 	        delete($newenv->{$key});
  535:             } else {
  536:                 $env{$key}=$newenv->{$key};
  537:             }
  538:         }
  539:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  540:         if ($opened
  541: 	    && &timed_flock($env_file,LOCK_EX)
  542: 	    &&
  543: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  544: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  545: 	    while (my ($key,$value) = each(%{$newenv})) {
  546: 	        $disk_env{$key} = $value;
  547: 	    }
  548: 	    untie(%disk_env);
  549:         }
  550:     }
  551:     return 'ok';
  552: }
  553: # ----------------------------------------------------- Delete from Environment
  554: 
  555: sub delenv {
  556:     my ($delthis,$regexp) = @_;
  557:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  558:         &logthis("<font color=\"blue\">WARNING: ".
  559:                 "Attempt to delete from environment ".$delthis);
  560:         return 'error';
  561:     }
  562:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  563:     if ($opened
  564: 	&& &timed_flock($env_file,LOCK_EX)
  565: 	&&
  566: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  567: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  568: 	foreach my $key (keys(%disk_env)) {
  569: 	    if ($regexp) {
  570:                 if ($key=~/^$delthis/) {
  571:                     delete($env{$key});
  572:                     delete($disk_env{$key});
  573:                 } 
  574:             } else {
  575:                 if ($key=~/^\Q$delthis\E/) {
  576: 		    delete($env{$key});
  577: 		    delete($disk_env{$key});
  578: 	        }
  579:             }
  580: 	}
  581: 	untie(%disk_env);
  582:     }
  583:     return 'ok';
  584: }
  585: 
  586: sub get_env_multiple {
  587:     my ($name) = @_;
  588:     my @values;
  589:     if (defined($env{$name})) {
  590:         # exists is it an array
  591:         if (ref($env{$name})) {
  592:             @values=@{ $env{$name} };
  593:         } else {
  594:             $values[0]=$env{$name};
  595:         }
  596:     }
  597:     return(@values);
  598: }
  599: 
  600: # ------------------------------------------------------------------- Locking
  601: 
  602: sub set_lock {
  603:     my ($text)=@_;
  604:     $locknum++;
  605:     my $id=$$.'-'.$locknum;
  606:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  607:              'session.lock.'.$id => $text});
  608:     return $id;
  609: }
  610: 
  611: sub get_locks {
  612:     my $num=0;
  613:     my %texts=();
  614:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  615:        if ($lock=~/\w/) {
  616:           $num++;
  617:           $texts{$lock}=$env{'session.lock.'.$lock};
  618:        }
  619:    }
  620:    return ($num,%texts);
  621: }
  622: 
  623: sub remove_lock {
  624:     my ($id)=@_;
  625:     my $newlocks='';
  626:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  627:        if (($lock=~/\w/) && ($lock ne $id)) {
  628:           $newlocks.=','.$lock;
  629:        }
  630:     }
  631:     &appenv({'session.locks' => $newlocks});
  632:     &delenv('session.lock.'.$id);
  633: }
  634: 
  635: sub remove_all_locks {
  636:     my $activelocks=$env{'session.locks'};
  637:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  638:        if ($lock=~/\w/) {
  639:           &remove_lock($lock);
  640:        }
  641:     }
  642: }
  643: 
  644: 
  645: # ------------------------------------------ Find out current server userload
  646: sub userload {
  647:     my $numusers=0;
  648:     {
  649: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  650: 	my $filename;
  651: 	my $curtime=time;
  652: 	while ($filename=readdir(LONIDS)) {
  653: 	    next if ($filename eq '.' || $filename eq '..');
  654: 	    next if ($filename =~ /publicuser_\d+\.id/);
  655: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  656: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  657: 	}
  658: 	closedir(LONIDS);
  659:     }
  660:     my $userloadpercent=0;
  661:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  662:     if ($maxuserload) {
  663: 	$userloadpercent=100*$numusers/$maxuserload;
  664:     }
  665:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  666:     return $userloadpercent;
  667: }
  668: 
  669: # ------------------------------------------ Fight off request when overloaded
  670: 
  671: sub overloaderror {
  672:     my ($r,$checkserver)=@_;
  673:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  674:     my $loadavg;
  675:     if ($checkserver eq $perlvar{'lonHostID'}) {
  676:        open(my $loadfile,'/proc/loadavg');
  677:        $loadavg=<$loadfile>;
  678:        $loadavg =~ s/\s.*//g;
  679:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  680:        close($loadfile);
  681:     } else {
  682:        $loadavg=&reply('load',$checkserver);
  683:     }
  684:     my $overload=$loadavg-100;
  685:     if ($overload>0) {
  686: 	$r->err_headers_out->{'Retry-After'}=$overload;
  687:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  688:         return 413;
  689:     }    
  690:     return '';
  691: }
  692: 
  693: # ------------------------------ Find server with least workload from spare.tab
  694: 
  695: sub spareserver {
  696:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  697:     my $spare_server;
  698:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  699:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  700:                                                      :  $userloadpercent;
  701:     
  702:     foreach my $try_server (@{ $spareid{'primary'} }) {
  703: 	($spare_server, $lowest_load) =
  704: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  705:     }
  706: 
  707:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  708: 
  709:     if (!$found_server) {
  710: 	foreach my $try_server (@{ $spareid{'default'} }) {
  711: 	    ($spare_server, $lowest_load) =
  712: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  713: 	}
  714:     }
  715: 
  716:     if (!$want_server_name) {
  717:         my $protocol = 'http';
  718:         if ($protocol{$spare_server} eq 'https') {
  719:             $protocol = $protocol{$spare_server};
  720:         }
  721: 	$spare_server = $protocol.'://'.&hostname($spare_server);
  722:     }
  723:     return $spare_server;
  724: }
  725: 
  726: sub compare_server_load {
  727:     my ($try_server, $spare_server, $lowest_load) = @_;
  728: 
  729:     my $loadans     = &reply('load',    $try_server);
  730:     my $userloadans = &reply('userload',$try_server);
  731: 
  732:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  733: 	next; #didn't get a number from the server
  734:     }
  735: 
  736:     my $load;
  737:     if ($loadans =~ /\d/) {
  738: 	if ($userloadans =~ /\d/) {
  739: 	    #both are numbers, pick the bigger one
  740: 	    $load = ($loadans > $userloadans) ? $loadans 
  741: 		                              : $userloadans;
  742: 	} else {
  743: 	    $load = $loadans;
  744: 	}
  745:     } else {
  746: 	$load = $userloadans;
  747:     }
  748: 
  749:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  750: 	$spare_server = $try_server;
  751: 	$lowest_load  = $load;
  752:     }
  753:     return ($spare_server,$lowest_load);
  754: }
  755: 
  756: # --------------------------- ask offload servers if user already has a session
  757: sub find_existing_session {
  758:     my ($udom,$uname) = @_;
  759:     foreach my $try_server (@{ $spareid{'primary'} },
  760: 			    @{ $spareid{'default'} }) {
  761: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
  762:     }
  763:     return;
  764: }
  765: 
  766: # -------------------------------- ask if server already has a session for user
  767: sub has_user_session {
  768:     my ($lonid,$udom,$uname) = @_;
  769:     my $result = &reply(join(':','userhassession',
  770: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  771:     return 1 if ($result eq 'ok');
  772: 
  773:     return 0;
  774: }
  775: 
  776: # --------------------------------------------- Try to change a user's password
  777: 
  778: sub changepass {
  779:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  780:     $currentpass = &escape($currentpass);
  781:     $newpass     = &escape($newpass);
  782:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  783: 		       $server);
  784:     if (! $answer) {
  785: 	&logthis("No reply on password change request to $server ".
  786: 		 "by $uname in domain $udom.");
  787:     } elsif ($answer =~ "^ok") {
  788:         &logthis("$uname in $udom successfully changed their password ".
  789: 		 "on $server.");
  790:     } elsif ($answer =~ "^pwchange_failure") {
  791: 	&logthis("$uname in $udom was unable to change their password ".
  792: 		 "on $server.  The action was blocked by either lcpasswd ".
  793: 		 "or pwchange");
  794:     } elsif ($answer =~ "^non_authorized") {
  795:         &logthis("$uname in $udom did not get their password correct when ".
  796: 		 "attempting to change it on $server.");
  797:     } elsif ($answer =~ "^auth_mode_error") {
  798:         &logthis("$uname in $udom attempted to change their password despite ".
  799: 		 "not being locally or internally authenticated on $server.");
  800:     } elsif ($answer =~ "^unknown_user") {
  801:         &logthis("$uname in $udom attempted to change their password ".
  802: 		 "on $server but were unable to because $server is not ".
  803: 		 "their home server.");
  804:     } elsif ($answer =~ "^refused") {
  805: 	&logthis("$server refused to change $uname in $udom password because ".
  806: 		 "it was sent an unencrypted request to change the password.");
  807:     }
  808:     return $answer;
  809: }
  810: 
  811: # ----------------------- Try to determine user's current authentication scheme
  812: 
  813: sub queryauthenticate {
  814:     my ($uname,$udom)=@_;
  815:     my $uhome=&homeserver($uname,$udom);
  816:     if (!$uhome) {
  817: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  818: 	return 'no_host';
  819:     }
  820:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  821:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  822: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  823:     }
  824:     return $answer;
  825: }
  826: 
  827: # --------- Try to authenticate user from domain's lib servers (first this one)
  828: 
  829: sub authenticate {
  830:     my ($uname,$upass,$udom,$checkdefauth)=@_;
  831:     $upass=&escape($upass);
  832:     $uname= &LONCAPA::clean_username($uname);
  833:     my $uhome=&homeserver($uname,$udom,1);
  834:     my $newhome;
  835:     if ((!$uhome) || ($uhome eq 'no_host')) {
  836: # Maybe the machine was offline and only re-appeared again recently?
  837:         &reconlonc();
  838: # One more
  839: 	$uhome=&homeserver($uname,$udom,1);
  840:         if (($uhome eq 'no_host') && $checkdefauth) {
  841:             if (defined(&domain($udom,'primary'))) {
  842:                 $newhome=&domain($udom,'primary');
  843:             }
  844:             if ($newhome ne '') {
  845:                 $uhome = $newhome;
  846:             }
  847:         }
  848: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  849: 	    &logthis("User $uname at $udom is unknown in authenticate");
  850: 	    return 'no_host';
  851:         }
  852:     }
  853:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
  854:     if ($answer eq 'authorized') {
  855:         if ($newhome) {
  856:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
  857:             return 'no_account_on_host'; 
  858:         } else {
  859:             &logthis("User $uname at $udom authorized by $uhome");
  860:             return $uhome;
  861:         }
  862:     }
  863:     if ($answer eq 'non_authorized') {
  864: 	&logthis("User $uname at $udom rejected by $uhome");
  865: 	return 'no_host'; 
  866:     }
  867:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  868:     return 'no_host';
  869: }
  870: 
  871: # ---------------------- Find the homebase for a user from domain's lib servers
  872: 
  873: my %homecache;
  874: sub homeserver {
  875:     my ($uname,$udom,$ignoreBadCache)=@_;
  876:     my $index="$uname:$udom";
  877: 
  878:     if (exists($homecache{$index})) { return $homecache{$index}; }
  879: 
  880:     my %servers = &get_servers($udom,'library');
  881:     foreach my $tryserver (keys(%servers)) {
  882:         next if ($ignoreBadCache ne 'true' && 
  883: 		 exists($badServerCache{$tryserver}));
  884: 
  885: 	my $answer=reply("home:$udom:$uname",$tryserver);
  886: 	if ($answer eq 'found') {
  887: 	    delete($badServerCache{$tryserver}); 
  888: 	    return $homecache{$index}=$tryserver;
  889: 	} elsif ($answer eq 'no_host') {
  890: 	    $badServerCache{$tryserver}=1;
  891: 	}
  892:     }    
  893:     return 'no_host';
  894: }
  895: 
  896: # ------------------------------------- Find the usernames behind a list of IDs
  897: 
  898: sub idget {
  899:     my ($udom,@ids)=@_;
  900:     my %returnhash=();
  901:     
  902:     my %servers = &get_servers($udom,'library');
  903:     foreach my $tryserver (keys(%servers)) {
  904: 	my $idlist=join('&',@ids);
  905: 	$idlist=~tr/A-Z/a-z/; 
  906: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  907: 	my @answer=();
  908: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  909: 	    @answer=split(/\&/,$reply);
  910: 	}                    ;
  911: 	my $i;
  912: 	for ($i=0;$i<=$#ids;$i++) {
  913: 	    if ($answer[$i]) {
  914: 		$returnhash{$ids[$i]}=$answer[$i];
  915: 	    } 
  916: 	}
  917:     } 
  918:     return %returnhash;
  919: }
  920: 
  921: # ------------------------------------- Find the IDs behind a list of usernames
  922: 
  923: sub idrget {
  924:     my ($udom,@unames)=@_;
  925:     my %returnhash=();
  926:     foreach my $uname (@unames) {
  927:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  928:     }
  929:     return %returnhash;
  930: }
  931: 
  932: # ------------------------------- Store away a list of names and associated IDs
  933: 
  934: sub idput {
  935:     my ($udom,%ids)=@_;
  936:     my %servers=();
  937:     foreach my $uname (keys(%ids)) {
  938: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  939:         my $uhom=&homeserver($uname,$udom);
  940:         if ($uhom ne 'no_host') {
  941:             my $id=&escape($ids{$uname});
  942:             $id=~tr/A-Z/a-z/;
  943:             my $esc_unam=&escape($uname);
  944: 	    if ($servers{$uhom}) {
  945: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  946:             } else {
  947:                 $servers{$uhom}=$id.'='.$esc_unam;
  948:             }
  949:         }
  950:     }
  951:     foreach my $server (keys(%servers)) {
  952:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  953:     }
  954: }
  955: 
  956: # ------------------------------------------- get items from domain db files   
  957: 
  958: sub get_dom {
  959:     my ($namespace,$storearr,$udom,$uhome)=@_;
  960:     my $items='';
  961:     foreach my $item (@$storearr) {
  962:         $items.=&escape($item).'&';
  963:     }
  964:     $items=~s/\&$//;
  965:     if (!$udom) {
  966:         $udom=$env{'user.domain'};
  967:         if (defined(&domain($udom,'primary'))) {
  968:             $uhome=&domain($udom,'primary');
  969:         } else {
  970:             undef($uhome);
  971:         }
  972:     } else {
  973:         if (!$uhome) {
  974:             if (defined(&domain($udom,'primary'))) {
  975:                 $uhome=&domain($udom,'primary');
  976:             }
  977:         }
  978:     }
  979:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  980:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  981:         my %returnhash;
  982:         if ($rep eq '' || $rep =~ /^error: 2 /) {
  983:             return %returnhash;
  984:         }
  985:         my @pairs=split(/\&/,$rep);
  986:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  987:             return @pairs;
  988:         }
  989:         my $i=0;
  990:         foreach my $item (@$storearr) {
  991:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  992:             $i++;
  993:         }
  994:         return %returnhash;
  995:     } else {
  996:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
  997:     }
  998: }
  999: 
 1000: # -------------------------------------------- put items in domain db files 
 1001: 
 1002: sub put_dom {
 1003:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1004:     if (!$udom) {
 1005:         $udom=$env{'user.domain'};
 1006:         if (defined(&domain($udom,'primary'))) {
 1007:             $uhome=&domain($udom,'primary');
 1008:         } else {
 1009:             undef($uhome);
 1010:         }
 1011:     } else {
 1012:         if (!$uhome) {
 1013:             if (defined(&domain($udom,'primary'))) {
 1014:                 $uhome=&domain($udom,'primary');
 1015:             }
 1016:         }
 1017:     } 
 1018:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1019:         my $items='';
 1020:         foreach my $item (keys(%$storehash)) {
 1021:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1022:         }
 1023:         $items=~s/\&$//;
 1024:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1025:     } else {
 1026:         &logthis("put_dom failed - no homeserver and/or domain");
 1027:     }
 1028: }
 1029: 
 1030: sub retrieve_inst_usertypes {
 1031:     my ($udom) = @_;
 1032:     my (%returnhash,@order);
 1033:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1034:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1035:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1036:         %returnhash = %{$domdefs{'inststatustypes'}};
 1037:         @order = @{$domdefs{'inststatusorder'}};
 1038:     } else {
 1039:         if (defined(&domain($udom,'primary'))) {
 1040:             my $uhome=&domain($udom,'primary');
 1041:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1042:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1043:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1044:                 return (\%returnhash,\@order);
 1045:             }
 1046:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1047:             my @pairs=split(/\&/,$hashitems);
 1048:             foreach my $item (@pairs) {
 1049:                 my ($key,$value)=split(/=/,$item,2);
 1050:                 $key = &unescape($key);
 1051:                 next if ($key =~ /^error: 2 /);
 1052:                 $returnhash{$key}=&thaw_unescape($value);
 1053:             }
 1054:             my @esc_order = split(/\&/,$orderitems);
 1055:             foreach my $item (@esc_order) {
 1056:                 push(@order,&unescape($item));
 1057:             }
 1058:         } else {
 1059:             &logthis("get_dom failed - no primary domain server for $udom");
 1060:         }
 1061:     }
 1062:     return (\%returnhash,\@order);
 1063: }
 1064: 
 1065: sub is_domainimage {
 1066:     my ($url) = @_;
 1067:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1068:         if (&domain($1) ne '') {
 1069:             return '1';
 1070:         }
 1071:     }
 1072:     return;
 1073: }
 1074: 
 1075: sub inst_directory_query {
 1076:     my ($srch) = @_;
 1077:     my $udom = $srch->{'srchdomain'};
 1078:     my %results;
 1079:     my $homeserver = &domain($udom,'primary');
 1080:     my $outcome;
 1081:     if ($homeserver ne '') {
 1082: 	my $queryid=&reply("querysend:instdirsearch:".
 1083: 			   &escape($srch->{'srchby'}).':'.
 1084: 			   &escape($srch->{'srchterm'}).':'.
 1085: 			   &escape($srch->{'srchtype'}),$homeserver);
 1086: 	my $host=&hostname($homeserver);
 1087: 	if ($queryid !~/^\Q$host\E\_/) {
 1088: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1089: 	    return;
 1090: 	}
 1091: 	my $response = &get_query_reply($queryid);
 1092: 	my $maxtries = 5;
 1093: 	my $tries = 1;
 1094: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1095: 	    $response = &get_query_reply($queryid);
 1096: 	    $tries ++;
 1097: 	}
 1098: 
 1099:         if (!&error($response) && $response ne 'refused') {
 1100:             if ($response eq 'unavailable') {
 1101:                 $outcome = $response;
 1102:             } else {
 1103:                 $outcome = 'ok';
 1104:                 my @matches = split(/\n/,$response);
 1105:                 foreach my $match (@matches) {
 1106:                     my ($key,$value) = split(/=/,$match);
 1107:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1108:                 }
 1109:             }
 1110:         }
 1111:     }
 1112:     return ($outcome,%results);
 1113: }
 1114: 
 1115: sub usersearch {
 1116:     my ($srch) = @_;
 1117:     my $dom = $srch->{'srchdomain'};
 1118:     my %results;
 1119:     my %libserv = &all_library();
 1120:     my $query = 'usersearch';
 1121:     foreach my $tryserver (keys(%libserv)) {
 1122:         if (&host_domain($tryserver) eq $dom) {
 1123:             my $host=&hostname($tryserver);
 1124:             my $queryid=
 1125:                 &reply("querysend:".&escape($query).':'.
 1126:                        &escape($srch->{'srchby'}).':'.
 1127:                        &escape($srch->{'srchtype'}).':'.
 1128:                        &escape($srch->{'srchterm'}),$tryserver);
 1129:             if ($queryid !~/^\Q$host\E\_/) {
 1130:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1131:                 next;
 1132:             }
 1133:             my $reply = &get_query_reply($queryid);
 1134:             my $maxtries = 1;
 1135:             my $tries = 1;
 1136:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1137:                 $reply = &get_query_reply($queryid);
 1138:                 $tries ++;
 1139:             }
 1140:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1141:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1142:             } else {
 1143:                 my @matches;
 1144:                 if ($reply =~ /\n/) {
 1145:                     @matches = split(/\n/,$reply);
 1146:                 } else {
 1147:                     @matches = split(/\&/,$reply);
 1148:                 }
 1149:                 foreach my $match (@matches) {
 1150:                     my ($uname,$udom,%userhash);
 1151:                     foreach my $entry (split(/:/,$match)) {
 1152:                         my ($key,$value) =
 1153:                             map {&unescape($_);} split(/=/,$entry);
 1154:                         $userhash{$key} = $value;
 1155:                         if ($key eq 'username') {
 1156:                             $uname = $value;
 1157:                         } elsif ($key eq 'domain') {
 1158:                             $udom = $value;
 1159:                         }
 1160:                     }
 1161:                     $results{$uname.':'.$udom} = \%userhash;
 1162:                 }
 1163:             }
 1164:         }
 1165:     }
 1166:     return %results;
 1167: }
 1168: 
 1169: sub get_instuser {
 1170:     my ($udom,$uname,$id) = @_;
 1171:     my $homeserver = &domain($udom,'primary');
 1172:     my ($outcome,%results);
 1173:     if ($homeserver ne '') {
 1174:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1175:                            &escape($id).':'.&escape($udom),$homeserver);
 1176:         my $host=&hostname($homeserver);
 1177:         if ($queryid !~/^\Q$host\E\_/) {
 1178:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1179:             return;
 1180:         }
 1181:         my $response = &get_query_reply($queryid);
 1182:         my $maxtries = 5;
 1183:         my $tries = 1;
 1184:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1185:             $response = &get_query_reply($queryid);
 1186:             $tries ++;
 1187:         }
 1188:         if (!&error($response) && $response ne 'refused') {
 1189:             if ($response eq 'unavailable') {
 1190:                 $outcome = $response;
 1191:             } else {
 1192:                 $outcome = 'ok';
 1193:                 my @matches = split(/\n/,$response);
 1194:                 foreach my $match (@matches) {
 1195:                     my ($key,$value) = split(/=/,$match);
 1196:                     $results{&unescape($key)} = &thaw_unescape($value);
 1197:                 }
 1198:             }
 1199:         }
 1200:     }
 1201:     my %userinfo;
 1202:     if (ref($results{$uname}) eq 'HASH') {
 1203:         %userinfo = %{$results{$uname}};
 1204:     } 
 1205:     return ($outcome,%userinfo);
 1206: }
 1207: 
 1208: sub inst_rulecheck {
 1209:     my ($udom,$uname,$id,$item,$rules) = @_;
 1210:     my %returnhash;
 1211:     if ($udom ne '') {
 1212:         if (ref($rules) eq 'ARRAY') {
 1213:             @{$rules} = map {&escape($_);} (@{$rules});
 1214:             my $rulestr = join(':',@{$rules});
 1215:             my $homeserver=&domain($udom,'primary');
 1216:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1217:                 my $response;
 1218:                 if ($item eq 'username') {                
 1219:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1220:                                               ':'.&escape($uname).':'.$rulestr,
 1221:                                               $homeserver));
 1222:                 } elsif ($item eq 'id') {
 1223:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1224:                                               ':'.&escape($id).':'.$rulestr,
 1225:                                               $homeserver));
 1226:                 } elsif ($item eq 'selfcreate') {
 1227:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1228:                                                &escape($udom).':'.&escape($uname).
 1229:                                               ':'.$rulestr,$homeserver));
 1230:                 }
 1231:                 if ($response ne 'refused') {
 1232:                     my @pairs=split(/\&/,$response);
 1233:                     foreach my $item (@pairs) {
 1234:                         my ($key,$value)=split(/=/,$item,2);
 1235:                         $key = &unescape($key);
 1236:                         next if ($key =~ /^error: 2 /);
 1237:                         $returnhash{$key}=&thaw_unescape($value);
 1238:                     }
 1239:                 }
 1240:             }
 1241:         }
 1242:     }
 1243:     return %returnhash;
 1244: }
 1245: 
 1246: sub inst_userrules {
 1247:     my ($udom,$check) = @_;
 1248:     my (%ruleshash,@ruleorder);
 1249:     if ($udom ne '') {
 1250:         my $homeserver=&domain($udom,'primary');
 1251:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1252:             my $response;
 1253:             if ($check eq 'id') {
 1254:                 $response=&reply('instidrules:'.&escape($udom),
 1255:                                  $homeserver);
 1256:             } elsif ($check eq 'email') {
 1257:                 $response=&reply('instemailrules:'.&escape($udom),
 1258:                                  $homeserver);
 1259:             } else {
 1260:                 $response=&reply('instuserrules:'.&escape($udom),
 1261:                                  $homeserver);
 1262:             }
 1263:             if (($response ne 'refused') && ($response ne 'error') && 
 1264:                 ($response ne 'unknown_cmd') && 
 1265:                 ($response ne 'no_such_host')) {
 1266:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1267:                 my @pairs=split(/\&/,$hashitems);
 1268:                 foreach my $item (@pairs) {
 1269:                     my ($key,$value)=split(/=/,$item,2);
 1270:                     $key = &unescape($key);
 1271:                     next if ($key =~ /^error: 2 /);
 1272:                     $ruleshash{$key}=&thaw_unescape($value);
 1273:                 }
 1274:                 my @esc_order = split(/\&/,$orderitems);
 1275:                 foreach my $item (@esc_order) {
 1276:                     push(@ruleorder,&unescape($item));
 1277:                 }
 1278:             }
 1279:         }
 1280:     }
 1281:     return (\%ruleshash,\@ruleorder);
 1282: }
 1283: 
 1284: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1285: 
 1286: sub get_domain_defaults {
 1287:     my ($domain) = @_;
 1288:     my $cachetime = 60*60*24;
 1289:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1290:     if (defined($cached)) {
 1291:         if (ref($result) eq 'HASH') {
 1292:             return %{$result};
 1293:         }
 1294:     }
 1295:     my %domdefaults;
 1296:     my %domconfig =
 1297:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1298:                                   'requestcourses','inststatus'],$domain);
 1299:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1300:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1301:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1302:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1303:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1304:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1305:     } else {
 1306:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1307:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1308:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1309:     }
 1310:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1311:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1312:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1313:         } else {
 1314:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1315:         } 
 1316:         my @usertools = ('aboutme','blog','portfolio');
 1317:         foreach my $item (@usertools) {
 1318:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1319:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1320:             }
 1321:         }
 1322:     }
 1323:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1324:         foreach my $item ('official','unofficial') {
 1325:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1326:         }
 1327:     }
 1328:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 1329:         foreach my $item ('inststatustypes','inststatusorder') {
 1330:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 1331:         }
 1332:     }
 1333:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1334:                                   $cachetime);
 1335:     return %domdefaults;
 1336: }
 1337: 
 1338: # --------------------------------------------------- Assign a key to a student
 1339: 
 1340: sub assign_access_key {
 1341: #
 1342: # a valid key looks like uname:udom#comments
 1343: # comments are being appended
 1344: #
 1345:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1346:     $kdom=
 1347:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1348:     $knum=
 1349:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1350:     $cdom=
 1351:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1352:     $cnum=
 1353:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1354:     $udom=$env{'user.name'} unless (defined($udom));
 1355:     $uname=$env{'user.domain'} unless (defined($uname));
 1356:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1357:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1358:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1359:                                                   # assigned to this person
 1360:                                                   # - this should not happen,
 1361:                                                   # unless something went wrong
 1362:                                                   # the first time around
 1363: # ready to assign
 1364:         $logentry=$1.'; '.$logentry;
 1365:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1366:                                                  $kdom,$knum) eq 'ok') {
 1367: # key now belongs to user
 1368: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1369:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1370:                 &appenv({'environment.'.$envkey => $ckey});
 1371:                 return 'ok';
 1372:             } else {
 1373:                 return 
 1374:   'error: Count not permanently assign key, will need to be re-entered later.';
 1375: 	    }
 1376:         } else {
 1377:             return 'error: Could not assign key, try again later.';
 1378:         }
 1379:     } elsif (!$existing{$ckey}) {
 1380: # the key does not exist
 1381: 	return 'error: The key does not exist';
 1382:     } else {
 1383: # the key is somebody else's
 1384: 	return 'error: The key is already in use';
 1385:     }
 1386: }
 1387: 
 1388: # ------------------------------------------ put an additional comment on a key
 1389: 
 1390: sub comment_access_key {
 1391: #
 1392: # a valid key looks like uname:udom#comments
 1393: # comments are being appended
 1394: #
 1395:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1396:     $cdom=
 1397:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1398:     $cnum=
 1399:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1400:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1401:     if ($existing{$ckey}) {
 1402:         $existing{$ckey}.='; '.$logentry;
 1403: # ready to assign
 1404:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1405:                                                  $cdom,$cnum) eq 'ok') {
 1406: 	    return 'ok';
 1407:         } else {
 1408: 	    return 'error: Count not store comment.';
 1409:         }
 1410:     } else {
 1411: # the key does not exist
 1412: 	return 'error: The key does not exist';
 1413:     }
 1414: }
 1415: 
 1416: # ------------------------------------------------------ Generate a set of keys
 1417: 
 1418: sub generate_access_keys {
 1419:     my ($number,$cdom,$cnum,$logentry)=@_;
 1420:     $cdom=
 1421:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1422:     $cnum=
 1423:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1424:     unless (&allowed('mky',$cdom)) { return 0; }
 1425:     unless (($cdom) && ($cnum)) { return 0; }
 1426:     if ($number>10000) { return 0; }
 1427:     sleep(2); # make sure don't get same seed twice
 1428:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1429:     my $total=0;
 1430:     for (my $i=1;$i<=$number;$i++) {
 1431:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1432:                   sprintf("%lx",int(100000*rand)).'-'.
 1433:                   sprintf("%lx",int(100000*rand));
 1434:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1435:        $newkey=~s/0/h/g; # and also 0 and O
 1436:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1437:        if ($existing{$newkey}) {
 1438:            $i--;
 1439:        } else {
 1440: 	  if (&put('accesskeys',
 1441:               { $newkey => '# generated '.localtime().
 1442:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1443:                            '; '.$logentry },
 1444: 		   $cdom,$cnum) eq 'ok') {
 1445:               $total++;
 1446: 	  }
 1447:        }
 1448:     }
 1449:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1450:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1451:     return $total;
 1452: }
 1453: 
 1454: # ------------------------------------------------------- Validate an accesskey
 1455: 
 1456: sub validate_access_key {
 1457:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1458:     $cdom=
 1459:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1460:     $cnum=
 1461:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1462:     $udom=$env{'user.domain'} unless (defined($udom));
 1463:     $uname=$env{'user.name'} unless (defined($uname));
 1464:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1465:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1466: }
 1467: 
 1468: # ------------------------------------- Find the section of student in a course
 1469: sub devalidate_getsection_cache {
 1470:     my ($udom,$unam,$courseid)=@_;
 1471:     my $hashid="$udom:$unam:$courseid";
 1472:     &devalidate_cache_new('getsection',$hashid);
 1473: }
 1474: 
 1475: sub courseid_to_courseurl {
 1476:     my ($courseid) = @_;
 1477:     #already url style courseid
 1478:     return $courseid if ($courseid =~ m{^/});
 1479: 
 1480:     if (exists($env{'course.'.$courseid.'.num'})) {
 1481: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1482: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1483: 	return "/$cdom/$cnum";
 1484:     }
 1485: 
 1486:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1487:     if (exists($courseinfo{'num'})) {
 1488: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1489:     }
 1490: 
 1491:     return undef;
 1492: }
 1493: 
 1494: sub getsection {
 1495:     my ($udom,$unam,$courseid)=@_;
 1496:     my $cachetime=1800;
 1497: 
 1498:     my $hashid="$udom:$unam:$courseid";
 1499:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1500:     if (defined($cached)) { return $result; }
 1501: 
 1502:     my %Pending; 
 1503:     my %Expired;
 1504:     #
 1505:     # Each role can either have not started yet (pending), be active, 
 1506:     #    or have expired.
 1507:     #
 1508:     # If there is an active role, we are done.
 1509:     #
 1510:     # If there is more than one role which has not started yet, 
 1511:     #     choose the one which will start sooner
 1512:     # If there is one role which has not started yet, return it.
 1513:     #
 1514:     # If there is more than one expired role, choose the one which ended last.
 1515:     # If there is a role which has expired, return it.
 1516:     #
 1517:     $courseid = &courseid_to_courseurl($courseid);
 1518:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1519:     foreach my $key (keys(%roleshash)) {
 1520:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1521:         my $section=$1;
 1522:         if ($key eq $courseid.'_st') { $section=''; }
 1523:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1524:         my $now=time;
 1525:         if (defined($end) && $end && ($now > $end)) {
 1526:             $Expired{$end}=$section;
 1527:             next;
 1528:         }
 1529:         if (defined($start) && $start && ($now < $start)) {
 1530:             $Pending{$start}=$section;
 1531:             next;
 1532:         }
 1533:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1534:     }
 1535:     #
 1536:     # Presumedly there will be few matching roles from the above
 1537:     # loop and the sorting time will be negligible.
 1538:     if (scalar(keys(%Pending))) {
 1539:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1540:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1541:     } 
 1542:     if (scalar(keys(%Expired))) {
 1543:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1544:         my $time = pop(@sorted);
 1545:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1546:     }
 1547:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1548: }
 1549: 
 1550: sub save_cache {
 1551:     &purge_remembered();
 1552:     #&Apache::loncommon::validate_page();
 1553:     undef(%env);
 1554:     undef($env_loaded);
 1555: }
 1556: 
 1557: my $to_remember=-1;
 1558: my %remembered;
 1559: my %accessed;
 1560: my $kicks=0;
 1561: my $hits=0;
 1562: sub make_key {
 1563:     my ($name,$id) = @_;
 1564:     if (length($id) > 65 
 1565: 	&& length(&escape($id)) > 200) {
 1566: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1567:     }
 1568:     return &escape($name.':'.$id);
 1569: }
 1570: 
 1571: sub devalidate_cache_new {
 1572:     my ($name,$id,$debug) = @_;
 1573:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1574:     $id=&make_key($name,$id);
 1575:     $memcache->delete($id);
 1576:     delete($remembered{$id});
 1577:     delete($accessed{$id});
 1578: }
 1579: 
 1580: sub is_cached_new {
 1581:     my ($name,$id,$debug) = @_;
 1582:     $id=&make_key($name,$id);
 1583:     if (exists($remembered{$id})) {
 1584: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1585: 	$accessed{$id}=[&gettimeofday()];
 1586: 	$hits++;
 1587: 	return ($remembered{$id},1);
 1588:     }
 1589:     my $value = $memcache->get($id);
 1590:     if (!(defined($value))) {
 1591: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1592: 	return (undef,undef);
 1593:     }
 1594:     if ($value eq '__undef__') {
 1595: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1596: 	$value=undef;
 1597:     }
 1598:     &make_room($id,$value,$debug);
 1599:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1600:     return ($value,1);
 1601: }
 1602: 
 1603: sub do_cache_new {
 1604:     my ($name,$id,$value,$time,$debug) = @_;
 1605:     $id=&make_key($name,$id);
 1606:     my $setvalue=$value;
 1607:     if (!defined($setvalue)) {
 1608: 	$setvalue='__undef__';
 1609:     }
 1610:     if (!defined($time) ) {
 1611: 	$time=600;
 1612:     }
 1613:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1614:     my $result = $memcache->set($id,$setvalue,$time);
 1615:     if (! $result) {
 1616: 	&logthis("caching of id -> $id  failed");
 1617: 	$memcache->disconnect_all();
 1618:     }
 1619:     # need to make a copy of $value
 1620:     &make_room($id,$value,$debug);
 1621:     return $value;
 1622: }
 1623: 
 1624: sub make_room {
 1625:     my ($id,$value,$debug)=@_;
 1626: 
 1627:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1628:                                     : $value;
 1629:     if ($to_remember<0) { return; }
 1630:     $accessed{$id}=[&gettimeofday()];
 1631:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1632:     my $to_kick;
 1633:     my $max_time=0;
 1634:     foreach my $other (keys(%accessed)) {
 1635: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1636: 	    $to_kick=$other;
 1637: 	    $max_time=&tv_interval($accessed{$other});
 1638: 	}
 1639:     }
 1640:     delete($remembered{$to_kick});
 1641:     delete($accessed{$to_kick});
 1642:     $kicks++;
 1643:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1644:     return;
 1645: }
 1646: 
 1647: sub purge_remembered {
 1648:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1649:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1650:     undef(%remembered);
 1651:     undef(%accessed);
 1652: }
 1653: # ------------------------------------- Read an entry from a user's environment
 1654: 
 1655: sub userenvironment {
 1656:     my ($udom,$unam,@what)=@_;
 1657:     my $items;
 1658:     foreach my $item (@what) {
 1659:         $items.=&escape($item).'&';
 1660:     }
 1661:     $items=~s/\&$//;
 1662:     my %returnhash=();
 1663:     my @answer=split(/\&/,
 1664:                 &reply('get:'.$udom.':'.$unam.':environment:'.$items,
 1665:                       &homeserver($unam,$udom)));
 1666:     my $i;
 1667:     for ($i=0;$i<=$#what;$i++) {
 1668: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1669:     }
 1670:     return %returnhash;
 1671: }
 1672: 
 1673: # ---------------------------------------------------------- Get a studentphoto
 1674: sub studentphoto {
 1675:     my ($udom,$unam,$ext) = @_;
 1676:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1677:     if (defined($env{'request.course.id'})) {
 1678:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1679:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1680:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1681:             } else {
 1682:                 my ($result,$perm_reqd)=
 1683: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1684:                 if ($result eq 'ok') {
 1685:                     if (!($perm_reqd eq 'yes')) {
 1686:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1687:                     }
 1688:                 }
 1689:             }
 1690:         }
 1691:     } else {
 1692:         my ($result,$perm_reqd) = 
 1693: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1694:         if ($result eq 'ok') {
 1695:             if (!($perm_reqd eq 'yes')) {
 1696:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1697:             }
 1698:         }
 1699:     }
 1700:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1701: }
 1702: 
 1703: sub retrievestudentphoto {
 1704:     my ($udom,$unam,$ext,$type) = @_;
 1705:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1706:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1707:     if ($ret eq 'ok') {
 1708:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1709:         if ($type eq 'thumbnail') {
 1710:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1711:         }
 1712:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1713:         return $tokenurl;
 1714:     } else {
 1715:         if ($type eq 'thumbnail') {
 1716:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1717:         } else { 
 1718:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1719:         }
 1720:     }
 1721: }
 1722: 
 1723: # -------------------------------------------------------------------- New chat
 1724: 
 1725: sub chatsend {
 1726:     my ($newentry,$anon,$group)=@_;
 1727:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1728:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1729:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1730:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1731: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1732: 		   &escape($newentry)).':'.$group,$chome);
 1733: }
 1734: 
 1735: # ------------------------------------------ Find current version of a resource
 1736: 
 1737: sub getversion {
 1738:     my $fname=&clutter(shift);
 1739:     unless ($fname=~/^\/res\//) { return -1; }
 1740:     return &currentversion(&filelocation('',$fname));
 1741: }
 1742: 
 1743: sub currentversion {
 1744:     my $fname=shift;
 1745:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1746:     if (defined($cached)) { return $result; }
 1747:     my $author=$fname;
 1748:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1749:     my ($udom,$uname)=split(/\//,$author);
 1750:     my $home=homeserver($uname,$udom);
 1751:     if ($home eq 'no_host') { 
 1752:         return -1; 
 1753:     }
 1754:     my $answer=reply("currentversion:$fname",$home);
 1755:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1756: 	return -1;
 1757:     }
 1758:     return &do_cache_new('resversion',$fname,$answer,600);
 1759: }
 1760: 
 1761: # ----------------------------- Subscribe to a resource, return URL if possible
 1762: 
 1763: sub subscribe {
 1764:     my $fname=shift;
 1765:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1766:     $fname=~s/[\n\r]//g;
 1767:     my $author=$fname;
 1768:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1769:     my ($udom,$uname)=split(/\//,$author);
 1770:     my $home=homeserver($uname,$udom);
 1771:     if ($home eq 'no_host') {
 1772:         return 'not_found';
 1773:     }
 1774:     my $answer=reply("sub:$fname",$home);
 1775:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1776: 	$answer.=' by '.$home;
 1777:     }
 1778:     return $answer;
 1779: }
 1780:     
 1781: # -------------------------------------------------------------- Replicate file
 1782: 
 1783: sub repcopy {
 1784:     my $filename=shift;
 1785:     $filename=~s/\/+/\//g;
 1786:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1787:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1788:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1789: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1790: 	return &repcopy_userfile($filename);
 1791:     }
 1792:     $filename=~s/[\n\r]//g;
 1793:     my $transname="$filename.in.transfer";
 1794: # FIXME: this should flock
 1795:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1796:     my $remoteurl=subscribe($filename);
 1797:     if ($remoteurl =~ /^con_lost by/) {
 1798: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1799:            return 'unavailable';
 1800:     } elsif ($remoteurl eq 'not_found') {
 1801: 	   #&logthis("Subscribe returned not_found: $filename");
 1802: 	   return 'not_found';
 1803:     } elsif ($remoteurl =~ /^rejected by/) {
 1804: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1805:            return 'forbidden';
 1806:     } elsif ($remoteurl eq 'directory') {
 1807:            return 'ok';
 1808:     } else {
 1809:         my $author=$filename;
 1810:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1811:         my ($udom,$uname)=split(/\//,$author);
 1812:         my $home=homeserver($uname,$udom);
 1813:         unless ($home eq $perlvar{'lonHostID'}) {
 1814:            my @parts=split(/\//,$filename);
 1815:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1816:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1817:                &logthis("Malconfiguration for replication: $filename");
 1818: 	       return 'bad_request';
 1819:            }
 1820:            my $count;
 1821:            for ($count=5;$count<$#parts;$count++) {
 1822:                $path.="/$parts[$count]";
 1823:                if ((-e $path)!=1) {
 1824: 		   mkdir($path,0777);
 1825:                }
 1826:            }
 1827:            my $ua=new LWP::UserAgent;
 1828:            my $request=new HTTP::Request('GET',"$remoteurl");
 1829:            my $response=$ua->request($request,$transname);
 1830:            if ($response->is_error()) {
 1831: 	       unlink($transname);
 1832:                my $message=$response->status_line;
 1833:                &logthis("<font color=\"blue\">WARNING:"
 1834:                        ." LWP get: $message: $filename</font>");
 1835:                return 'unavailable';
 1836:            } else {
 1837: 	       if ($remoteurl!~/\.meta$/) {
 1838:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1839:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1840:                   if ($mresponse->is_error()) {
 1841: 		      unlink($filename.'.meta');
 1842:                       &logthis(
 1843:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1844:                   }
 1845: 	       }
 1846:                rename($transname,$filename);
 1847:                return 'ok';
 1848:            }
 1849:        }
 1850:     }
 1851: }
 1852: 
 1853: # ------------------------------------------------ Get server side include body
 1854: sub ssi_body {
 1855:     my ($filelink,%form)=@_;
 1856:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1857:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1858:     }
 1859:     my $output='';
 1860:     my $response;
 1861:     if ($filelink=~/^https?\:/) {
 1862:        ($output,$response)=&externalssi($filelink);
 1863:     } else {
 1864:        ($output,$response)=&ssi($filelink,%form);
 1865:     }
 1866:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1867:     $output=~s/^.*?\<body[^\>]*\>//si;
 1868:     $output=~s/\<\/body\s*\>.*?$//si;
 1869:     if (wantarray) {
 1870:         return ($output, $response);
 1871:     } else {
 1872:         return $output;
 1873:     }
 1874: }
 1875: 
 1876: # --------------------------------------------------------- Server Side Include
 1877: 
 1878: sub absolute_url {
 1879:     my ($host_name) = @_;
 1880:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1881:     if ($host_name eq '') {
 1882: 	$host_name = $ENV{'SERVER_NAME'};
 1883:     }
 1884:     return $protocol.$host_name;
 1885: }
 1886: 
 1887: #
 1888: #   Server side include.
 1889: # Parameters:
 1890: #  fn     Possibly encrypted resource name/id.
 1891: #  form   Hash that describes how the rendering should be done
 1892: #         and other things.
 1893: # Returns:
 1894: #   Scalar context: The content of the response.
 1895: #   Array context:  2 element list of the content and the full response object.
 1896: #     
 1897: sub ssi {
 1898: 
 1899:     my ($fn,%form)=@_;
 1900:     my $ua=new LWP::UserAgent;
 1901:     my $request;
 1902: 
 1903:     $form{'no_update_last_known'}=1;
 1904:     &Apache::lonenc::check_encrypt(\$fn);
 1905:     if (%form) {
 1906:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1907:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1908:     } else {
 1909:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1910:     }
 1911: 
 1912:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1913:     my $response=$ua->request($request);
 1914: 
 1915:     if (wantarray) {
 1916: 	return ($response->content, $response);
 1917:     } else {
 1918: 	return $response->content;
 1919:     }
 1920: }
 1921: 
 1922: sub externalssi {
 1923:     my ($url)=@_;
 1924:     my $ua=new LWP::UserAgent;
 1925:     my $request=new HTTP::Request('GET',$url);
 1926:     my $response=$ua->request($request);
 1927:     if (wantarray) {
 1928:         return ($response->content, $response);
 1929:     } else {
 1930:         return $response->content;
 1931:     }
 1932: }
 1933: 
 1934: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1935: 
 1936: sub allowuploaded {
 1937:     my ($srcurl,$url)=@_;
 1938:     $url=&clutter(&declutter($url));
 1939:     my $dir=$url;
 1940:     $dir=~s/\/[^\/]+$//;
 1941:     my %httpref=();
 1942:     my $httpurl=&hreflocation('',$url);
 1943:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1944:     &Apache::lonnet::appenv(\%httpref);
 1945: }
 1946: 
 1947: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1948: # input: action, courseID, current domain, intended
 1949: #        path to file, source of file, instruction to parse file for objects,
 1950: #        ref to hash for embedded objects,
 1951: #        ref to hash for codebase of java objects.
 1952: #
 1953: # output: url to file (if action was uploaddoc), 
 1954: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1955: #
 1956: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1957: # course.
 1958: #
 1959: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1960: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1961: #          course's home server.
 1962: #
 1963: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1964: #          be copied from $source (current location) to 
 1965: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1966: #         and will then be copied to
 1967: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1968: #         course's home server.
 1969: #
 1970: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1971: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1972: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1973: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1974: #         in course's home server.
 1975: #
 1976: 
 1977: sub process_coursefile {
 1978:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1979:     my $fetchresult;
 1980:     my $home=&homeserver($docuname,$docudom);
 1981:     if ($action eq 'propagate') {
 1982:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1983: 			     $home);
 1984:     } else {
 1985:         my $fpath = '';
 1986:         my $fname = $file;
 1987:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1988:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1989:         my $filepath = &build_filepath($fpath);
 1990:         if ($action eq 'copy') {
 1991:             if ($source eq '') {
 1992:                 $fetchresult = 'no source file';
 1993:                 return $fetchresult;
 1994:             } else {
 1995:                 my $destination = $filepath.'/'.$fname;
 1996:                 rename($source,$destination);
 1997:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1998:                                  $home);
 1999:             }
 2000:         } elsif ($action eq 'uploaddoc') {
 2001:             open(my $fh,'>'.$filepath.'/'.$fname);
 2002:             print $fh $env{'form.'.$source};
 2003:             close($fh);
 2004:             if ($parser eq 'parse') {
 2005:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2006:                 unless ($parse_result eq 'ok') {
 2007:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2008:                 }
 2009:             }
 2010:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2011:                                  $home);
 2012:             if ($fetchresult eq 'ok') {
 2013:                 return '/uploaded/'.$fpath.'/'.$fname;
 2014:             } else {
 2015:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2016:                         ' to host '.$home.': '.$fetchresult);
 2017:                 return '/adm/notfound.html';
 2018:             }
 2019:         }
 2020:     }
 2021:     unless ( $fetchresult eq 'ok') {
 2022:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2023:              ' to host '.$home.': '.$fetchresult);
 2024:     }
 2025:     return $fetchresult;
 2026: }
 2027: 
 2028: sub build_filepath {
 2029:     my ($fpath) = @_;
 2030:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2031:     unless ($fpath eq '') {
 2032:         my @parts=split('/',$fpath);
 2033:         foreach my $part (@parts) {
 2034:             $filepath.= '/'.$part;
 2035:             if ((-e $filepath)!=1) {
 2036:                 mkdir($filepath,0777);
 2037:             }
 2038:         }
 2039:     }
 2040:     return $filepath;
 2041: }
 2042: 
 2043: sub store_edited_file {
 2044:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2045:     my $file = $primary_url;
 2046:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2047:     my $fpath = '';
 2048:     my $fname = $file;
 2049:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2050:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2051:     my $filepath = &build_filepath($fpath);
 2052:     open(my $fh,'>'.$filepath.'/'.$fname);
 2053:     print $fh $content;
 2054:     close($fh);
 2055:     my $home=&homeserver($docuname,$docudom);
 2056:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2057: 			  $home);
 2058:     if ($$fetchresult eq 'ok') {
 2059:         return '/uploaded/'.$fpath.'/'.$fname;
 2060:     } else {
 2061:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2062: 		 ' to host '.$home.': '.$$fetchresult);
 2063:         return '/adm/notfound.html';
 2064:     }
 2065: }
 2066: 
 2067: sub clean_filename {
 2068:     my ($fname,$args)=@_;
 2069: # Replace Windows backslashes by forward slashes
 2070:     $fname=~s/\\/\//g;
 2071:     if (!$args->{'keep_path'}) {
 2072:         # Get rid of everything but the actual filename
 2073: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2074:     }
 2075: # Replace spaces by underscores
 2076:     $fname=~s/\s+/\_/g;
 2077: # Replace all other weird characters by nothing
 2078:     $fname=~s{[^/\w\.\-]}{}g;
 2079: # Replace all .\d. sequences with _\d. so they no longer look like version
 2080: # numbers
 2081:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2082:     return $fname;
 2083: }
 2084: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
 2085: sub resizeImage {
 2086: 	my($img_url) = @_;	
 2087: 	my $ima = Image::Magick->new;                       
 2088:         $ima->Read($img_url);
 2089: 	if($ima->Get('width') > 400)
 2090: 	{
 2091: 		my $factor = $ima->Get('width')/400;
 2092:              	$ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
 2093: 	}
 2094: 	if($ima->Get('height') > 500)
 2095:         {
 2096:         	my $factor = $ima->Get('height')/500;
 2097:                 $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
 2098:         } 
 2099: 		
 2100: 	$ima->Write($img_url);
 2101: }
 2102: 
 2103: #Wrapper function for userphotoupload
 2104: sub userphotoupload
 2105: {
 2106: 	my($formname,$subdir) = @_;
 2107: 	$upload_photo_form = 1;
 2108: 	return &userfileupload($formname,undef,$subdir);
 2109: }
 2110: 
 2111: # --------------- Take an uploaded file and put it into the userfiles directory
 2112: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2113: #                    the desired filenam is in $env{"form.$formname.filename"}
 2114: #        $coursedoc - if true up to the current course
 2115: #                     if false
 2116: #        $subdir - directory in userfile to store the file into
 2117: #        $parser - instruction to parse file for objects ($parser = parse)    
 2118: #        $allfiles - reference to hash for embedded objects
 2119: #        $codebase - reference to hash for codebase of java objects
 2120: #        $desuname - username for permanent storage of uploaded file
 2121: #        $dsetudom - domain for permanaent storage of uploaded file
 2122: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2123: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2124: # 
 2125: # output: url of file in userspace, or error: <message> 
 2126: #             or /adm/notfound.html if failure to upload occurse
 2127: 
 2128: 
 2129: sub userfileupload {
 2130:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 2131:         $destudom,$thumbwidth,$thumbheight)=@_;
 2132:     if (!defined($subdir)) { $subdir='unknown'; }
 2133:     my $fname=$env{'form.'.$formname.'.filename'};
 2134:     $fname=&clean_filename($fname);
 2135: # See if there is anything left
 2136:     unless ($fname) { return 'error: no uploaded file'; }
 2137:     chop($env{'form.'.$formname});
 2138:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 2139:         my $now = time;
 2140:         my $filepath = 'tmp/helprequests/'.$now;
 2141:         my @parts=split(/\//,$filepath);
 2142:         my $fullpath = $perlvar{'lonDaemons'};
 2143:         for (my $i=0;$i<@parts;$i++) {
 2144:             $fullpath .= '/'.$parts[$i];
 2145:             if ((-e $fullpath)!=1) {
 2146:                 mkdir($fullpath,0777);
 2147:             }
 2148:         }
 2149:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2150:         print $fh $env{'form.'.$formname};
 2151:         close($fh);
 2152:         return $fullpath.'/'.$fname;
 2153:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 2154:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2155:                        '_'.$env{'user.domain'}.'/pending';
 2156:         my @parts=split(/\//,$filepath);
 2157:         my $fullpath = $perlvar{'lonDaemons'};
 2158:         for (my $i=0;$i<@parts;$i++) {
 2159:             $fullpath .= '/'.$parts[$i];
 2160:             if ((-e $fullpath)!=1) {
 2161:                 mkdir($fullpath,0777);
 2162:             }
 2163:         }
 2164:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2165:         print $fh $env{'form.'.$formname};
 2166:         close($fh);
 2167:         return $fullpath.'/'.$fname;
 2168:     }
 2169:     
 2170: # Create the directory if not present
 2171:     $fname="$subdir/$fname";
 2172:     if ($coursedoc) {
 2173: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2174: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2175:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2176:             return &finishuserfileupload($docuname,$docudom,
 2177: 					 $formname,$fname,$parser,$allfiles,
 2178: 					 $codebase,$thumbwidth,$thumbheight);
 2179:         } else {
 2180:             $fname=$env{'form.folder'}.'/'.$fname;
 2181:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2182: 				       $fname,$formname,$parser,
 2183: 				       $allfiles,$codebase);
 2184:         }
 2185:     } elsif (defined($destuname)) {
 2186:         my $docuname=$destuname;
 2187:         my $docudom=$destudom;
 2188: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2189: 				     $parser,$allfiles,$codebase,
 2190:                                      $thumbwidth,$thumbheight);
 2191:         
 2192:     } else {
 2193:         my $docuname=$env{'user.name'};
 2194:         my $docudom=$env{'user.domain'};
 2195:         if (exists($env{'form.group'})) {
 2196:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2197:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2198:         }
 2199: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2200: 				     $parser,$allfiles,$codebase,
 2201:                                      $thumbwidth,$thumbheight);
 2202:     }
 2203: }
 2204: 
 2205: sub finishuserfileupload {
 2206:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2207:         $thumbwidth,$thumbheight) = @_;
 2208:     my $path=$docudom.'/'.$docuname.'/';
 2209:     my $filepath=$perlvar{'lonDocRoot'};
 2210:   
 2211:     my ($fnamepath,$file,$fetchthumb);
 2212:     $file=$fname;
 2213:     if ($fname=~m|/|) {
 2214:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2215: 	$path.=$fnamepath.'/';
 2216:     }
 2217:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2218:     my $count;
 2219:     for ($count=4;$count<=$#parts;$count++) {
 2220:         $filepath.="/$parts[$count]";
 2221:         if ((-e $filepath)!=1) {
 2222: 	    mkdir($filepath,0777);
 2223:         }
 2224:     }
 2225: 
 2226: # Save the file
 2227:     {
 2228: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2229: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2230: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2231: 	    return '/adm/notfound.html';
 2232: 	}
 2233: 	if (!print FH ($env{'form.'.$formname})) {
 2234: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2235: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2236: 	    return '/adm/notfound.html';
 2237: 	}
 2238: 	close(FH);
 2239: 	if($upload_photo_form==1)
 2240: 	{
 2241: 		resizeImage($filepath.'/'.$file);		
 2242: 		$upload_photo_form = 0;
 2243: 	}
 2244:     }
 2245:     if ($parser eq 'parse') {
 2246:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
 2247: 						   $codebase);
 2248:         unless ($parse_result eq 'ok') {
 2249:             &logthis('Failed to parse '.$filepath.$file.
 2250: 		     ' for embedded media: '.$parse_result); 
 2251:         }
 2252:     }
 2253:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2254:         my $input = $filepath.'/'.$file;
 2255:         my $output = $filepath.'/'.'tn-'.$file;
 2256:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2257:         system("convert -sample $thumbsize $input $output");
 2258:         if (-e $filepath.'/'.'tn-'.$file) {
 2259:             $fetchthumb  = 1; 
 2260:         }
 2261:     }
 2262:  
 2263: # Notify homeserver to grep it
 2264: #
 2265:     my $docuhome=&homeserver($docuname,$docudom);	
 2266:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2267:     if ($fetchresult eq 'ok') {
 2268:         if ($fetchthumb) {
 2269:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2270:             if ($thumbresult ne 'ok') {
 2271:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2272:                          $docuhome.': '.$thumbresult);
 2273:             }
 2274:         }
 2275: #
 2276: # Return the URL to it
 2277:         return '/uploaded/'.$path.$file;
 2278:     } else {
 2279:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2280: 		 ': '.$fetchresult);
 2281:         return '/adm/notfound.html';
 2282:     }
 2283: }
 2284: 
 2285: sub extract_embedded_items {
 2286:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 2287:     my @state = ();
 2288:     my %javafiles = (
 2289:                       codebase => '',
 2290:                       code => '',
 2291:                       archive => ''
 2292:                     );
 2293:     my %mediafiles = (
 2294:                       src => '',
 2295:                       movie => '',
 2296:                      );
 2297:     my $p;
 2298:     if ($content) {
 2299:         $p = HTML::LCParser->new($content);
 2300:     } else {
 2301:         $p = HTML::LCParser->new($fullpath);
 2302:     }
 2303:     while (my $t=$p->get_token()) {
 2304: 	if ($t->[0] eq 'S') {
 2305: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2306: 	    push(@state, $tagname);
 2307:             if (lc($tagname) eq 'allow') {
 2308:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2309:             }
 2310: 	    if (lc($tagname) eq 'img') {
 2311: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2312: 	    }
 2313: 	    if (lc($tagname) eq 'a') {
 2314: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2315: 	    }
 2316:             if (lc($tagname) eq 'script') {
 2317:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2318:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2319:                 } else {
 2320:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2321:                 }
 2322:             }
 2323:             if (lc($tagname) eq 'link') {
 2324:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2325:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2326:                 }
 2327:             }
 2328: 	    if (lc($tagname) eq 'object' ||
 2329: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2330: 		foreach my $item (keys(%javafiles)) {
 2331: 		    $javafiles{$item} = '';
 2332: 		}
 2333: 	    }
 2334: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2335: 		my $name = lc($attr->{'name'});
 2336: 		foreach my $item (keys(%javafiles)) {
 2337: 		    if ($name eq $item) {
 2338: 			$javafiles{$item} = $attr->{'value'};
 2339: 			last;
 2340: 		    }
 2341: 		}
 2342: 		foreach my $item (keys(%mediafiles)) {
 2343: 		    if ($name eq $item) {
 2344: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2345: 			last;
 2346: 		    }
 2347: 		}
 2348: 	    }
 2349: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2350: 		foreach my $item (keys(%javafiles)) {
 2351: 		    if ($attr->{$item}) {
 2352: 			$javafiles{$item} = $attr->{$item};
 2353: 			last;
 2354: 		    }
 2355: 		}
 2356: 		foreach my $item (keys(%mediafiles)) {
 2357: 		    if ($attr->{$item}) {
 2358: 			&add_filetype($allfiles,$attr->{$item},$item);
 2359: 			last;
 2360: 		    }
 2361: 		}
 2362: 	    }
 2363: 	} elsif ($t->[0] eq 'E') {
 2364: 	    my ($tagname) = ($t->[1]);
 2365: 	    if ($javafiles{'codebase'} ne '') {
 2366: 		$javafiles{'codebase'} .= '/';
 2367: 	    }  
 2368: 	    if (lc($tagname) eq 'applet' ||
 2369: 		lc($tagname) eq 'object' ||
 2370: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2371: 		) {
 2372: 		foreach my $item (keys(%javafiles)) {
 2373: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2374: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2375: 			&add_filetype($allfiles,$file,$item);
 2376: 		    }
 2377: 		}
 2378: 	    } 
 2379: 	    pop @state;
 2380: 	}
 2381:     }
 2382:     return 'ok';
 2383: }
 2384: 
 2385: sub add_filetype {
 2386:     my ($allfiles,$file,$type)=@_;
 2387:     if (exists($allfiles->{$file})) {
 2388: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2389: 	    push(@{$allfiles->{$file}}, &escape($type));
 2390: 	}
 2391:     } else {
 2392: 	@{$allfiles->{$file}} = (&escape($type));
 2393:     }
 2394: }
 2395: 
 2396: sub removeuploadedurl {
 2397:     my ($url)=@_;	
 2398:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 2399:     return &removeuserfile($uname,$udom,$fname);
 2400: }
 2401: 
 2402: sub removeuserfile {
 2403:     my ($docuname,$docudom,$fname)=@_;
 2404:     my $home=&homeserver($docuname,$docudom);    
 2405:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2406:     if ($result eq 'ok') {	
 2407:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2408:             my $metafile = $fname.'.meta';
 2409:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2410: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2411:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 2412:             my $sqlresult = 
 2413:                 &update_portfolio_table($docuname,$docudom,$file,
 2414:                                         'portfolio_metadata',$group,
 2415:                                         'delete');
 2416:         }
 2417:     }
 2418:     return $result;
 2419: }
 2420: 
 2421: sub mkdiruserfile {
 2422:     my ($docuname,$docudom,$dir)=@_;
 2423:     my $home=&homeserver($docuname,$docudom);
 2424:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2425: }
 2426: 
 2427: sub renameuserfile {
 2428:     my ($docuname,$docudom,$old,$new)=@_;
 2429:     my $home=&homeserver($docuname,$docudom);
 2430:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2431:                         &escape("$old").':'.&escape("$new"),$home);
 2432:     if ($result eq 'ok') {
 2433:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2434:             my $oldmeta = $old.'.meta';
 2435:             my $newmeta = $new.'.meta';
 2436:             my $metaresult = 
 2437:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2438: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2439:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2440:             my $sqlresult = 
 2441:                 &update_portfolio_table($docuname,$docudom,$file,
 2442:                                         'portfolio_metadata',$group,
 2443:                                         'delete');
 2444:         }
 2445:     }
 2446:     return $result;
 2447: }
 2448: 
 2449: # ------------------------------------------------------------------------- Log
 2450: 
 2451: sub log {
 2452:     my ($dom,$nam,$hom,$what)=@_;
 2453:     return critical("log:$dom:$nam:$what",$hom);
 2454: }
 2455: 
 2456: # ------------------------------------------------------------------ Course Log
 2457: #
 2458: # This routine flushes several buffers of non-mission-critical nature
 2459: #
 2460: 
 2461: sub flushcourselogs {
 2462:     &logthis('Flushing log buffers');
 2463: #
 2464: # course logs
 2465: # This is a log of all transactions in a course, which can be used
 2466: # for data mining purposes
 2467: #
 2468: # It also collects the courseid database, which lists last transaction
 2469: # times and course titles for all courseids
 2470: #
 2471:     my %courseidbuffer=();
 2472:     foreach my $crsid (keys(%courselogs)) {
 2473:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2474: 		          &escape($courselogs{$crsid}),
 2475: 		          $coursehombuf{$crsid}) eq 'ok') {
 2476: 	    delete $courselogs{$crsid};
 2477:         } else {
 2478:             &logthis('Failed to flush log buffer for '.$crsid);
 2479:             if (length($courselogs{$crsid})>40000) {
 2480:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2481:                         " exceeded maximum size, deleting.</font>");
 2482:                delete $courselogs{$crsid};
 2483:             }
 2484:         }
 2485:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2486:             'description' => $coursedescrbuf{$crsid},
 2487:             'inst_code'    => $courseinstcodebuf{$crsid},
 2488:             'type'        => $coursetypebuf{$crsid},
 2489:             'owner'       => $courseownerbuf{$crsid},
 2490:         };
 2491:     }
 2492: #
 2493: # Write course id database (reverse lookup) to homeserver of courses 
 2494: # Is used in pickcourse
 2495: #
 2496:     foreach my $crs_home (keys(%courseidbuffer)) {
 2497:         my $response = &courseidput(&host_domain($crs_home),
 2498:                                     $courseidbuffer{$crs_home},
 2499:                                     $crs_home,'timeonly');
 2500:     }
 2501: #
 2502: # File accesses
 2503: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2504: #
 2505:     foreach my $entry (keys(%accesshash)) {
 2506:         if ($entry =~ /___count$/) {
 2507:             my ($dom,$name);
 2508:             ($dom,$name,undef)=
 2509: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2510:             if (! defined($dom) || $dom eq '' || 
 2511:                 ! defined($name) || $name eq '') {
 2512:                 my $cid = $env{'request.course.id'};
 2513:                 $dom  = $env{'request.'.$cid.'.domain'};
 2514:                 $name = $env{'request.'.$cid.'.num'};
 2515:             }
 2516:             my $value = $accesshash{$entry};
 2517:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2518:             my %temphash=($url => $value);
 2519:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2520:             if ($result eq 'ok') {
 2521:                 delete $accesshash{$entry};
 2522:             } elsif ($result eq 'unknown_cmd') {
 2523:                 # Target server has old code running on it.
 2524:                 my %temphash=($entry => $value);
 2525:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2526:                     delete $accesshash{$entry};
 2527:                 }
 2528:             }
 2529:         } else {
 2530:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2531:             my %temphash=($entry => $accesshash{$entry});
 2532:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2533:                 delete $accesshash{$entry};
 2534:             }
 2535:         }
 2536:     }
 2537: #
 2538: # Roles
 2539: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2540: #
 2541:     foreach my $entry (keys(%userrolehash)) {
 2542:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2543: 	    split(/\:/,$entry);
 2544:         if (&Apache::lonnet::put('nohist_userroles',
 2545:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2546:                 $rudom,$runame) eq 'ok') {
 2547: 	    delete $userrolehash{$entry};
 2548:         }
 2549:     }
 2550: #
 2551: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2552: #
 2553:     my %domrolebuffer = ();
 2554:     foreach my $entry (keys %domainrolehash) {
 2555:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2556:         if ($domrolebuffer{$rudom}) {
 2557:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2558:                       '='.&escape($domainrolehash{$entry});
 2559:         } else {
 2560:             $domrolebuffer{$rudom}.=&escape($entry).
 2561:                       '='.&escape($domainrolehash{$entry});
 2562:         }
 2563:         delete $domainrolehash{$entry};
 2564:     }
 2565:     foreach my $dom (keys(%domrolebuffer)) {
 2566: 	my %servers = &get_servers($dom,'library');
 2567: 	foreach my $tryserver (keys(%servers)) {
 2568: 	    unless (&reply('domroleput:'.$dom.':'.
 2569: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2570: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2571: 	    }
 2572:         }
 2573:     }
 2574:     $dumpcount++;
 2575: }
 2576: 
 2577: sub courselog {
 2578:     my $what=shift;
 2579:     $what=time.':'.$what;
 2580:     unless ($env{'request.course.id'}) { return ''; }
 2581:     $coursedombuf{$env{'request.course.id'}}=
 2582:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2583:     $coursenumbuf{$env{'request.course.id'}}=
 2584:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2585:     $coursehombuf{$env{'request.course.id'}}=
 2586:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2587:     $coursedescrbuf{$env{'request.course.id'}}=
 2588:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2589:     $courseinstcodebuf{$env{'request.course.id'}}=
 2590:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2591:     $courseownerbuf{$env{'request.course.id'}}=
 2592:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2593:     $coursetypebuf{$env{'request.course.id'}}=
 2594:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2595:     if (defined $courselogs{$env{'request.course.id'}}) {
 2596: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2597:     } else {
 2598: 	$courselogs{$env{'request.course.id'}}.=$what;
 2599:     }
 2600:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2601: 	&flushcourselogs();
 2602:     }
 2603: }
 2604: 
 2605: sub courseacclog {
 2606:     my $fnsymb=shift;
 2607:     unless ($env{'request.course.id'}) { return ''; }
 2608:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2609:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2610:         $what.=':POST';
 2611:         # FIXME: Probably ought to escape things....
 2612: 	foreach my $key (keys(%env)) {
 2613:             if ($key=~/^form\.(.*)/) {
 2614:                 my $formitem = $1;
 2615:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 2616:                     $what.=':'.$formitem.'='.$env{$key};
 2617:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 2618:                     $what.=':'.$formitem.'='.$env{$key};
 2619:                 }
 2620:             }
 2621:         }
 2622:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2623:         # FIXME: We should not be depending on a form parameter that someone
 2624:         # editing lonsearchcat.pm might change in the future.
 2625:         if ($env{'form.phase'} eq 'course_search') {
 2626:             $what.= ':POST';
 2627:             # FIXME: Probably ought to escape things....
 2628:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2629:                                  'crsdiscuss') {
 2630:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2631:             }
 2632:         }
 2633:     }
 2634:     &courselog($what);
 2635: }
 2636: 
 2637: sub countacc {
 2638:     my $url=&declutter(shift);
 2639:     return if (! defined($url) || $url eq '');
 2640:     unless ($env{'request.course.id'}) { return ''; }
 2641:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2642:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2643:     $accesshash{$key}++;
 2644: }
 2645: 
 2646: sub linklog {
 2647:     my ($from,$to)=@_;
 2648:     $from=&declutter($from);
 2649:     $to=&declutter($to);
 2650:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2651:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2652: }
 2653:   
 2654: sub userrolelog {
 2655:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2656:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2657:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2658:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2659:         ($trole=~/^ta/)) {
 2660:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2661:        $userrolehash
 2662:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2663:                     =$tend.':'.$tstart;
 2664:     }
 2665:     if (($env{'request.role'} =~ /dc\./) &&
 2666: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2667: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2668: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
 2669:        $userrolehash
 2670:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2671:                     =$tend.':'.$tstart;
 2672:     }
 2673:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2674:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2675:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2676:         ($trole=~/^sc/)) {
 2677:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2678:        $domainrolehash
 2679:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2680:                     = $tend.':'.$tstart;
 2681:     }
 2682: }
 2683: 
 2684: sub courserolelog {
 2685:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 2686:     if (($trole eq 'cc') || ($trole eq 'in') ||
 2687:         ($trole eq 'ep') || ($trole eq 'ad') ||
 2688:         ($trole eq 'ta') || ($trole eq 'st') ||
 2689:         ($trole=~/^cr/) || ($trole eq 'gr')) {
 2690:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 2691:             my $cdom = $1;
 2692:             my $cnum = $2;
 2693:             my $sec = $3;
 2694:             my $namespace = 'rolelog';
 2695:             my %storehash = (
 2696:                                role    => $trole,
 2697:                                start   => $tstart,
 2698:                                end     => $tend,
 2699:                                selfenroll => $selfenroll,
 2700:                                context    => $context,
 2701:                             );
 2702:             if ($trole eq 'gr') {
 2703:                 $namespace = 'groupslog';
 2704:                 $storehash{'group'} = $sec;
 2705:             } else {
 2706:                 $storehash{'section'} = $sec;
 2707:             }
 2708:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 2709:         }
 2710:     }
 2711:     return;
 2712: }
 2713: 
 2714: sub get_course_adv_roles {
 2715:     my ($cid,$codes) = @_;
 2716:     $cid=$env{'request.course.id'} unless (defined($cid));
 2717:     my %coursehash=&coursedescription($cid);
 2718:     my $crstype = &Apache::loncommon::course_type($cid);
 2719:     my %nothide=();
 2720:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2721:         if ($user !~ /:/) {
 2722: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2723:         } else {
 2724:             $nothide{$user}=1;
 2725:         }
 2726:     }
 2727:     my %returnhash=();
 2728:     my %dumphash=
 2729:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2730:     my $now=time;
 2731:     foreach my $entry (keys %dumphash) {
 2732: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2733:         if (($tstart) && ($tstart<0)) { next; }
 2734:         if (($tend) && ($tend<$now)) { next; }
 2735:         if (($tstart) && ($now<$tstart)) { next; }
 2736:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2737: 	if ($username eq '' || $domain eq '') { next; }
 2738: 	if ((&privileged($username,$domain)) && 
 2739: 	    (!$nothide{$username.':'.$domain})) { next; }
 2740: 	if ($role eq 'cr') { next; }
 2741:         if ($codes) {
 2742:             if ($section) { $role .= ':'.$section; }
 2743:             if ($returnhash{$role}) {
 2744:                 $returnhash{$role}.=','.$username.':'.$domain;
 2745:             } else {
 2746:                 $returnhash{$role}=$username.':'.$domain;
 2747:             }
 2748:         } else {
 2749:             my $key=&plaintext($role,$crstype);
 2750:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 2751:             if ($returnhash{$key}) {
 2752: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2753:             } else {
 2754:                 $returnhash{$key}=$username.':'.$domain;
 2755:             }
 2756:         }
 2757:     }
 2758:     return %returnhash;
 2759: }
 2760: 
 2761: sub get_my_roles {
 2762:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2763:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2764:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2765:     my (%dumphash,%nothide);
 2766:     if ($context eq 'userroles') { 
 2767:         %dumphash = &dump('roles',$udom,$uname);
 2768:     } else {
 2769:         %dumphash=
 2770:             &dump('nohist_userroles',$udom,$uname);
 2771:         if ($hidepriv) {
 2772:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2773:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2774:                 if ($user !~ /:/) {
 2775:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2776:                 } else {
 2777:                     $nothide{$user} = 1;
 2778:                 }
 2779:             }
 2780:         }
 2781:     }
 2782:     my %returnhash=();
 2783:     my $now=time;
 2784:     foreach my $entry (keys(%dumphash)) {
 2785:         my ($role,$tend,$tstart);
 2786:         if ($context eq 'userroles') {
 2787: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2788:         } else {
 2789:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2790:         }
 2791:         if (($tstart) && ($tstart<0)) { next; }
 2792:         my $status = 'active';
 2793:         if (($tend) && ($tend<=$now)) {
 2794:             $status = 'previous';
 2795:         } 
 2796:         if (($tstart) && ($now<$tstart)) {
 2797:             $status = 'future';
 2798:         }
 2799:         if (ref($types) eq 'ARRAY') {
 2800:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2801:                 next;
 2802:             } 
 2803:         } else {
 2804:             if ($status ne 'active') {
 2805:                 next;
 2806:             }
 2807:         }
 2808:         my ($rolecode,$username,$domain,$section,$area);
 2809:         if ($context eq 'userroles') {
 2810:             ($area,$rolecode) = split(/_/,$entry);
 2811:             (undef,$domain,$username,$section) = split(/\//,$area);
 2812:         } else {
 2813:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2814:         }
 2815:         if (ref($roledoms) eq 'ARRAY') {
 2816:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2817:                 next;
 2818:             }
 2819:         }
 2820:         if (ref($roles) eq 'ARRAY') {
 2821:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2822:                 if ($role =~ /^cr\//) {
 2823:                     if (!grep(/^cr$/,@{$roles})) {
 2824:                         next;
 2825:                     }
 2826:                 } else {
 2827:                     next;
 2828:                 }
 2829:             }
 2830:         }
 2831:         if ($hidepriv) {
 2832:             if ((&privileged($username,$domain)) &&
 2833:                 (!$nothide{$username.':'.$domain})) { 
 2834:                 next;
 2835:             }
 2836:         }
 2837:         if ($withsec) {
 2838:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2839:                 $tstart.':'.$tend;
 2840:         } else {
 2841:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2842:         }
 2843:     }
 2844:     return %returnhash;
 2845: }
 2846: 
 2847: # ----------------------------------------------------- Frontpage Announcements
 2848: #
 2849: #
 2850: 
 2851: sub postannounce {
 2852:     my ($server,$text)=@_;
 2853:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2854:     unless ($text=~/\w/) { $text=''; }
 2855:     return &reply('setannounce:'.&escape($text),$server);
 2856: }
 2857: 
 2858: sub getannounce {
 2859: 
 2860:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2861: 	my $announcement='';
 2862: 	while (my $line = <$fh>) { $announcement .= $line; }
 2863: 	close($fh);
 2864: 	if ($announcement=~/\w/) { 
 2865: 	    return 
 2866:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2867:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2868: 	} else {
 2869: 	    return '';
 2870: 	}
 2871:     } else {
 2872: 	return '';
 2873:     }
 2874: }
 2875: 
 2876: # ---------------------------------------------------------- Course ID routines
 2877: # Deal with domain's nohist_courseid.db files
 2878: #
 2879: 
 2880: sub courseidput {
 2881:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2882:     my $outcome;
 2883:     if ($caller eq 'timeonly') {
 2884:         my $cids = '';
 2885:         foreach my $item (keys(%$storehash)) {
 2886:             $cids.=&escape($item).'&';
 2887:         }
 2888:         $cids=~s/\&$//;
 2889:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 2890:                           $coursehome);       
 2891:     } else {
 2892:         my $items = '';
 2893:         foreach my $item (keys(%$storehash)) {
 2894:             $items.= &escape($item).'='.
 2895:                      &freeze_escape($$storehash{$item}).'&';
 2896:         }
 2897:         $items=~s/\&$//;
 2898:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 2899:                           $coursehome);
 2900:     }
 2901:     if ($outcome eq 'unknown_cmd') {
 2902:         my $what;
 2903:         foreach my $cid (keys(%$storehash)) {
 2904:             $what .= &escape($cid).'=';
 2905:             foreach my $item ('description','inst_code','owner','type') {
 2906:                 $what .= &escape($storehash->{$cid}{$item}).':';
 2907:             }
 2908:             $what =~ s/\:$/&/;
 2909:         }
 2910:         $what =~ s/\&$//;  
 2911:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2912:     } else {
 2913:         return $outcome;
 2914:     }
 2915: }
 2916: 
 2917: sub courseiddump {
 2918:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 2919:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 2920:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
 2921:     my $as_hash = 1;
 2922:     my %returnhash;
 2923:     if (!$domfilter) { $domfilter=''; }
 2924:     my %libserv = &all_library();
 2925:     foreach my $tryserver (keys(%libserv)) {
 2926:         if ( (  $hostidflag == 1 
 2927: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2928: 	     || (!defined($hostidflag)) ) {
 2929: 
 2930: 	    if (($domfilter eq '') ||
 2931: 		(&host_domain($tryserver) eq $domfilter)) {
 2932:                 my $rep = 
 2933:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 2934:                          $sincefilter.':'.&escape($descfilter).':'.
 2935:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 2936:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 2937:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 2938:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 2939:                          $showhidden.':'.$caller,$tryserver);
 2940:                 my @pairs=split(/\&/,$rep);
 2941:                 foreach my $item (@pairs) {
 2942:                     my ($key,$value)=split(/\=/,$item,2);
 2943:                     $key = &unescape($key);
 2944:                     next if ($key =~ /^error: 2 /);
 2945:                     my $result = &thaw_unescape($value);
 2946:                     if (ref($result) eq 'HASH') {
 2947:                         $returnhash{$key}=$result;
 2948:                     } else {
 2949:                         my @responses = split(/:/,$value);
 2950:                         my @items = ('description','inst_code','owner','type');
 2951:                         for (my $i=0; $i<@responses; $i++) {
 2952:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 2953:                         }
 2954:                     } 
 2955:                 }
 2956:             }
 2957:         }
 2958:     }
 2959:     return %returnhash;
 2960: }
 2961: 
 2962: # ---------------------------------------------------------- DC e-mail
 2963: 
 2964: sub dcmailput {
 2965:     my ($domain,$msgid,$message,$server)=@_;
 2966:     my $status = &Apache::lonnet::critical(
 2967:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2968:        &escape($message),$server);
 2969:     return $status;
 2970: }
 2971: 
 2972: sub dcmaildump {
 2973:     my ($dom,$startdate,$enddate,$senders) = @_;
 2974:     my %returnhash=();
 2975: 
 2976:     if (defined(&domain($dom,'primary'))) {
 2977:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2978:                                                          &escape($enddate).':';
 2979: 	my @esc_senders=map { &escape($_)} @$senders;
 2980: 	$cmd.=&escape(join('&',@esc_senders));
 2981: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2982:             my ($key,$value) = split(/\=/,$line,2);
 2983:             if (($key) && ($value)) {
 2984:                 $returnhash{&unescape($key)} = &unescape($value);
 2985:             }
 2986:         }
 2987:     }
 2988:     return %returnhash;
 2989: }
 2990: # ---------------------------------------------------------- Domain roles
 2991: 
 2992: sub get_domain_roles {
 2993:     my ($dom,$roles,$startdate,$enddate)=@_;
 2994:     if (undef($startdate) || $startdate eq '') {
 2995:         $startdate = '.';
 2996:     }
 2997:     if (undef($enddate) || $enddate eq '') {
 2998:         $enddate = '.';
 2999:     }
 3000:     my $rolelist;
 3001:     if (ref($roles) eq 'ARRAY') {
 3002:         $rolelist = join(':',@{$roles});
 3003:     }
 3004:     my %personnel = ();
 3005: 
 3006:     my %servers = &get_servers($dom,'library');
 3007:     foreach my $tryserver (keys(%servers)) {
 3008: 	%{$personnel{$tryserver}}=();
 3009: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 3010: 					    &escape($startdate).':'.
 3011: 					    &escape($enddate).':'.
 3012: 					    &escape($rolelist), $tryserver))) {
 3013: 	    my ($key,$value) = split(/\=/,$line,2);
 3014: 	    if (($key) && ($value)) {
 3015: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 3016: 	    }
 3017: 	}
 3018:     }
 3019:     return %personnel;
 3020: }
 3021: 
 3022: # ----------------------------------------------------------- Check out an item
 3023: 
 3024: sub get_first_access {
 3025:     my ($type,$argsymb)=@_;
 3026:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3027:     if ($argsymb) { $symb=$argsymb; }
 3028:     my ($map,$id,$res)=&decode_symb($symb);
 3029:     if ($type eq 'course') {
 3030: 	$res='course';
 3031:     } elsif ($type eq 'map') {
 3032: 	$res=&symbread($map);
 3033:     } else {
 3034: 	$res=$symb;
 3035:     }
 3036:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 3037:     return $times{"$courseid\0$res"};
 3038: }
 3039: 
 3040: sub set_first_access {
 3041:     my ($type)=@_;
 3042:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3043:     my ($map,$id,$res)=&decode_symb($symb);
 3044:     if ($type eq 'course') {
 3045: 	$res='course';
 3046:     } elsif ($type eq 'map') {
 3047: 	$res=&symbread($map);
 3048:     } else {
 3049: 	$res=$symb;
 3050:     }
 3051:     my $firstaccess=&get_first_access($type,$symb);
 3052:     if (!$firstaccess) {
 3053: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 3054:     }
 3055:     return 'already_set';
 3056: }
 3057: 
 3058: sub checkout {
 3059:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 3060:     my $now=time;
 3061:     my $lonhost=$perlvar{'lonHostID'};
 3062:     my $infostr=&escape(
 3063:                  'CHECKOUTTOKEN&'.
 3064:                  $tuname.'&'.
 3065:                  $tudom.'&'.
 3066:                  $tcrsid.'&'.
 3067:                  $symb.'&'.
 3068: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 3069:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 3070:     if ($token=~/^error\:/) { 
 3071:         &logthis("<font color=\"blue\">WARNING: ".
 3072:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 3073:                  "</font>");
 3074:         return ''; 
 3075:     }
 3076: 
 3077:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 3078:     $token=~tr/a-z/A-Z/;
 3079: 
 3080:     my %infohash=('resource.0.outtoken' => $token,
 3081:                   'resource.0.checkouttime' => $now,
 3082:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 3083: 
 3084:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3085:        return '';
 3086:     } else {
 3087:         &logthis("<font color=\"blue\">WARNING: ".
 3088:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 3089:                  "</font>");
 3090:     }    
 3091: 
 3092:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3093:                          &escape('Checkout '.$infostr.' - '.
 3094:                                                  $token)) ne 'ok') {
 3095: 	return '';
 3096:     } else {
 3097:         &logthis("<font color=\"blue\">WARNING: ".
 3098:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 3099:                  "</font>");
 3100:     }
 3101:     return $token;
 3102: }
 3103: 
 3104: # ------------------------------------------------------------ Check in an item
 3105: 
 3106: sub checkin {
 3107:     my $token=shift;
 3108:     my $now=time;
 3109:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 3110:     $lonhost=~tr/A-Z/a-z/;
 3111:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 3112:     $dtoken=~s/\W/\_/g;
 3113:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 3114:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 3115: 
 3116:     unless (($tuname) && ($tudom)) {
 3117:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 3118:         return '';
 3119:     }
 3120:     
 3121:     unless (&allowed('mgr',$tcrsid)) {
 3122:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 3123:                  $env{'user.name'}.' - '.$env{'user.domain'});
 3124:         return '';
 3125:     }
 3126: 
 3127:     my %infohash=('resource.0.intoken' => $token,
 3128:                   'resource.0.checkintime' => $now,
 3129:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 3130: 
 3131:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3132:        return '';
 3133:     }    
 3134: 
 3135:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3136:                          &escape('Checkin - '.$token)) ne 'ok') {
 3137: 	return '';
 3138:     }
 3139: 
 3140:     return ($symb,$tuname,$tudom,$tcrsid);    
 3141: }
 3142: 
 3143: # --------------------------------------------- Set Expire Date for Spreadsheet
 3144: 
 3145: sub expirespread {
 3146:     my ($uname,$udom,$stype,$usymb)=@_;
 3147:     my $cid=$env{'request.course.id'}; 
 3148:     if ($cid) {
 3149:        my $now=time;
 3150:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3151:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3152:                             $env{'course.'.$cid.'.num'}.
 3153: 	        	    ':nohist_expirationdates:'.
 3154:                             &escape($key).'='.$now,
 3155:                             $env{'course.'.$cid.'.home'})
 3156:     }
 3157:     return 'ok';
 3158: }
 3159: 
 3160: # ----------------------------------------------------- Devalidate Spreadsheets
 3161: 
 3162: sub devalidate {
 3163:     my ($symb,$uname,$udom)=@_;
 3164:     my $cid=$env{'request.course.id'}; 
 3165:     if ($cid) {
 3166:         # delete the stored spreadsheets for
 3167:         # - the student level sheet of this user in course's homespace
 3168:         # - the assessment level sheet for this resource 
 3169:         #   for this user in user's homespace
 3170: 	# - current conditional state info
 3171: 	my $key=$uname.':'.$udom.':';
 3172:         my $status=
 3173: 	    &del('nohist_calculatedsheets',
 3174: 		 [$key.'studentcalc:'],
 3175: 		 $env{'course.'.$cid.'.domain'},
 3176: 		 $env{'course.'.$cid.'.num'})
 3177: 		.' '.
 3178: 	    &del('nohist_calculatedsheets_'.$cid,
 3179: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3180:         unless ($status eq 'ok ok') {
 3181:            &logthis('Could not devalidate spreadsheet '.
 3182:                     $uname.' at '.$udom.' for '.
 3183: 		    $symb.': '.$status);
 3184:         }
 3185: 	&delenv('user.state.'.$cid);
 3186:     }
 3187: }
 3188: 
 3189: sub get_scalar {
 3190:     my ($string,$end) = @_;
 3191:     my $value;
 3192:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3193: 	$value = $1;
 3194:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3195: 	$value = $1;
 3196:     }
 3197:     return &unescape($value);
 3198: }
 3199: 
 3200: sub array2str {
 3201:   my (@array) = @_;
 3202:   my $result=&arrayref2str(\@array);
 3203:   $result=~s/^__ARRAY_REF__//;
 3204:   $result=~s/__END_ARRAY_REF__$//;
 3205:   return $result;
 3206: }
 3207: 
 3208: sub arrayref2str {
 3209:   my ($arrayref) = @_;
 3210:   my $result='__ARRAY_REF__';
 3211:   foreach my $elem (@$arrayref) {
 3212:     if(ref($elem) eq 'ARRAY') {
 3213:       $result.=&arrayref2str($elem).'&';
 3214:     } elsif(ref($elem) eq 'HASH') {
 3215:       $result.=&hashref2str($elem).'&';
 3216:     } elsif(ref($elem)) {
 3217:       #print("Got a ref of ".(ref($elem))." skipping.");
 3218:     } else {
 3219:       $result.=&escape($elem).'&';
 3220:     }
 3221:   }
 3222:   $result=~s/\&$//;
 3223:   $result .= '__END_ARRAY_REF__';
 3224:   return $result;
 3225: }
 3226: 
 3227: sub hash2str {
 3228:   my (%hash) = @_;
 3229:   my $result=&hashref2str(\%hash);
 3230:   $result=~s/^__HASH_REF__//;
 3231:   $result=~s/__END_HASH_REF__$//;
 3232:   return $result;
 3233: }
 3234: 
 3235: sub hashref2str {
 3236:   my ($hashref)=@_;
 3237:   my $result='__HASH_REF__';
 3238:   foreach my $key (sort(keys(%$hashref))) {
 3239:     if (ref($key) eq 'ARRAY') {
 3240:       $result.=&arrayref2str($key).'=';
 3241:     } elsif (ref($key) eq 'HASH') {
 3242:       $result.=&hashref2str($key).'=';
 3243:     } elsif (ref($key)) {
 3244:       $result.='=';
 3245:       #print("Got a ref of ".(ref($key))." skipping.");
 3246:     } else {
 3247: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3248:     }
 3249: 
 3250:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3251:       $result.=&arrayref2str($hashref->{$key}).'&';
 3252:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3253:       $result.=&hashref2str($hashref->{$key}).'&';
 3254:     } elsif(ref($hashref->{$key})) {
 3255:        $result.='&';
 3256:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3257:     } else {
 3258:       $result.=&escape($hashref->{$key}).'&';
 3259:     }
 3260:   }
 3261:   $result=~s/\&$//;
 3262:   $result .= '__END_HASH_REF__';
 3263:   return $result;
 3264: }
 3265: 
 3266: sub str2hash {
 3267:     my ($string)=@_;
 3268:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3269:     return %$hash;
 3270: }
 3271: 
 3272: sub str2hashref {
 3273:   my ($string) = @_;
 3274: 
 3275:   my %hash;
 3276: 
 3277:   if($string !~ /^__HASH_REF__/) {
 3278:       if (! ($string eq '' || !defined($string))) {
 3279: 	  $hash{'error'}='Not hash reference';
 3280:       }
 3281:       return (\%hash, $string);
 3282:   }
 3283: 
 3284:   $string =~ s/^__HASH_REF__//;
 3285: 
 3286:   while($string !~ /^__END_HASH_REF__/) {
 3287:       #key
 3288:       my $key='';
 3289:       if($string =~ /^__HASH_REF__/) {
 3290:           ($key, $string)=&str2hashref($string);
 3291:           if(defined($key->{'error'})) {
 3292:               $hash{'error'}='Bad data';
 3293:               return (\%hash, $string);
 3294:           }
 3295:       } elsif($string =~ /^__ARRAY_REF__/) {
 3296:           ($key, $string)=&str2arrayref($string);
 3297:           if($key->[0] eq 'Array reference error') {
 3298:               $hash{'error'}='Bad data';
 3299:               return (\%hash, $string);
 3300:           }
 3301:       } else {
 3302:           $string =~ s/^(.*?)=//;
 3303: 	  $key=&unescape($1);
 3304:       }
 3305:       $string =~ s/^=//;
 3306: 
 3307:       #value
 3308:       my $value='';
 3309:       if($string =~ /^__HASH_REF__/) {
 3310:           ($value, $string)=&str2hashref($string);
 3311:           if(defined($value->{'error'})) {
 3312:               $hash{'error'}='Bad data';
 3313:               return (\%hash, $string);
 3314:           }
 3315:       } elsif($string =~ /^__ARRAY_REF__/) {
 3316:           ($value, $string)=&str2arrayref($string);
 3317:           if($value->[0] eq 'Array reference error') {
 3318:               $hash{'error'}='Bad data';
 3319:               return (\%hash, $string);
 3320:           }
 3321:       } else {
 3322: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3323:       }
 3324:       $string =~ s/^&//;
 3325: 
 3326:       $hash{$key}=$value;
 3327:   }
 3328: 
 3329:   $string =~ s/^__END_HASH_REF__//;
 3330: 
 3331:   return (\%hash, $string);
 3332: }
 3333: 
 3334: sub str2array {
 3335:     my ($string)=@_;
 3336:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3337:     return @$array;
 3338: }
 3339: 
 3340: sub str2arrayref {
 3341:   my ($string) = @_;
 3342:   my @array;
 3343: 
 3344:   if($string !~ /^__ARRAY_REF__/) {
 3345:       if (! ($string eq '' || !defined($string))) {
 3346: 	  $array[0]='Array reference error';
 3347:       }
 3348:       return (\@array, $string);
 3349:   }
 3350: 
 3351:   $string =~ s/^__ARRAY_REF__//;
 3352: 
 3353:   while($string !~ /^__END_ARRAY_REF__/) {
 3354:       my $value='';
 3355:       if($string =~ /^__HASH_REF__/) {
 3356:           ($value, $string)=&str2hashref($string);
 3357:           if(defined($value->{'error'})) {
 3358:               $array[0] ='Array reference error';
 3359:               return (\@array, $string);
 3360:           }
 3361:       } elsif($string =~ /^__ARRAY_REF__/) {
 3362:           ($value, $string)=&str2arrayref($string);
 3363:           if($value->[0] eq 'Array reference error') {
 3364:               $array[0] ='Array reference error';
 3365:               return (\@array, $string);
 3366:           }
 3367:       } else {
 3368: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3369:       }
 3370:       $string =~ s/^&//;
 3371: 
 3372:       push(@array, $value);
 3373:   }
 3374: 
 3375:   $string =~ s/^__END_ARRAY_REF__//;
 3376: 
 3377:   return (\@array, $string);
 3378: }
 3379: 
 3380: # -------------------------------------------------------------------Temp Store
 3381: 
 3382: sub tmpreset {
 3383:   my ($symb,$namespace,$domain,$stuname) = @_;
 3384:   if (!$symb) {
 3385:     $symb=&symbread();
 3386:     if (!$symb) { $symb= $env{'request.url'}; }
 3387:   }
 3388:   $symb=escape($symb);
 3389: 
 3390:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3391:   $namespace=~s/\//\_/g;
 3392:   $namespace=~s/\W//g;
 3393: 
 3394:   if (!$domain) { $domain=$env{'user.domain'}; }
 3395:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3396:   if ($domain eq 'public' && $stuname eq 'public') {
 3397:       $stuname=$ENV{'REMOTE_ADDR'};
 3398:   }
 3399:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3400:   my %hash;
 3401:   if (tie(%hash,'GDBM_File',
 3402: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3403: 	  &GDBM_WRCREAT(),0640)) {
 3404:     foreach my $key (keys %hash) {
 3405:       if ($key=~ /:$symb/) {
 3406: 	delete($hash{$key});
 3407:       }
 3408:     }
 3409:   }
 3410: }
 3411: 
 3412: sub tmpstore {
 3413:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3414: 
 3415:   if (!$symb) {
 3416:     $symb=&symbread();
 3417:     if (!$symb) { $symb= $env{'request.url'}; }
 3418:   }
 3419:   $symb=escape($symb);
 3420: 
 3421:   if (!$namespace) {
 3422:     # I don't think we would ever want to store this for a course.
 3423:     # it seems this will only be used if we don't have a course.
 3424:     #$namespace=$env{'request.course.id'};
 3425:     #if (!$namespace) {
 3426:       $namespace=$env{'request.state'};
 3427:     #}
 3428:   }
 3429:   $namespace=~s/\//\_/g;
 3430:   $namespace=~s/\W//g;
 3431:   if (!$domain) { $domain=$env{'user.domain'}; }
 3432:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3433:   if ($domain eq 'public' && $stuname eq 'public') {
 3434:       $stuname=$ENV{'REMOTE_ADDR'};
 3435:   }
 3436:   my $now=time;
 3437:   my %hash;
 3438:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3439:   if (tie(%hash,'GDBM_File',
 3440: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3441: 	  &GDBM_WRCREAT(),0640)) {
 3442:     $hash{"version:$symb"}++;
 3443:     my $version=$hash{"version:$symb"};
 3444:     my $allkeys=''; 
 3445:     foreach my $key (keys(%$storehash)) {
 3446:       $allkeys.=$key.':';
 3447:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3448:     }
 3449:     $hash{"$version:$symb:timestamp"}=$now;
 3450:     $allkeys.='timestamp';
 3451:     $hash{"$version:keys:$symb"}=$allkeys;
 3452:     if (untie(%hash)) {
 3453:       return 'ok';
 3454:     } else {
 3455:       return "error:$!";
 3456:     }
 3457:   } else {
 3458:     return "error:$!";
 3459:   }
 3460: }
 3461: 
 3462: # -----------------------------------------------------------------Temp Restore
 3463: 
 3464: sub tmprestore {
 3465:   my ($symb,$namespace,$domain,$stuname) = @_;
 3466: 
 3467:   if (!$symb) {
 3468:     $symb=&symbread();
 3469:     if (!$symb) { $symb= $env{'request.url'}; }
 3470:   }
 3471:   $symb=escape($symb);
 3472: 
 3473:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3474: 
 3475:   if (!$domain) { $domain=$env{'user.domain'}; }
 3476:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3477:   if ($domain eq 'public' && $stuname eq 'public') {
 3478:       $stuname=$ENV{'REMOTE_ADDR'};
 3479:   }
 3480:   my %returnhash;
 3481:   $namespace=~s/\//\_/g;
 3482:   $namespace=~s/\W//g;
 3483:   my %hash;
 3484:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3485:   if (tie(%hash,'GDBM_File',
 3486: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3487: 	  &GDBM_READER(),0640)) {
 3488:     my $version=$hash{"version:$symb"};
 3489:     $returnhash{'version'}=$version;
 3490:     my $scope;
 3491:     for ($scope=1;$scope<=$version;$scope++) {
 3492:       my $vkeys=$hash{"$scope:keys:$symb"};
 3493:       my @keys=split(/:/,$vkeys);
 3494:       my $key;
 3495:       $returnhash{"$scope:keys"}=$vkeys;
 3496:       foreach $key (@keys) {
 3497: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3498: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3499:       }
 3500:     }
 3501:     if (!(untie(%hash))) {
 3502:       return "error:$!";
 3503:     }
 3504:   } else {
 3505:     return "error:$!";
 3506:   }
 3507:   return %returnhash;
 3508: }
 3509: 
 3510: # ----------------------------------------------------------------------- Store
 3511: 
 3512: sub store {
 3513:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3514:     my $home='';
 3515: 
 3516:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3517: 
 3518:     $symb=&symbclean($symb);
 3519:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3520: 
 3521:     if (!$domain) { $domain=$env{'user.domain'}; }
 3522:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3523: 
 3524:     &devalidate($symb,$stuname,$domain);
 3525: 
 3526:     $symb=escape($symb);
 3527:     if (!$namespace) { 
 3528:        unless ($namespace=$env{'request.course.id'}) { 
 3529:           return ''; 
 3530:        } 
 3531:     }
 3532:     if (!$home) { $home=$env{'user.home'}; }
 3533: 
 3534:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3535:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3536: 
 3537:     my $namevalue='';
 3538:     foreach my $key (keys(%$storehash)) {
 3539:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3540:     }
 3541:     $namevalue=~s/\&$//;
 3542:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3543:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3544: }
 3545: 
 3546: # -------------------------------------------------------------- Critical Store
 3547: 
 3548: sub cstore {
 3549:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3550:     my $home='';
 3551: 
 3552:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3553: 
 3554:     $symb=&symbclean($symb);
 3555:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3556: 
 3557:     if (!$domain) { $domain=$env{'user.domain'}; }
 3558:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3559: 
 3560:     &devalidate($symb,$stuname,$domain);
 3561: 
 3562:     $symb=escape($symb);
 3563:     if (!$namespace) { 
 3564:        unless ($namespace=$env{'request.course.id'}) { 
 3565:           return ''; 
 3566:        } 
 3567:     }
 3568:     if (!$home) { $home=$env{'user.home'}; }
 3569: 
 3570:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3571:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3572: 
 3573:     my $namevalue='';
 3574:     foreach my $key (keys(%$storehash)) {
 3575:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3576:     }
 3577:     $namevalue=~s/\&$//;
 3578:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3579:     return critical
 3580:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3581: }
 3582: 
 3583: # --------------------------------------------------------------------- Restore
 3584: 
 3585: sub restore {
 3586:     my ($symb,$namespace,$domain,$stuname) = @_;
 3587:     my $home='';
 3588: 
 3589:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3590: 
 3591:     if (!$symb) {
 3592:       unless ($symb=escape(&symbread())) { return ''; }
 3593:     } else {
 3594:       $symb=&escape(&symbclean($symb));
 3595:     }
 3596:     if (!$namespace) { 
 3597:        unless ($namespace=$env{'request.course.id'}) { 
 3598:           return ''; 
 3599:        } 
 3600:     }
 3601:     if (!$domain) { $domain=$env{'user.domain'}; }
 3602:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3603:     if (!$home) { $home=$env{'user.home'}; }
 3604:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3605: 
 3606:     my %returnhash=();
 3607:     foreach my $line (split(/\&/,$answer)) {
 3608: 	my ($name,$value)=split(/\=/,$line);
 3609:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3610:     }
 3611:     my $version;
 3612:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3613:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3614:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3615:        }
 3616:     }
 3617:     return %returnhash;
 3618: }
 3619: 
 3620: # ---------------------------------------------------------- Course Description
 3621: 
 3622: sub coursedescription {
 3623:     my ($courseid,$args)=@_;
 3624:     $courseid=~s/^\///;
 3625:     $courseid=~s/\_/\//g;
 3626:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3627:     my $chome=&homeserver($cnum,$cdomain);
 3628:     my $normalid=$cdomain.'_'.$cnum;
 3629:     # need to always cache even if we get errors otherwise we keep 
 3630:     # trying and trying and trying to get the course description.
 3631:     my %envhash=();
 3632:     my %returnhash=();
 3633:     
 3634:     my $expiretime=600;
 3635:     if ($env{'request.course.id'} eq $normalid) {
 3636: 	$expiretime=120;
 3637:     }
 3638: 
 3639:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3640:     if (!$args->{'freshen_cache'}
 3641: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3642: 	foreach my $key (keys(%env)) {
 3643: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3644: 	    my ($setting) = $1;
 3645: 	    $returnhash{$setting} = $env{$key};
 3646: 	}
 3647: 	return %returnhash;
 3648:     }
 3649: 
 3650:     # get the data agin
 3651:     if (!$args->{'one_time'}) {
 3652: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3653:     }
 3654: 
 3655:     if ($chome ne 'no_host') {
 3656:        %returnhash=&dump('environment',$cdomain,$cnum);
 3657:        if (!exists($returnhash{'con_lost'})) {
 3658:            $returnhash{'home'}= $chome;
 3659: 	   $returnhash{'domain'} = $cdomain;
 3660: 	   $returnhash{'num'} = $cnum;
 3661:            if (!defined($returnhash{'type'})) {
 3662:                $returnhash{'type'} = 'Course';
 3663:            }
 3664:            while (my ($name,$value) = each %returnhash) {
 3665:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3666:            }
 3667:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3668:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3669: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3670:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3671:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3672:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3673:        }
 3674:     }
 3675:     if (!$args->{'one_time'}) {
 3676: 	&appenv(\%envhash);
 3677:     }
 3678:     return %returnhash;
 3679: }
 3680: 
 3681: # -------------------------------------------------See if a user is privileged
 3682: 
 3683: sub privileged {
 3684:     my ($username,$domain)=@_;
 3685:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3686: 			&homeserver($username,$domain));
 3687:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3688:     my $now=time;
 3689:     if ($rolesdump ne '') {
 3690:         foreach my $entry (split(/&/,$rolesdump)) {
 3691: 	    if ($entry!~/^rolesdef_/) {
 3692: 		my ($area,$role)=split(/=/,$entry);
 3693: 		$area=~s/\_\w\w$//;
 3694: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3695: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3696: 		    my $active=1;
 3697: 		    if ($tend) {
 3698: 			if ($tend<$now) { $active=0; }
 3699: 		    }
 3700: 		    if ($tstart) {
 3701: 			if ($tstart>$now) { $active=0; }
 3702: 		    }
 3703: 		    if ($active) { return 1; }
 3704: 		}
 3705: 	    }
 3706: 	}
 3707:     }
 3708:     return 0;
 3709: }
 3710: 
 3711: # -------------------------------------------------------- Get user privileges
 3712: 
 3713: sub rolesinit {
 3714:     my ($domain,$username,$authhost)=@_;
 3715:     my %userroles;
 3716:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3717:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
 3718:     my %allroles=();
 3719:     my %allgroups=();   
 3720:     my $now=time;
 3721:     %userroles = ('user.login.time' => $now);
 3722:     my $group_privs;
 3723: 
 3724:     if ($rolesdump ne '') {
 3725:         foreach my $entry (split(/&/,$rolesdump)) {
 3726: 	  if ($entry!~/^rolesdef_/) {
 3727:             my ($area,$role)=split(/=/,$entry);
 3728: 	    $area=~s/\_\w\w$//;
 3729:             my ($trole,$tend,$tstart,$group_privs);
 3730: 	    if ($role=~/^cr/) { 
 3731: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3732: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3733: 		    ($tend,$tstart)=split('_',$trest);
 3734: 		} else {
 3735: 		    $trole=$role;
 3736: 		}
 3737:             } elsif ($role =~ m|^gr/|) {
 3738:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3739:                 ($trole,$group_privs) = split(/\//,$trole);
 3740:                 $group_privs = &unescape($group_privs);
 3741: 	    } else {
 3742: 		($trole,$tend,$tstart)=split(/_/,$role);
 3743: 	    }
 3744: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3745: 					 $username);
 3746: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3747:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3748:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3749:             if (($area ne '') && ($trole ne '')) {
 3750: 		my $spec=$trole.'.'.$area;
 3751: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3752: 		if ($trole =~ /^cr\//) {
 3753:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3754:                 } elsif ($trole eq 'gr') {
 3755:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3756: 		} else {
 3757:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3758: 		}
 3759:             }
 3760:           }
 3761:         }
 3762:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3763:         $userroles{'user.adv'}    = $adv;
 3764: 	$userroles{'user.author'} = $author;
 3765:         $env{'user.adv'}=$adv;
 3766:     }
 3767:     return \%userroles;  
 3768: }
 3769: 
 3770: sub set_arearole {
 3771:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3772: # log the associated role with the area
 3773:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3774:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3775: }
 3776: 
 3777: sub custom_roleprivs {
 3778:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3779:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3780:     my $homsvr=homeserver($rauthor,$rdomain);
 3781:     if (&hostname($homsvr) ne '') {
 3782:         my ($rdummy,$roledef)=
 3783:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3784:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3785:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3786:             if (defined($syspriv)) {
 3787:                 $$allroles{'cm./'}.=':'.$syspriv;
 3788:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3789:             }
 3790:             if ($tdomain ne '') {
 3791:                 if (defined($dompriv)) {
 3792:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3793:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3794:                 }
 3795:                 if (($trest ne '') && (defined($coursepriv))) {
 3796:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3797:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3798:                 }
 3799:             }
 3800:         }
 3801:     }
 3802: }
 3803: 
 3804: sub group_roleprivs {
 3805:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3806:     my $access = 1;
 3807:     my $now = time;
 3808:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3809:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3810:     if ($access) {
 3811:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3812:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3813:     }
 3814: }
 3815: 
 3816: sub standard_roleprivs {
 3817:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3818:     if (defined($pr{$trole.':s'})) {
 3819:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3820:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3821:     }
 3822:     if ($tdomain ne '') {
 3823:         if (defined($pr{$trole.':d'})) {
 3824:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3825:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3826:         }
 3827:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3828:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3829:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3830:         }
 3831:     }
 3832: }
 3833: 
 3834: sub set_userprivs {
 3835:     my ($userroles,$allroles,$allgroups) = @_; 
 3836:     my $author=0;
 3837:     my $adv=0;
 3838:     my %grouproles = ();
 3839:     if (keys(%{$allgroups}) > 0) {
 3840:         foreach my $role (keys %{$allroles}) {
 3841:             my ($trole,$area,$sec,$extendedarea);
 3842:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3843:                 $trole = $1;
 3844:                 $area = $2;
 3845:                 $sec = $3;
 3846:                 $extendedarea = $area.$sec;
 3847:                 if (exists($$allgroups{$area})) {
 3848:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3849:                         my $spec = $trole.'.'.$extendedarea;
 3850:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3851:                                                 $$allgroups{$area}{$group};
 3852:                     }
 3853:                 }
 3854:             }
 3855:         }
 3856:     }
 3857:     foreach my $group (keys(%grouproles)) {
 3858:         $$allroles{$group} = $grouproles{$group};
 3859:     }
 3860:     foreach my $role (keys(%{$allroles})) {
 3861:         my %thesepriv;
 3862:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3863:         foreach my $item (split(/:/,$$allroles{$role})) {
 3864:             if ($item ne '') {
 3865:                 my ($privilege,$restrictions)=split(/&/,$item);
 3866:                 if ($restrictions eq '') {
 3867:                     $thesepriv{$privilege}='F';
 3868:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3869:                     $thesepriv{$privilege}.=$restrictions;
 3870:                 }
 3871:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3872:             }
 3873:         }
 3874:         my $thesestr='';
 3875:         foreach my $priv (keys(%thesepriv)) {
 3876: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3877: 	}
 3878:         $userroles->{'user.priv.'.$role} = $thesestr;
 3879:     }
 3880:     return ($author,$adv);
 3881: }
 3882: 
 3883: sub role_status {
 3884:     my ($rolekey,$then,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 3885:     my @pwhere = ();
 3886:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 3887:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 3888:         unless (!defined($$role) || $$role eq '') {
 3889:             $$where=join('.',@pwhere);
 3890:             $$trolecode=$$role.'.'.$$where;
 3891:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 3892:             $$tstatus='is';
 3893:             if ($$tstart && $$tstart>$then) {
 3894:                 $$tstatus='future';
 3895:                 if ($$tstart<$now) { $$tstatus='will'; }
 3896:             }
 3897:             if ($$tend) {
 3898:                 if ($$tend<$then) {
 3899:                     $$tstatus='expired';
 3900:                 } elsif ($$tend<$now) {
 3901:                     $$tstatus='will_not';
 3902:                 }
 3903:             }
 3904:         }
 3905:     }
 3906: }
 3907: 
 3908: sub check_adhoc_privs {
 3909:     my ($cdom,$cnum,$then,$now,$checkrole) = @_;
 3910:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 3911:     if ($env{$cckey}) {
 3912:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 3913:         &role_status($cckey,$then,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 3914:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 3915:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
 3916:         }
 3917:     } else {
 3918:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
 3919:     }
 3920: }
 3921: 
 3922: sub set_adhoc_privileges {
 3923: # role can be cc or ca
 3924:     my ($dcdom,$pickedcourse,$role) = @_;
 3925:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 3926:     my $spec = $role.'.'.$area;
 3927:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 3928:                                   $env{'user.name'});
 3929:     my %ccrole = ();
 3930:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 3931:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 3932:     &appenv(\%userroles,[$role,'cm']);
 3933:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 3934:     &appenv( {'request.role'        => $spec,
 3935:               'request.role.domain' => $dcdom,
 3936:               'request.course.sec'  => ''
 3937:              }
 3938:            );
 3939:     my $tadv=0;
 3940:     if (&allowed('adv') eq 'F') { $tadv=1; }
 3941:     &appenv({'request.role.adv'    => $tadv});
 3942: }
 3943: 
 3944: # --------------------------------------------------------------- get interface
 3945: 
 3946: sub get {
 3947:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3948:    my $items='';
 3949:    foreach my $item (@$storearr) {
 3950:        $items.=&escape($item).'&';
 3951:    }
 3952:    $items=~s/\&$//;
 3953:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3954:    if (!$uname) { $uname=$env{'user.name'}; }
 3955:    my $uhome=&homeserver($uname,$udomain);
 3956: 
 3957:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3958:    my @pairs=split(/\&/,$rep);
 3959:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3960:      return @pairs;
 3961:    }
 3962:    my %returnhash=();
 3963:    my $i=0;
 3964:    foreach my $item (@$storearr) {
 3965:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3966:       $i++;
 3967:    }
 3968:    return %returnhash;
 3969: }
 3970: 
 3971: # --------------------------------------------------------------- del interface
 3972: 
 3973: sub del {
 3974:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3975:    my $items='';
 3976:    foreach my $item (@$storearr) {
 3977:        $items.=&escape($item).'&';
 3978:    }
 3979: 
 3980:    $items=~s/\&$//;
 3981:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3982:    if (!$uname) { $uname=$env{'user.name'}; }
 3983:    my $uhome=&homeserver($uname,$udomain);
 3984:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3985: }
 3986: 
 3987: # -------------------------------------------------------------- dump interface
 3988: 
 3989: sub dump {
 3990:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3991:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3992:     if (!$uname) { $uname=$env{'user.name'}; }
 3993:     my $uhome=&homeserver($uname,$udomain);
 3994:     if ($regexp) {
 3995: 	$regexp=&escape($regexp);
 3996:     } else {
 3997: 	$regexp='.';
 3998:     }
 3999:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4000:     my @pairs=split(/\&/,$rep);
 4001:     my %returnhash=();
 4002:     foreach my $item (@pairs) {
 4003: 	my ($key,$value)=split(/=/,$item,2);
 4004: 	$key = &unescape($key);
 4005: 	next if ($key =~ /^error: 2 /);
 4006: 	$returnhash{$key}=&thaw_unescape($value);
 4007:     }
 4008:     return %returnhash;
 4009: }
 4010: 
 4011: # --------------------------------------------------------- dumpstore interface
 4012: 
 4013: sub dumpstore {
 4014:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4015:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4016:    if (!$uname) { $uname=$env{'user.name'}; }
 4017:    my $uhome=&homeserver($uname,$udomain);
 4018:    if ($regexp) {
 4019:        $regexp=&escape($regexp);
 4020:    } else {
 4021:        $regexp='.';
 4022:    }
 4023:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4024:    my @pairs=split(/\&/,$rep);
 4025:    my %returnhash=();
 4026:    foreach my $item (@pairs) {
 4027:        my ($key,$value)=split(/=/,$item,2);
 4028:        next if ($key =~ /^error: 2 /);
 4029:        $returnhash{$key}=&thaw_unescape($value);
 4030:    }
 4031:    return %returnhash;
 4032: }
 4033: 
 4034: # -------------------------------------------------------------- keys interface
 4035: 
 4036: sub getkeys {
 4037:    my ($namespace,$udomain,$uname)=@_;
 4038:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4039:    if (!$uname) { $uname=$env{'user.name'}; }
 4040:    my $uhome=&homeserver($uname,$udomain);
 4041:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 4042:    my @keyarray=();
 4043:    foreach my $key (split(/\&/,$rep)) {
 4044:       next if ($key =~ /^error: 2 /);
 4045:       push(@keyarray,&unescape($key));
 4046:    }
 4047:    return @keyarray;
 4048: }
 4049: 
 4050: # --------------------------------------------------------------- currentdump
 4051: sub currentdump {
 4052:    my ($courseid,$sdom,$sname)=@_;
 4053:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 4054:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 4055:    $sname    = $env{'user.name'}         if (! defined($sname));
 4056:    my $uhome = &homeserver($sname,$sdom);
 4057:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 4058:    return if ($rep =~ /^(error:|no_such_host)/);
 4059:    #
 4060:    my %returnhash=();
 4061:    #
 4062:    if ($rep eq "unknown_cmd") { 
 4063:        # an old lond will not know currentdump
 4064:        # Do a dump and make it look like a currentdump
 4065:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 4066:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 4067:        my %hash = @tmp;
 4068:        @tmp=();
 4069:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 4070:    } else {
 4071:        my @pairs=split(/\&/,$rep);
 4072:        foreach my $pair (@pairs) {
 4073:            my ($key,$value)=split(/=/,$pair,2);
 4074:            my ($symb,$param) = split(/:/,$key);
 4075:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 4076:                                                         &thaw_unescape($value);
 4077:        }
 4078:    }
 4079:    return %returnhash;
 4080: }
 4081: 
 4082: sub convert_dump_to_currentdump{
 4083:     my %hash = %{shift()};
 4084:     my %returnhash;
 4085:     # Code ripped from lond, essentially.  The only difference
 4086:     # here is the unescaping done by lonnet::dump().  Conceivably
 4087:     # we might run in to problems with parameter names =~ /^v\./
 4088:     while (my ($key,$value) = each(%hash)) {
 4089:         my ($v,$symb,$param) = split(/:/,$key);
 4090: 	$symb  = &unescape($symb);
 4091: 	$param = &unescape($param);
 4092:         next if ($v eq 'version' || $symb eq 'keys');
 4093:         next if (exists($returnhash{$symb}) &&
 4094:                  exists($returnhash{$symb}->{$param}) &&
 4095:                  $returnhash{$symb}->{'v.'.$param} > $v);
 4096:         $returnhash{$symb}->{$param}=$value;
 4097:         $returnhash{$symb}->{'v.'.$param}=$v;
 4098:     }
 4099:     #
 4100:     # Remove all of the keys in the hashes which keep track of
 4101:     # the version of the parameter.
 4102:     while (my ($symb,$param_hash) = each(%returnhash)) {
 4103:         # use a foreach because we are going to delete from the hash.
 4104:         foreach my $key (keys(%$param_hash)) {
 4105:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 4106:         }
 4107:     }
 4108:     return \%returnhash;
 4109: }
 4110: 
 4111: # ------------------------------------------------------ critical inc interface
 4112: 
 4113: sub cinc {
 4114:     return &inc(@_,'critical');
 4115: }
 4116: 
 4117: # --------------------------------------------------------------- inc interface
 4118: 
 4119: sub inc {
 4120:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 4121:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4122:     if (!$uname) { $uname=$env{'user.name'}; }
 4123:     my $uhome=&homeserver($uname,$udomain);
 4124:     my $items='';
 4125:     if (! ref($store)) {
 4126:         # got a single value, so use that instead
 4127:         $items = &escape($store).'=&';
 4128:     } elsif (ref($store) eq 'SCALAR') {
 4129:         $items = &escape($$store).'=&';        
 4130:     } elsif (ref($store) eq 'ARRAY') {
 4131:         $items = join('=&',map {&escape($_);} @{$store});
 4132:     } elsif (ref($store) eq 'HASH') {
 4133:         while (my($key,$value) = each(%{$store})) {
 4134:             $items.= &escape($key).'='.&escape($value).'&';
 4135:         }
 4136:     }
 4137:     $items=~s/\&$//;
 4138:     if ($critical) {
 4139: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 4140:     } else {
 4141: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 4142:     }
 4143: }
 4144: 
 4145: # --------------------------------------------------------------- put interface
 4146: 
 4147: sub put {
 4148:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4149:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4150:    if (!$uname) { $uname=$env{'user.name'}; }
 4151:    my $uhome=&homeserver($uname,$udomain);
 4152:    my $items='';
 4153:    foreach my $item (keys(%$storehash)) {
 4154:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4155:    }
 4156:    $items=~s/\&$//;
 4157:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4158: }
 4159: 
 4160: # ------------------------------------------------------------ newput interface
 4161: 
 4162: sub newput {
 4163:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4164:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4165:    if (!$uname) { $uname=$env{'user.name'}; }
 4166:    my $uhome=&homeserver($uname,$udomain);
 4167:    my $items='';
 4168:    foreach my $key (keys(%$storehash)) {
 4169:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4170:    }
 4171:    $items=~s/\&$//;
 4172:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 4173: }
 4174: 
 4175: # ---------------------------------------------------------  putstore interface
 4176: 
 4177: sub putstore {
 4178:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4179:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4180:    if (!$uname) { $uname=$env{'user.name'}; }
 4181:    my $uhome=&homeserver($uname,$udomain);
 4182:    my $items='';
 4183:    foreach my $key (keys(%$storehash)) {
 4184:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 4185:    }
 4186:    $items=~s/\&$//;
 4187:    my $esc_symb=&escape($symb);
 4188:    my $esc_v=&escape($version);
 4189:    my $reply =
 4190:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 4191: 	      $uhome);
 4192:    if ($reply eq 'unknown_cmd') {
 4193:        # gfall back to way things use to be done
 4194:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 4195: 			    $uname);
 4196:    }
 4197:    return $reply;
 4198: }
 4199: 
 4200: sub old_putstore {
 4201:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4202:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4203:     if (!$uname) { $uname=$env{'user.name'}; }
 4204:     my $uhome=&homeserver($uname,$udomain);
 4205:     my %newstorehash;
 4206:     foreach my $item (keys(%$storehash)) {
 4207: 	my $key = $version.':'.&escape($symb).':'.$item;
 4208: 	$newstorehash{$key} = $storehash->{$item};
 4209:     }
 4210:     my $items='';
 4211:     my %allitems = ();
 4212:     foreach my $item (keys(%newstorehash)) {
 4213: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 4214: 	    my $key = $1.':keys:'.$2;
 4215: 	    $allitems{$key} .= $3.':';
 4216: 	}
 4217: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 4218:     }
 4219:     foreach my $item (keys(%allitems)) {
 4220: 	$allitems{$item} =~ s/\:$//;
 4221: 	$items.= $item.'='.$allitems{$item}.'&';
 4222:     }
 4223:     $items=~s/\&$//;
 4224:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4225: }
 4226: 
 4227: # ------------------------------------------------------ critical put interface
 4228: 
 4229: sub cput {
 4230:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4231:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4232:    if (!$uname) { $uname=$env{'user.name'}; }
 4233:    my $uhome=&homeserver($uname,$udomain);
 4234:    my $items='';
 4235:    foreach my $item (keys(%$storehash)) {
 4236:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4237:    }
 4238:    $items=~s/\&$//;
 4239:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 4240: }
 4241: 
 4242: # -------------------------------------------------------------- eget interface
 4243: 
 4244: sub eget {
 4245:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4246:    my $items='';
 4247:    foreach my $item (@$storearr) {
 4248:        $items.=&escape($item).'&';
 4249:    }
 4250:    $items=~s/\&$//;
 4251:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4252:    if (!$uname) { $uname=$env{'user.name'}; }
 4253:    my $uhome=&homeserver($uname,$udomain);
 4254:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 4255:    my @pairs=split(/\&/,$rep);
 4256:    my %returnhash=();
 4257:    my $i=0;
 4258:    foreach my $item (@$storearr) {
 4259:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4260:       $i++;
 4261:    }
 4262:    return %returnhash;
 4263: }
 4264: 
 4265: # ------------------------------------------------------------ tmpput interface
 4266: sub tmpput {
 4267:     my ($storehash,$server,$context)=@_;
 4268:     my $items='';
 4269:     foreach my $item (keys(%$storehash)) {
 4270: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4271:     }
 4272:     $items=~s/\&$//;
 4273:     if (defined($context)) {
 4274:         $items .= ':'.&escape($context);
 4275:     }
 4276:     return &reply("tmpput:$items",$server);
 4277: }
 4278: 
 4279: # ------------------------------------------------------------ tmpget interface
 4280: sub tmpget {
 4281:     my ($token,$server)=@_;
 4282:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4283:     my $rep=&reply("tmpget:$token",$server);
 4284:     my %returnhash;
 4285:     foreach my $item (split(/\&/,$rep)) {
 4286: 	my ($key,$value)=split(/=/,$item);
 4287:         next if ($key =~ /^error: 2 /);
 4288: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 4289:     }
 4290:     return %returnhash;
 4291: }
 4292: 
 4293: # ------------------------------------------------------------ tmpget interface
 4294: sub tmpdel {
 4295:     my ($token,$server)=@_;
 4296:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4297:     return &reply("tmpdel:$token",$server);
 4298: }
 4299: 
 4300: # -------------------------------------------------- portfolio access checking
 4301: 
 4302: sub portfolio_access {
 4303:     my ($requrl) = @_;
 4304:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4305:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4306:     if ($result) {
 4307:         my %setters;
 4308:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4309:             my ($startblock,$endblock) =
 4310:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4311:             if ($startblock && $endblock) {
 4312:                 return 'B';
 4313:             }
 4314:         } else {
 4315:             my ($startblock,$endblock) =
 4316:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4317:             if ($startblock && $endblock) {
 4318:                 return 'B';
 4319:             }
 4320:         }
 4321:     }
 4322:     if ($result eq 'ok') {
 4323:        return 'F';
 4324:     } elsif ($result =~ /^[^:]+:guest_/) {
 4325:        return 'A';
 4326:     }
 4327:     return '';
 4328: }
 4329: 
 4330: sub get_portfolio_access {
 4331:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4332: 
 4333:     if (!ref($access_hash)) {
 4334: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4335: 	my %access_controls = &get_access_controls($current_perms,$group,
 4336: 						   $file_name);
 4337: 	$access_hash = $access_controls{$file_name};
 4338:     }
 4339: 
 4340:     my ($public,$guest,@domains,@users,@courses,@groups);
 4341:     my $now = time;
 4342:     if (ref($access_hash) eq 'HASH') {
 4343:         foreach my $key (keys(%{$access_hash})) {
 4344:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4345:             if ($start > $now) {
 4346:                 next;
 4347:             }
 4348:             if ($end && $end<$now) {
 4349:                 next;
 4350:             }
 4351:             if ($scope eq 'public') {
 4352:                 $public = $key;
 4353:                 last;
 4354:             } elsif ($scope eq 'guest') {
 4355:                 $guest = $key;
 4356:             } elsif ($scope eq 'domains') {
 4357:                 push(@domains,$key);
 4358:             } elsif ($scope eq 'users') {
 4359:                 push(@users,$key);
 4360:             } elsif ($scope eq 'course') {
 4361:                 push(@courses,$key);
 4362:             } elsif ($scope eq 'group') {
 4363:                 push(@groups,$key);
 4364:             }
 4365:         }
 4366:         if ($public) {
 4367:             return 'ok';
 4368:         }
 4369:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4370:             if ($guest) {
 4371:                 return $guest;
 4372:             }
 4373:         } else {
 4374:             if (@domains > 0) {
 4375:                 foreach my $domkey (@domains) {
 4376:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4377:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4378:                             return 'ok';
 4379:                         }
 4380:                     }
 4381:                 }
 4382:             }
 4383:             if (@users > 0) {
 4384:                 foreach my $userkey (@users) {
 4385:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4386:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4387:                             if (ref($item) eq 'HASH') {
 4388:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4389:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4390:                                     return 'ok';
 4391:                                 }
 4392:                             }
 4393:                         }
 4394:                     } 
 4395:                 }
 4396:             }
 4397:             my %roleshash;
 4398:             my @courses_and_groups = @courses;
 4399:             push(@courses_and_groups,@groups); 
 4400:             if (@courses_and_groups > 0) {
 4401:                 my (%allgroups,%allroles); 
 4402:                 my ($start,$end,$role,$sec,$group);
 4403:                 foreach my $envkey (%env) {
 4404:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4405:                         my $cid = $2.'_'.$3; 
 4406:                         if ($1 eq 'gr') {
 4407:                             $group = $4;
 4408:                             $allgroups{$cid}{$group} = $env{$envkey};
 4409:                         } else {
 4410:                             if ($4 eq '') {
 4411:                                 $sec = 'none';
 4412:                             } else {
 4413:                                 $sec = $4;
 4414:                             }
 4415:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4416:                         }
 4417:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4418:                         my $cid = $2.'_'.$3;
 4419:                         if ($4 eq '') {
 4420:                             $sec = 'none';
 4421:                         } else {
 4422:                             $sec = $4;
 4423:                         }
 4424:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4425:                     }
 4426:                 }
 4427:                 if (keys(%allroles) == 0) {
 4428:                     return;
 4429:                 }
 4430:                 foreach my $key (@courses_and_groups) {
 4431:                     my %content = %{$$access_hash{$key}};
 4432:                     my $cnum = $content{'number'};
 4433:                     my $cdom = $content{'domain'};
 4434:                     my $cid = $cdom.'_'.$cnum;
 4435:                     if (!exists($allroles{$cid})) {
 4436:                         next;
 4437:                     }    
 4438:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4439:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4440:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4441:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4442:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4443:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4444:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4445:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4446:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4447:                                         if (grep/^all$/,@sections) {
 4448:                                             return 'ok';
 4449:                                         } else {
 4450:                                             if (grep/^$sec$/,@sections) {
 4451:                                                 return 'ok';
 4452:                                             }
 4453:                                         }
 4454:                                     }
 4455:                                 }
 4456:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4457:                                     if (grep/^none$/,@groups) {
 4458:                                         return 'ok';
 4459:                                     }
 4460:                                 } else {
 4461:                                     if (grep/^all$/,@groups) {
 4462:                                         return 'ok';
 4463:                                     } 
 4464:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4465:                                         if (grep/^$group$/,@groups) {
 4466:                                             return 'ok';
 4467:                                         }
 4468:                                     }
 4469:                                 } 
 4470:                             }
 4471:                         }
 4472:                     }
 4473:                 }
 4474:             }
 4475:             if ($guest) {
 4476:                 return $guest;
 4477:             }
 4478:         }
 4479:     }
 4480:     return;
 4481: }
 4482: 
 4483: sub course_group_datechecker {
 4484:     my ($dates,$now,$status) = @_;
 4485:     my ($start,$end) = split(/\./,$dates);
 4486:     if (!$start && !$end) {
 4487:         return 'ok';
 4488:     }
 4489:     if (grep/^active$/,@{$status}) {
 4490:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4491:             return 'ok';
 4492:         }
 4493:     }
 4494:     if (grep/^previous$/,@{$status}) {
 4495:         if ($end > $now ) {
 4496:             return 'ok';
 4497:         }
 4498:     }
 4499:     if (grep/^future$/,@{$status}) {
 4500:         if ($start > $now) {
 4501:             return 'ok';
 4502:         }
 4503:     }
 4504:     return; 
 4505: }
 4506: 
 4507: sub parse_portfolio_url {
 4508:     my ($url) = @_;
 4509: 
 4510:     my ($type,$udom,$unum,$group,$file_name);
 4511:     
 4512:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4513: 	$type = 1;
 4514:         $udom = $1;
 4515:         $unum = $2;
 4516:         $file_name = $3;
 4517:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4518: 	$type = 2;
 4519:         $udom = $1;
 4520:         $unum = $2;
 4521:         $group = $3;
 4522:         $file_name = $3.'/'.$4;
 4523:     }
 4524:     if (wantarray) {
 4525: 	return ($type,$udom,$unum,$file_name,$group);
 4526:     }
 4527:     return $type;
 4528: }
 4529: 
 4530: sub is_portfolio_url {
 4531:     my ($url) = @_;
 4532:     return scalar(&parse_portfolio_url($url));
 4533: }
 4534: 
 4535: sub is_portfolio_file {
 4536:     my ($file) = @_;
 4537:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4538:         return 1;
 4539:     }
 4540:     return;
 4541: }
 4542: 
 4543: sub usertools_access {
 4544:     my ($uname,$udom,$tool,$action,$context) = @_;
 4545:     my ($access,%tools);
 4546:     if ($context eq '') {
 4547:         $context = 'tools';
 4548:     }
 4549:     if ($context eq 'requestcourses') {
 4550:         %tools = (
 4551:                       official   => 1,
 4552:                       unofficial => 1,
 4553:                  );
 4554:     } else {
 4555:         %tools = (
 4556:                       aboutme   => 1,
 4557:                       blog      => 1,
 4558:                       portfolio => 1,
 4559:                  );
 4560:     }
 4561:     return if (!defined($tools{$tool}));
 4562: 
 4563:     if ((!defined($udom)) || (!defined($uname))) {
 4564:         $udom = $env{'user.domain'};
 4565:         $uname = $env{'user.name'};
 4566:     }
 4567: 
 4568:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4569:         if ($action ne 'reload') {
 4570:             if ($context eq 'requestcourses') {
 4571:                 return $env{'environment.canrequest.'.$tool};
 4572:             } else {
 4573:                 return $env{'environment.availabletools.'.$tool};
 4574:             }
 4575:         }
 4576:     }
 4577: 
 4578:     my ($toolstatus,$inststatus);
 4579: 
 4580:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 4581:          ($action ne 'reload')) {
 4582:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 4583:         $inststatus = $env{'environment.inststatus'};
 4584:     } else {
 4585:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool);
 4586:         $toolstatus = $userenv{$context.'.'.$tool};
 4587:         $inststatus = $userenv{'inststatus'};
 4588:     }
 4589: 
 4590:     if ($toolstatus ne '') {
 4591:         if ($toolstatus) {
 4592:             $access = 1;
 4593:         } else {
 4594:             $access = 0;
 4595:         }
 4596:         return $access;
 4597:     }
 4598: 
 4599:     my $is_adv = &is_advanced_user($udom,$uname);
 4600:     my %domdef = &get_domain_defaults($udom);
 4601:     if (ref($domdef{$tool}) eq 'HASH') {
 4602:         if ($is_adv) {
 4603:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 4604:                 if ($domdef{$tool}{'_LC_adv'}) { 
 4605:                     $access = 1;
 4606:                 } else {
 4607:                     $access = 0;
 4608:                 }
 4609:                 return $access;
 4610:             }
 4611:         }
 4612:         if ($inststatus ne '') {
 4613:             my ($hasaccess,$hasnoaccess);
 4614:             foreach my $affiliation (split(/:/,$inststatus)) {
 4615:                 if ($domdef{$tool}{$affiliation} ne '') { 
 4616:                     if ($domdef{$tool}{$affiliation}) {
 4617:                         $hasaccess = 1;
 4618:                     } else {
 4619:                         $hasnoaccess = 1;
 4620:                     }
 4621:                 }
 4622:             }
 4623:             if ($hasaccess || $hasnoaccess) {
 4624:                 if ($hasaccess) {
 4625:                     $access = 1;
 4626:                 } elsif ($hasnoaccess) {
 4627:                     $access = 0; 
 4628:                 }
 4629:                 return $access;
 4630:             }
 4631:         } else {
 4632:             if ($domdef{$tool}{'default'} ne '') {
 4633:                 if ($domdef{$tool}{'default'}) {
 4634:                     $access = 1;
 4635:                 } elsif ($domdef{$tool}{'default'} == 0) {
 4636:                     $access = 0;
 4637:                 }
 4638:                 return $access;
 4639:             }
 4640:         }
 4641:     } else {
 4642:         if ($context eq 'tools') {
 4643:             $access = 1;
 4644:         } else {
 4645:             $access = 0;
 4646:         }
 4647:         return $access;
 4648:     }
 4649: }
 4650: 
 4651: sub is_advanced_user {
 4652:     my ($udom,$uname) = @_;
 4653:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 4654:     my %allroles;
 4655:     my $is_adv;
 4656:     foreach my $role (keys(%roleshash)) {
 4657:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 4658:         my $area = '/'.$tdomain.'/'.$trest;
 4659:         if ($sec ne '') {
 4660:             $area .= '/'.$sec;
 4661:         }
 4662:         if (($area ne '') && ($trole ne '')) {
 4663:             my $spec=$trole.'.'.$area;
 4664:             if ($trole =~ /^cr\//) {
 4665:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4666:             } elsif ($trole ne 'gr') {
 4667:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4668:             }
 4669:         }
 4670:     }
 4671:     foreach my $role (keys(%allroles)) {
 4672:         last if ($is_adv);
 4673:         foreach my $item (split(/:/,$allroles{$role})) {
 4674:             if ($item ne '') {
 4675:                 my ($privilege,$restrictions)=split(/&/,$item);
 4676:                 if ($privilege eq 'adv') {
 4677:                     $is_adv = 1;
 4678:                     last;
 4679:                 }
 4680:             }
 4681:         }
 4682:     }
 4683:     return $is_adv;
 4684: }
 4685: 
 4686: # ---------------------------------------------- Custom access rule evaluation
 4687: 
 4688: sub customaccess {
 4689:     my ($priv,$uri)=@_;
 4690:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4691:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4692:     $udom = &LONCAPA::clean_domain($udom);
 4693:     $ucrs = &LONCAPA::clean_username($ucrs);
 4694:     my $access=0;
 4695:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4696: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4697: 	if ($type eq 'user') {
 4698: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4699: 		my ($tdom,$tuname)=split(m{/},$scope);
 4700: 		if ($tdom) {
 4701: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4702: 		}
 4703: 		if ($tuname) {
 4704: 		    if ($tuname ne $env{'user.name'}) { next; }
 4705: 		}
 4706: 		$access=($effect eq 'allow');
 4707: 		last;
 4708: 	    }
 4709: 	} else {
 4710: 	    if ($role) {
 4711: 		if ($role ne $urole) { next; }
 4712: 	    }
 4713: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4714: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4715: 		if ($tdom) {
 4716: 		    if ($tdom ne $udom) { next; }
 4717: 		}
 4718: 		if ($tcrs) {
 4719: 		    if ($tcrs ne $ucrs) { next; }
 4720: 		}
 4721: 		if ($tsec) {
 4722: 		    if ($tsec ne $usec) { next; }
 4723: 		}
 4724: 		$access=($effect eq 'allow');
 4725: 		last;
 4726: 	    }
 4727: 	    if ($realm eq '' && $role eq '') {
 4728: 		$access=($effect eq 'allow');
 4729: 	    }
 4730: 	}
 4731:     }
 4732:     return $access;
 4733: }
 4734: 
 4735: # ------------------------------------------------- Check for a user privilege
 4736: 
 4737: sub allowed {
 4738:     my ($priv,$uri,$symb,$role)=@_;
 4739:     my $ver_orguri=$uri;
 4740:     $uri=&deversion($uri);
 4741:     my $orguri=$uri;
 4742:     $uri=&declutter($uri);
 4743: 
 4744:     if ($priv eq 'evb') {
 4745: # Evade communication block restrictions for specified role in a course
 4746:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4747:             return $1;
 4748:         } else {
 4749:             return;
 4750:         }
 4751:     }
 4752: 
 4753:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4754: # Free bre access to adm and meta resources
 4755:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4756: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4757: 	&& ($priv eq 'bre')) {
 4758: 	return 'F';
 4759:     }
 4760: 
 4761: # Free bre access to user's own portfolio contents
 4762:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4763:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4764: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4765:         my %setters;
 4766:         my ($startblock,$endblock) = 
 4767:             &Apache::loncommon::blockcheck(\%setters,'port');
 4768:         if ($startblock && $endblock) {
 4769:             return 'B';
 4770:         } else {
 4771:             return 'F';
 4772:         }
 4773:     }
 4774: 
 4775: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4776:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4777:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4778:         if (exists($env{'request.course.id'})) {
 4779:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4780:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4781:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4782:                 my $courseprivid=$env{'request.course.id'};
 4783:                 $courseprivid=~s/\_/\//;
 4784:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4785:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4786:                     return $1; 
 4787:                 } else {
 4788:                     if ($env{'request.course.sec'}) {
 4789:                         $courseprivid.='/'.$env{'request.course.sec'};
 4790:                     }
 4791:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4792:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4793:                         return $2;
 4794:                     }
 4795:                 }
 4796:             }
 4797:         }
 4798:     }
 4799: 
 4800: # Free bre to public access
 4801: 
 4802:     if ($priv eq 'bre') {
 4803:         my $copyright=&metadata($uri,'copyright');
 4804: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4805:            return 'F'; 
 4806:         }
 4807:         if ($copyright eq 'priv') {
 4808:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4809: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4810: 		return '';
 4811:             }
 4812:         }
 4813:         if ($copyright eq 'domain') {
 4814:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4815: 	    unless (($env{'user.domain'} eq $1) ||
 4816:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4817: 		return '';
 4818:             }
 4819:         }
 4820:         if ($env{'request.role'}=~ /li\.\//) {
 4821:             # Library role, so allow browsing of resources in this domain.
 4822:             return 'F';
 4823:         }
 4824:         if ($copyright eq 'custom') {
 4825: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4826:         }
 4827:     }
 4828:     # Domain coordinator is trying to create a course
 4829:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4830:         # uri is the requested domain in this case.
 4831:         # comparison to 'request.role.domain' shows if the user has selected
 4832:         # a role of dc for the domain in question.
 4833:         return 'F' if ($uri eq $env{'request.role.domain'});
 4834:     }
 4835: 
 4836:     my $thisallowed='';
 4837:     my $statecond=0;
 4838:     my $courseprivid='';
 4839: 
 4840: # Course
 4841: 
 4842:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4843:        $thisallowed.=$1;
 4844:     }
 4845: 
 4846: # Domain
 4847: 
 4848:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4849:        =~/\Q$priv\E\&([^\:]*)/) {
 4850:        $thisallowed.=$1;
 4851:     }
 4852: 
 4853: # Course: uri itself is a course
 4854:     my $courseuri=$uri;
 4855:     $courseuri=~s/\_(\d)/\/$1/;
 4856:     $courseuri=~s/^([^\/])/\/$1/;
 4857: 
 4858:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 4859:        =~/\Q$priv\E\&([^\:]*)/) {
 4860:        $thisallowed.=$1;
 4861:     }
 4862: 
 4863: # URI is an uploaded document for this course, default permissions don't matter
 4864: # not allowing 'edit' access (editupload) to uploaded course docs
 4865:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 4866: 	$thisallowed='';
 4867:         my ($match)=&is_on_map($uri);
 4868:         if ($match) {
 4869:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 4870:                   =~/\Q$priv\E\&([^\:]*)/) {
 4871:                 $thisallowed.=$1;
 4872:             }
 4873:         } else {
 4874:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 4875:             if ($refuri) {
 4876:                 if ($refuri =~ m|^/adm/|) {
 4877:                     $thisallowed='F';
 4878:                 } else {
 4879:                     $refuri=&declutter($refuri);
 4880:                     my ($match) = &is_on_map($refuri);
 4881:                     if ($match) {
 4882:                         $thisallowed='F';
 4883:                     }
 4884:                 }
 4885:             }
 4886:         }
 4887:     }
 4888: 
 4889:     if ($priv eq 'bre'
 4890: 	&& $thisallowed ne 'F' 
 4891: 	&& $thisallowed ne '2'
 4892: 	&& &is_portfolio_url($uri)) {
 4893: 	$thisallowed = &portfolio_access($uri);
 4894:     }
 4895:     
 4896: # Full access at system, domain or course-wide level? Exit.
 4897:     if ($thisallowed=~/F/) {
 4898: 	return 'F';
 4899:     }
 4900: 
 4901: # If this is generating or modifying users, exit with special codes
 4902: 
 4903:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4904: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4905: 	    my ($audom,$auname)=split('/',$uri);
 4906: # no author name given, so this just checks on the general right to make a co-author in this domain
 4907: 	    unless ($auname) { return $thisallowed; }
 4908: # an author name is given, so we are about to actually make a co-author for a certain account
 4909: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4910: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 4911: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 4912: 	}
 4913: 	return $thisallowed;
 4914:     }
 4915: #
 4916: # Gathered so far: system, domain and course wide privileges
 4917: #
 4918: # Course: See if uri or referer is an individual resource that is part of 
 4919: # the course
 4920: 
 4921:     if ($env{'request.course.id'}) {
 4922: 
 4923:        $courseprivid=$env{'request.course.id'};
 4924:        if ($env{'request.course.sec'}) {
 4925:           $courseprivid.='/'.$env{'request.course.sec'};
 4926:        }
 4927:        $courseprivid=~s/\_/\//;
 4928:        my $checkreferer=1;
 4929:        my ($match,$cond)=&is_on_map($uri);
 4930:        if ($match) {
 4931:            $statecond=$cond;
 4932:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4933:                =~/\Q$priv\E\&([^\:]*)/) {
 4934:                $thisallowed.=$1;
 4935:                $checkreferer=0;
 4936:            }
 4937:        }
 4938:        
 4939:        if ($checkreferer) {
 4940: 	  my $refuri=$env{'httpref.'.$orguri};
 4941:             unless ($refuri) {
 4942:                 foreach my $key (keys(%env)) {
 4943: 		    if ($key=~/^httpref\..*\*/) {
 4944: 			my $pattern=$key;
 4945:                         $pattern=~s/^httpref\.\/res\///;
 4946:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4947:                         $pattern=~s/\//\\\//g;
 4948:                         if ($orguri=~/$pattern/) {
 4949: 			    $refuri=$env{$key};
 4950:                         }
 4951:                     }
 4952:                 }
 4953:             }
 4954: 
 4955:          if ($refuri) { 
 4956: 	  $refuri=&declutter($refuri);
 4957:           my ($match,$cond)=&is_on_map($refuri);
 4958:             if ($match) {
 4959:               my $refstatecond=$cond;
 4960:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4961:                   =~/\Q$priv\E\&([^\:]*)/) {
 4962:                   $thisallowed.=$1;
 4963:                   $uri=$refuri;
 4964:                   $statecond=$refstatecond;
 4965:               }
 4966:           }
 4967:         }
 4968:        }
 4969:    }
 4970: 
 4971: #
 4972: # Gathered now: all privileges that could apply, and condition number
 4973: # 
 4974: #
 4975: # Full or no access?
 4976: #
 4977: 
 4978:     if ($thisallowed=~/F/) {
 4979: 	return 'F';
 4980:     }
 4981: 
 4982:     unless ($thisallowed) {
 4983:         return '';
 4984:     }
 4985: 
 4986: # Restrictions exist, deal with them
 4987: #
 4988: #   C:according to course preferences
 4989: #   R:according to resource settings
 4990: #   L:unless locked
 4991: #   X:according to user session state
 4992: #
 4993: 
 4994: # Possibly locked functionality, check all courses
 4995: # Locks might take effect only after 10 minutes cache expiration for other
 4996: # courses, and 2 minutes for current course
 4997: 
 4998:     my $envkey;
 4999:     if ($thisallowed=~/L/) {
 5000:         foreach $envkey (keys %env) {
 5001:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 5002:                my $courseid=$2;
 5003:                my $roleid=$1.'.'.$2;
 5004:                $courseid=~s/^\///;
 5005:                my $expiretime=600;
 5006:                if ($env{'request.role'} eq $roleid) {
 5007: 		  $expiretime=120;
 5008:                }
 5009: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 5010:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 5011:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 5012: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 5013:                }
 5014:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5015:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 5016: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 5017:                        &log($env{'user.domain'},$env{'user.name'},
 5018:                             $env{'user.home'},
 5019:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 5020:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5021:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5022: 		       return '';
 5023:                    }
 5024:                }
 5025:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5026:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 5027: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 5028:                        &log($env{'user.domain'},$env{'user.name'},
 5029:                             $env{'user.home'},
 5030:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 5031:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5032:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5033: 		       return '';
 5034:                    }
 5035:                }
 5036: 	   }
 5037:        }
 5038:     }
 5039:    
 5040: #
 5041: # Rest of the restrictions depend on selected course
 5042: #
 5043: 
 5044:     unless ($env{'request.course.id'}) {
 5045: 	if ($thisallowed eq 'A') {
 5046: 	    return 'A';
 5047:         } elsif ($thisallowed eq 'B') {
 5048:             return 'B';
 5049: 	} else {
 5050: 	    return '1';
 5051: 	}
 5052:     }
 5053: 
 5054: #
 5055: # Now user is definitely in a course
 5056: #
 5057: 
 5058: 
 5059: # Course preferences
 5060: 
 5061:    if ($thisallowed=~/C/) {
 5062:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5063:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 5064:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 5065: 	   =~/\Q$rolecode\E/) {
 5066: 	   if ($priv ne 'pch') { 
 5067: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5068: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 5069: 			$env{'request.course.id'});
 5070: 	   }
 5071:            return '';
 5072:        }
 5073: 
 5074:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 5075: 	   =~/\Q$unamedom\E/) {
 5076: 	   if ($priv ne 'pch') { 
 5077: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 5078: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 5079: 			$env{'request.course.id'});
 5080: 	   }
 5081:            return '';
 5082:        }
 5083:    }
 5084: 
 5085: # Resource preferences
 5086: 
 5087:    if ($thisallowed=~/R/) {
 5088:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5089:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 5090: 	   if ($priv ne 'pch') { 
 5091: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5092: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 5093: 	   }
 5094: 	   return '';
 5095:        }
 5096:    }
 5097: 
 5098: # Restricted by state or randomout?
 5099: 
 5100:    if ($thisallowed=~/X/) {
 5101:       if ($env{'acc.randomout'}) {
 5102: 	 if (!$symb) { $symb=&symbread($uri,1); }
 5103:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 5104:             return ''; 
 5105:          }
 5106:       }
 5107:       if (&condval($statecond)) {
 5108: 	 return '2';
 5109:       } else {
 5110:          return '';
 5111:       }
 5112:    }
 5113: 
 5114:     if ($thisallowed eq 'A') {
 5115: 	return 'A';
 5116:     } elsif ($thisallowed eq 'B') {
 5117:         return 'B';
 5118:     }
 5119:    return 'F';
 5120: }
 5121: 
 5122: sub split_uri_for_cond {
 5123:     my $uri=&deversion(&declutter(shift));
 5124:     my @uriparts=split(/\//,$uri);
 5125:     my $filename=pop(@uriparts);
 5126:     my $pathname=join('/',@uriparts);
 5127:     return ($pathname,$filename);
 5128: }
 5129: # --------------------------------------------------- Is a resource on the map?
 5130: 
 5131: sub is_on_map {
 5132:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 5133:     #Trying to find the conditional for the file
 5134:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 5135: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 5136:     if ($match) {
 5137: 	return (1,$1);
 5138:     } else {
 5139: 	return (0,0);
 5140:     }
 5141: }
 5142: 
 5143: # --------------------------------------------------------- Get symb from alias
 5144: 
 5145: sub get_symb_from_alias {
 5146:     my $symb=shift;
 5147:     my ($map,$resid,$url)=&decode_symb($symb);
 5148: # Already is a symb
 5149:     if ($url) { return $symb; }
 5150: # Must be an alias
 5151:     my $aliassymb='';
 5152:     my %bighash;
 5153:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5154:                             &GDBM_READER(),0640)) {
 5155:         my $rid=$bighash{'mapalias_'.$symb};
 5156: 	if ($rid) {
 5157: 	    my ($mapid,$resid)=split(/\./,$rid);
 5158: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 5159: 				    $resid,$bighash{'src_'.$rid});
 5160: 	}
 5161:         untie %bighash;
 5162:     }
 5163:     return $aliassymb;
 5164: }
 5165: 
 5166: # ----------------------------------------------------------------- Define Role
 5167: 
 5168: sub definerole {
 5169:   if (allowed('mcr','/')) {
 5170:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 5171:     foreach my $role (split(':',$sysrole)) {
 5172: 	my ($crole,$cqual)=split(/\&/,$role);
 5173:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 5174:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 5175: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5176:                return "refused:s:$crole&$cqual"; 
 5177:             }
 5178:         }
 5179:     }
 5180:     foreach my $role (split(':',$domrole)) {
 5181: 	my ($crole,$cqual)=split(/\&/,$role);
 5182:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 5183:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 5184: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 5185:                return "refused:d:$crole&$cqual"; 
 5186:             }
 5187:         }
 5188:     }
 5189:     foreach my $role (split(':',$courole)) {
 5190: 	my ($crole,$cqual)=split(/\&/,$role);
 5191:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 5192:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 5193: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5194:                return "refused:c:$crole&$cqual"; 
 5195:             }
 5196:         }
 5197:     }
 5198:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5199:                 "$env{'user.domain'}:$env{'user.name'}:".
 5200: 	        "rolesdef_$rolename=".
 5201:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 5202:     return reply($command,$env{'user.home'});
 5203:   } else {
 5204:     return 'refused';
 5205:   }
 5206: }
 5207: 
 5208: # ---------------- Make a metadata query against the network of library servers
 5209: 
 5210: sub metadata_query {
 5211:     my ($query,$custom,$customshow,$server_array)=@_;
 5212:     my %rhash;
 5213:     my %libserv = &all_library();
 5214:     my @server_list = (defined($server_array) ? @$server_array
 5215:                                               : keys(%libserv) );
 5216:     for my $server (@server_list) {
 5217: 	unless ($custom or $customshow) {
 5218: 	    my $reply=&reply("querysend:".&escape($query),$server);
 5219: 	    $rhash{$server}=$reply;
 5220: 	}
 5221: 	else {
 5222: 	    my $reply=&reply("querysend:".&escape($query).':'.
 5223: 			     &escape($custom).':'.&escape($customshow),
 5224: 			     $server);
 5225: 	    $rhash{$server}=$reply;
 5226: 	}
 5227:     }
 5228:     return \%rhash;
 5229: }
 5230: 
 5231: # ----------------------------------------- Send log queries and wait for reply
 5232: 
 5233: sub log_query {
 5234:     my ($uname,$udom,$query,%filters)=@_;
 5235:     my $uhome=&homeserver($uname,$udom);
 5236:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 5237:     my $uhost=&hostname($uhome);
 5238:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 5239:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 5240:                        $uhome);
 5241:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 5242:     return get_query_reply($queryid);
 5243: }
 5244: 
 5245: # -------------------------- Update MySQL table for portfolio file
 5246: 
 5247: sub update_portfolio_table {
 5248:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 5249:     if ($group ne '') {
 5250:         $file_name =~s /^\Q$group\E//;
 5251:     }
 5252:     my $homeserver = &homeserver($uname,$udom);
 5253:     my $queryid=
 5254:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 5255:                ':'.&escape($file_name).':'.$action,$homeserver);
 5256:     my $reply = &get_query_reply($queryid);
 5257:     return $reply;
 5258: }
 5259: 
 5260: # -------------------------- Update MySQL allusers table
 5261: 
 5262: sub update_allusers_table {
 5263:     my ($uname,$udom,$names) = @_;
 5264:     my $homeserver = &homeserver($uname,$udom);
 5265:     my $queryid=
 5266:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 5267:                'lastname='.&escape($names->{'lastname'}).'%%'.
 5268:                'firstname='.&escape($names->{'firstname'}).'%%'.
 5269:                'middlename='.&escape($names->{'middlename'}).'%%'.
 5270:                'generation='.&escape($names->{'generation'}).'%%'.
 5271:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 5272:                'id='.&escape($names->{'id'}),$homeserver);
 5273:     my $reply = &get_query_reply($queryid);
 5274:     return $reply;
 5275: }
 5276: 
 5277: # ------- Request retrieval of institutional classlists for course(s)
 5278: 
 5279: sub fetch_enrollment_query {
 5280:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 5281:     my $homeserver;
 5282:     my $maxtries = 1;
 5283:     if ($context eq 'automated') {
 5284:         $homeserver = $perlvar{'lonHostID'};
 5285:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 5286:     } else {
 5287:         $homeserver = &homeserver($cnum,$dom);
 5288:     }
 5289:     my $host=&hostname($homeserver);
 5290:     my $cmd = '';
 5291:     foreach my $affiliate (keys %{$affiliatesref}) {
 5292:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5293:     }
 5294:     $cmd =~ s/%%$//;
 5295:     $cmd = &escape($cmd);
 5296:     my $query = 'fetchenrollment';
 5297:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 5298:     unless ($queryid=~/^\Q$host\E\_/) { 
 5299:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 5300:         return 'error: '.$queryid;
 5301:     }
 5302:     my $reply = &get_query_reply($queryid);
 5303:     my $tries = 1;
 5304:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5305:         $reply = &get_query_reply($queryid);
 5306:         $tries ++;
 5307:     }
 5308:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5309:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5310:     } else {
 5311:         my @responses = split(/:/,$reply);
 5312:         if ($homeserver eq $perlvar{'lonHostID'}) {
 5313:             foreach my $line (@responses) {
 5314:                 my ($key,$value) = split(/=/,$line,2);
 5315:                 $$replyref{$key} = $value;
 5316:             }
 5317:         } else {
 5318:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 5319:             foreach my $line (@responses) {
 5320:                 my ($key,$value) = split(/=/,$line);
 5321:                 $$replyref{$key} = $value;
 5322:                 if ($value > 0) {
 5323:                     foreach my $item (@{$$affiliatesref{$key}}) {
 5324:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 5325:                         my $destname = $pathname.'/'.$filename;
 5326:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 5327:                         if ($xml_classlist =~ /^error/) {
 5328:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 5329:                         } else {
 5330:                             if ( open(FILE,">$destname") ) {
 5331:                                 print FILE &unescape($xml_classlist);
 5332:                                 close(FILE);
 5333:                             } else {
 5334:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 5335:                             }
 5336:                         }
 5337:                     }
 5338:                 }
 5339:             }
 5340:         }
 5341:         return 'ok';
 5342:     }
 5343:     return 'error';
 5344: }
 5345: 
 5346: sub get_query_reply {
 5347:     my $queryid=shift;
 5348:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 5349:     my $reply='';
 5350:     for (1..100) {
 5351: 	sleep 2;
 5352:         if (-e $replyfile.'.end') {
 5353: 	    if (open(my $fh,$replyfile)) {
 5354: 		$reply = join('',<$fh>);
 5355: 		close($fh);
 5356: 	   } else { return 'error: reply_file_error'; }
 5357:            return &unescape($reply);
 5358: 	}
 5359:     }
 5360:     return 'timeout:'.$queryid;
 5361: }
 5362: 
 5363: sub courselog_query {
 5364: #
 5365: # possible filters:
 5366: # url: url or symb
 5367: # username
 5368: # domain
 5369: # action: view, submit, grade
 5370: # start: timestamp
 5371: # end: timestamp
 5372: #
 5373:     my (%filters)=@_;
 5374:     unless ($env{'request.course.id'}) { return 'no_course'; }
 5375:     if ($filters{'url'}) {
 5376: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 5377:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 5378:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 5379:     }
 5380:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5381:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5382:     return &log_query($cname,$cdom,'courselog',%filters);
 5383: }
 5384: 
 5385: sub userlog_query {
 5386: #
 5387: # possible filters:
 5388: # action: log check role
 5389: # start: timestamp
 5390: # end: timestamp
 5391: #
 5392:     my ($uname,$udom,%filters)=@_;
 5393:     return &log_query($uname,$udom,'userlog',%filters);
 5394: }
 5395: 
 5396: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 5397: 
 5398: sub auto_run {
 5399:     my ($cnum,$cdom) = @_;
 5400:     my $response = 0;
 5401:     my $settings;
 5402:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 5403:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5404:         $settings = $domconfig{'autoenroll'};
 5405:         if ($settings->{'run'} eq '1') {
 5406:             $response = 1;
 5407:         }
 5408:     } else {
 5409:         my $homeserver;
 5410:         if (&is_course($cdom,$cnum)) {
 5411:             $homeserver = &homeserver($cnum,$cdom);
 5412:         } else {
 5413:             $homeserver = &domain($cdom,'primary');
 5414:         }
 5415:         if ($homeserver ne 'no_host') {
 5416:             $response = &reply('autorun:'.$cdom,$homeserver);
 5417:         }
 5418:     }
 5419:     return $response;
 5420: }
 5421: 
 5422: sub auto_get_sections {
 5423:     my ($cnum,$cdom,$inst_coursecode) = @_;
 5424:     my $homeserver = &homeserver($cnum,$cdom);
 5425:     my @secs = ();
 5426:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 5427:     unless ($response eq 'refused') {
 5428:         @secs = split(/:/,$response);
 5429:     }
 5430:     return @secs;
 5431: }
 5432: 
 5433: sub auto_new_course {
 5434:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 5435:     my $homeserver = &homeserver($cnum,$cdom);
 5436:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 5437:     return $response;
 5438: }
 5439: 
 5440: sub auto_validate_courseID {
 5441:     my ($cnum,$cdom,$inst_course_id) = @_;
 5442:     my $homeserver = &homeserver($cnum,$cdom);
 5443:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5444:     return $response;
 5445: }
 5446: 
 5447: sub auto_create_password {
 5448:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5449:     my ($homeserver,$response);
 5450:     my $create_passwd = 0;
 5451:     my $authchk = '';
 5452:     if ($udom =~ /^$match_domain$/) {
 5453:         $homeserver = &domain($udom,'primary');
 5454:     }
 5455:     if ($homeserver eq '') {
 5456:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5457:             $homeserver = &homeserver($cnum,$cdom);
 5458:         }
 5459:     }
 5460:     if ($homeserver eq '') {
 5461:         $authchk = 'nodomain';
 5462:     } else {
 5463:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5464:         if ($response eq 'refused') {
 5465:             $authchk = 'refused';
 5466:         } else {
 5467:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5468:         }
 5469:     }
 5470:     return ($authparam,$create_passwd,$authchk);
 5471: }
 5472: 
 5473: sub auto_photo_permission {
 5474:     my ($cnum,$cdom,$students) = @_;
 5475:     my $homeserver = &homeserver($cnum,$cdom);
 5476:     my ($outcome,$perm_reqd,$conditions) = 
 5477: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5478:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5479: 	return (undef,undef);
 5480:     }
 5481:     return ($outcome,$perm_reqd,$conditions);
 5482: }
 5483: 
 5484: sub auto_checkphotos {
 5485:     my ($uname,$udom,$pid) = @_;
 5486:     my $homeserver = &homeserver($uname,$udom);
 5487:     my ($result,$resulttype);
 5488:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5489: 				   &escape($uname).':'.&escape($pid),
 5490: 				   $homeserver));
 5491:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5492: 	return (undef,undef);
 5493:     }
 5494:     if ($outcome) {
 5495:         ($result,$resulttype) = split(/:/,$outcome);
 5496:     } 
 5497:     return ($result,$resulttype);
 5498: }
 5499: 
 5500: sub auto_photochoice {
 5501:     my ($cnum,$cdom) = @_;
 5502:     my $homeserver = &homeserver($cnum,$cdom);
 5503:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5504: 						       &escape($cdom),
 5505: 						       $homeserver)));
 5506:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5507: 	return (undef,undef);
 5508:     }
 5509:     return ($update,$comment);
 5510: }
 5511: 
 5512: sub auto_photoupdate {
 5513:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5514:     my $homeserver = &homeserver($cnum,$dom);
 5515:     my $host=&hostname($homeserver);
 5516:     my $cmd = '';
 5517:     my $maxtries = 1;
 5518:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5519:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5520:     }
 5521:     $cmd =~ s/%%$//;
 5522:     $cmd = &escape($cmd);
 5523:     my $query = 'institutionalphotos';
 5524:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5525:     unless ($queryid=~/^\Q$host\E\_/) {
 5526:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5527:         return 'error: '.$queryid;
 5528:     }
 5529:     my $reply = &get_query_reply($queryid);
 5530:     my $tries = 1;
 5531:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5532:         $reply = &get_query_reply($queryid);
 5533:         $tries ++;
 5534:     }
 5535:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5536:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5537:     } else {
 5538:         my @responses = split(/:/,$reply);
 5539:         my $outcome = shift(@responses); 
 5540:         foreach my $item (@responses) {
 5541:             my ($key,$value) = split(/=/,$item);
 5542:             $$photo{$key} = $value;
 5543:         }
 5544:         return $outcome;
 5545:     }
 5546:     return 'error';
 5547: }
 5548: 
 5549: sub auto_instcode_format {
 5550:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5551: 	$cat_order) = @_;
 5552:     my $courses = '';
 5553:     my @homeservers;
 5554:     if ($caller eq 'global') {
 5555: 	my %servers = &get_servers($codedom,'library');
 5556: 	foreach my $tryserver (keys(%servers)) {
 5557: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5558: 		push(@homeservers,$tryserver);
 5559: 	    }
 5560:         }
 5561:     } else {
 5562:         push(@homeservers,&homeserver($caller,$codedom));
 5563:     }
 5564:     foreach my $code (keys(%{$instcodes})) {
 5565:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5566:     }
 5567:     chop($courses);
 5568:     my $ok_response = 0;
 5569:     my $response;
 5570:     while (@homeservers > 0 && $ok_response == 0) {
 5571:         my $server = shift(@homeservers); 
 5572:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5573:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5574:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5575: 		split(/:/,$response);
 5576:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5577:             push(@{$codetitles},&str2array($codetitles_str));
 5578:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5579:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5580:             $ok_response = 1;
 5581:         }
 5582:     }
 5583:     if ($ok_response) {
 5584:         return 'ok';
 5585:     } else {
 5586:         return $response;
 5587:     }
 5588: }
 5589: 
 5590: sub auto_instcode_defaults {
 5591:     my ($domain,$returnhash,$code_order) = @_;
 5592:     my @homeservers;
 5593: 
 5594:     my %servers = &get_servers($domain,'library');
 5595:     foreach my $tryserver (keys(%servers)) {
 5596: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5597: 	    push(@homeservers,$tryserver);
 5598: 	}
 5599:     }
 5600: 
 5601:     my $response;
 5602:     foreach my $server (@homeservers) {
 5603:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5604:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5605: 	
 5606: 	foreach my $pair (split(/\&/,$response)) {
 5607: 	    my ($name,$value)=split(/\=/,$pair);
 5608: 	    if ($name eq 'code_order') {
 5609: 		@{$code_order} = split(/\&/,&unescape($value));
 5610: 	    } else {
 5611: 		$returnhash->{&unescape($name)}=&unescape($value);
 5612: 	    }
 5613: 	}
 5614: 	return 'ok';
 5615:     }
 5616: 
 5617:     return $response;
 5618: } 
 5619: 
 5620: sub auto_validate_class_sec {
 5621:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5622:     my $homeserver = &homeserver($cnum,$cdom);
 5623:     my $ownerlist;
 5624:     if (ref($owners) eq 'ARRAY') {
 5625:         $ownerlist = join(',',@{$owners});
 5626:     } else {
 5627:         $ownerlist = $owners;
 5628:     }
 5629:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 5630:                         &escape($ownerlist).':'.$cdom,$homeserver);
 5631:     return $response;
 5632: }
 5633: 
 5634: # ------------------------------------------------------- Course Group routines
 5635: 
 5636: sub get_coursegroups {
 5637:     my ($cdom,$cnum,$group,$namespace) = @_;
 5638:     return(&dump($namespace,$cdom,$cnum,$group));
 5639: }
 5640: 
 5641: sub modify_coursegroup {
 5642:     my ($cdom,$cnum,$groupsettings) = @_;
 5643:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 5644: }
 5645: 
 5646: sub toggle_coursegroup_status {
 5647:     my ($cdom,$cnum,$group,$action) = @_;
 5648:     my ($from_namespace,$to_namespace);
 5649:     if ($action eq 'delete') {
 5650:         $from_namespace = 'coursegroups';
 5651:         $to_namespace = 'deleted_groups';
 5652:     } else {
 5653:         $from_namespace = 'deleted_groups';
 5654:         $to_namespace = 'coursegroups';
 5655:     }
 5656:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 5657:     if (my $tmp = &error(%curr_group)) {
 5658:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 5659:         return ('read error',$tmp);
 5660:     } else {
 5661:         my %savedsettings = %curr_group; 
 5662:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 5663:         my $deloutcome;
 5664:         if ($result eq 'ok') {
 5665:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 5666:         } else {
 5667:             return ('write error',$result);
 5668:         }
 5669:         if ($deloutcome eq 'ok') {
 5670:             return 'ok';
 5671:         } else {
 5672:             return ('delete error',$deloutcome);
 5673:         }
 5674:     }
 5675: }
 5676: 
 5677: sub modify_group_roles {
 5678:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 5679:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 5680:     my $role = 'gr/'.&escape($userprivs);
 5681:     my ($uname,$udom) = split(/:/,$user);
 5682:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 5683:     if ($result eq 'ok') {
 5684:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 5685:     }
 5686:     return $result;
 5687: }
 5688: 
 5689: sub modify_coursegroup_membership {
 5690:     my ($cdom,$cnum,$membership) = @_;
 5691:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 5692:     return $result;
 5693: }
 5694: 
 5695: sub get_active_groups {
 5696:     my ($udom,$uname,$cdom,$cnum) = @_;
 5697:     my $now = time;
 5698:     my %groups = ();
 5699:     foreach my $key (keys(%env)) {
 5700:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 5701:             my ($start,$end) = split(/\./,$env{$key});
 5702:             if (($end!=0) && ($end<$now)) { next; }
 5703:             if (($start!=0) && ($start>$now)) { next; }
 5704:             if ($1 eq $cdom && $2 eq $cnum) {
 5705:                 $groups{$3} = $env{$key} ;
 5706:             }
 5707:         }
 5708:     }
 5709:     return %groups;
 5710: }
 5711: 
 5712: sub get_group_membership {
 5713:     my ($cdom,$cnum,$group) = @_;
 5714:     return(&dump('groupmembership',$cdom,$cnum,$group));
 5715: }
 5716: 
 5717: sub get_users_groups {
 5718:     my ($udom,$uname,$courseid) = @_;
 5719:     my @usersgroups;
 5720:     my $cachetime=1800;
 5721: 
 5722:     my $hashid="$udom:$uname:$courseid";
 5723:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 5724:     if (defined($cached)) {
 5725:         @usersgroups = split(/:/,$grouplist);
 5726:     } else {  
 5727:         $grouplist = '';
 5728:         my $courseurl = &courseid_to_courseurl($courseid);
 5729:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 5730:         my $access_end = $env{'course.'.$courseid.
 5731:                               '.default_enrollment_end_date'};
 5732:         my $now = time;
 5733:         foreach my $key (keys(%roleshash)) {
 5734:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 5735:                 my $group = $1;
 5736:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 5737:                     my $start = $2;
 5738:                     my $end = $1;
 5739:                     if ($start == -1) { next; } # deleted from group
 5740:                     if (($start!=0) && ($start>$now)) { next; }
 5741:                     if (($end!=0) && ($end<$now)) {
 5742:                         if ($access_end && $access_end < $now) {
 5743:                             if ($access_end - $end < 86400) {
 5744:                                 push(@usersgroups,$group);
 5745:                             }
 5746:                         }
 5747:                         next;
 5748:                     }
 5749:                     push(@usersgroups,$group);
 5750:                 }
 5751:             }
 5752:         }
 5753:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 5754:         $grouplist = join(':',@usersgroups);
 5755:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 5756:     }
 5757:     return @usersgroups;
 5758: }
 5759: 
 5760: sub devalidate_getgroups_cache {
 5761:     my ($udom,$uname,$cdom,$cnum)=@_;
 5762:     my $courseid = $cdom.'_'.$cnum;
 5763: 
 5764:     my $hashid="$udom:$uname:$courseid";
 5765:     &devalidate_cache_new('getgroups',$hashid);
 5766: }
 5767: 
 5768: # ------------------------------------------------------------------ Plain Text
 5769: 
 5770: sub plaintext {
 5771:     my ($short,$type,$cid,$forcedefault) = @_;
 5772:     if ($short =~ /^cr/) {
 5773: 	return (split('/',$short))[-1];
 5774:     }
 5775:     if (!defined($cid)) {
 5776:         $cid = $env{'request.course.id'};
 5777:     }
 5778:     if (defined($cid) && ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '')) {
 5779:         unless ($forcedefault) {
 5780:             my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 5781:             &Apache::lonlocal::mt_escape(\$roletext);
 5782:             return &Apache::lonlocal::mt($roletext);
 5783:         }
 5784:     }
 5785:     my %rolenames = (
 5786:                       Course => 'std',
 5787:                       Group => 'alt1',
 5788:                     );
 5789:     if (defined($type) && 
 5790:          defined($rolenames{$type}) && 
 5791:          defined($prp{$short}{$rolenames{$type}})) {
 5792:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 5793:     } else {
 5794:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 5795:     }
 5796: }
 5797: 
 5798: # ----------------------------------------------------------------- Assign Role
 5799: 
 5800: sub assignrole {
 5801:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 5802:         $context)=@_;
 5803:     my $mrole;
 5804:     if ($role =~ /^cr\//) {
 5805:         my $cwosec=$url;
 5806:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5807: 	unless (&allowed('ccr',$cwosec)) {
 5808:            &logthis('Refused custom assignrole: '.
 5809:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5810: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 5811:            return 'refused'; 
 5812:         }
 5813:         $mrole='cr';
 5814:     } elsif ($role =~ /^gr\//) {
 5815:         my $cwogrp=$url;
 5816:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 5817:         unless (&allowed('mdg',$cwogrp)) {
 5818:             &logthis('Refused group assignrole: '.
 5819:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5820:                     $env{'user.name'}.' at '.$env{'user.domain'});
 5821:             return 'refused';
 5822:         }
 5823:         $mrole='gr';
 5824:     } else {
 5825:         my $cwosec=$url;
 5826:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5827:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 5828:             my $refused;
 5829:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 5830:                 if (!(&allowed('c'.$role,$url))) {
 5831:                     $refused = 1;
 5832:                 }
 5833:             } else {
 5834:                 $refused = 1;
 5835:             }
 5836:             if ($refused) {
 5837:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5838:                     $refused = '';
 5839:                 } else {
 5840:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 5841:                              ' '.$role.' '.$end.' '.$start.' by '.
 5842: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 5843:                     return 'refused';
 5844:                 }
 5845:             }
 5846:         }
 5847:         $mrole=$role;
 5848:     }
 5849:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5850:                 "$udom:$uname:$url".'_'."$mrole=$role";
 5851:     if ($end) { $command.='_'.$end; }
 5852:     if ($start) {
 5853: 	if ($end) { 
 5854:            $command.='_'.$start; 
 5855:         } else {
 5856:            $command.='_0_'.$start;
 5857:         }
 5858:     }
 5859:     my $origstart = $start;
 5860:     my $origend = $end;
 5861:     my $delflag;
 5862: # actually delete
 5863:     if ($deleteflag) {
 5864: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 5865: # modify command to delete the role
 5866:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 5867:                 "$udom:$uname:$url".'_'."$mrole";
 5868: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 5869: # set start and finish to negative values for userrolelog
 5870:            $start=-1;
 5871:            $end=-1;
 5872:            $delflag = 1;
 5873:         }
 5874:     }
 5875: # send command
 5876:     my $answer=&reply($command,&homeserver($uname,$udom));
 5877: # log new user role if status is ok
 5878:     if ($answer eq 'ok') {
 5879: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 5880: # for course roles, perform group memberships changes triggered by role change.
 5881:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 5882:         unless ($role =~ /^gr/) {
 5883:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 5884:                                              $origstart,$selfenroll,$context);
 5885:         }
 5886:     }
 5887:     return $answer;
 5888: }
 5889: 
 5890: # -------------------------------------------------- Modify user authentication
 5891: # Overrides without validation
 5892: 
 5893: sub modifyuserauth {
 5894:     my ($udom,$uname,$umode,$upass)=@_;
 5895:     my $uhome=&homeserver($uname,$udom);
 5896:     unless (&allowed('mau',$udom)) { return 'refused'; }
 5897:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 5898:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5899:              ' in domain '.$env{'request.role.domain'});  
 5900:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 5901: 		     &escape($upass),$uhome);
 5902:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 5903:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 5904:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5905:     &log($udom,,$uname,$uhome,
 5906:         'Authentication changed by '.$env{'user.domain'}.', '.
 5907:                                      $env{'user.name'}.', '.$umode.
 5908:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5909:     unless ($reply eq 'ok') {
 5910:         &logthis('Authentication mode error: '.$reply);
 5911: 	return 'error: '.$reply;
 5912:     }   
 5913:     return 'ok';
 5914: }
 5915: 
 5916: # --------------------------------------------------------------- Modify a user
 5917: 
 5918: sub modifyuser {
 5919:     my ($udom,    $uname, $uid,
 5920:         $umode,   $upass, $first,
 5921:         $middle,  $last,  $gene,
 5922:         $forceid, $desiredhome, $email, $inststatus)=@_;
 5923:     $udom= &LONCAPA::clean_domain($udom);
 5924:     $uname=&LONCAPA::clean_username($uname);
 5925:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 5926:              $umode.', '.$first.', '.$middle.', '.
 5927: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 5928:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 5929:                                      ' desiredhome not specified'). 
 5930:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5931:              ' in domain '.$env{'request.role.domain'});
 5932:     my $uhome=&homeserver($uname,$udom,'true');
 5933: # ----------------------------------------------------------------- Create User
 5934:     if (($uhome eq 'no_host') && 
 5935: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 5936:         my $unhome='';
 5937:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 5938:             $unhome = $desiredhome;
 5939: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 5940: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 5941:         } else { # load balancing routine for determining $unhome
 5942:             my $loadm=10000000;
 5943: 	    my %servers = &get_servers($udom,'library');
 5944: 	    foreach my $tryserver (keys(%servers)) {
 5945: 		my $answer=reply('load',$tryserver);
 5946: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 5947: 		    $loadm=$answer;
 5948: 		    $unhome=$tryserver;
 5949: 		}
 5950: 	    }
 5951:         }
 5952:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 5953: 	    return 'error: unable to find a home server for '.$uname.
 5954:                    ' in domain '.$udom;
 5955:         }
 5956:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 5957:                          &escape($upass),$unhome);
 5958: 	unless ($reply eq 'ok') {
 5959:             return 'error: '.$reply;
 5960:         }   
 5961:         $uhome=&homeserver($uname,$udom,'true');
 5962:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 5963: 	    return 'error: unable verify users home machine.';
 5964:         }
 5965:     }   # End of creation of new user
 5966: # ---------------------------------------------------------------------- Add ID
 5967:     if ($uid) {
 5968:        $uid=~tr/A-Z/a-z/;
 5969:        my %uidhash=&idrget($udom,$uname);
 5970:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 5971:          && (!$forceid)) {
 5972: 	  unless ($uid eq $uidhash{$uname}) {
 5973: 	      return 'error: user id "'.$uid.'" does not match '.
 5974:                   'current user id "'.$uidhash{$uname}.'".';
 5975:           }
 5976:        } else {
 5977: 	  &idput($udom,($uname => $uid));
 5978:        }
 5979:     }
 5980: # -------------------------------------------------------------- Add names, etc
 5981:     my @tmp=&get('environment',
 5982: 		   ['firstname','middlename','lastname','generation','id',
 5983:                     'permanentemail','inststatus'],
 5984: 		   $udom,$uname);
 5985:     my %names;
 5986:     if ($tmp[0] =~ m/^error:.*/) { 
 5987:         %names=(); 
 5988:     } else {
 5989:         %names = @tmp;
 5990:     }
 5991: #
 5992: # Make sure to not trash student environment if instructor does not bother
 5993: # to supply name and email information
 5994: #
 5995:     if ($first)  { $names{'firstname'}  = $first; }
 5996:     if (defined($middle)) { $names{'middlename'} = $middle; }
 5997:     if ($last)   { $names{'lastname'}   = $last; }
 5998:     if (defined($gene))   { $names{'generation'} = $gene; }
 5999:     if ($email) {
 6000:        $email=~s/[^\w\@\.\-\,]//gs;
 6001:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 6002:     }
 6003:     if ($uid) { $names{'id'}  = $uid; }
 6004:     if (defined($inststatus)) {
 6005:         $names{'inststatus'} = '';
 6006:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 6007:         if (ref($usertypes) eq 'HASH') {
 6008:             my @okstatuses; 
 6009:             foreach my $item (split(/:/,$inststatus)) {
 6010:                 if (defined($usertypes->{$item})) {
 6011:                     push(@okstatuses,$item);  
 6012:                 }
 6013:             }
 6014:             if (@okstatuses) {
 6015:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 6016:             }
 6017:         }
 6018:     }
 6019:     my $reply = &put('environment', \%names, $udom,$uname);
 6020:     if ($reply ne 'ok') { return 'error: '.$reply; }
 6021:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 6022:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 6023:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 6024:                  $umode.', '.$first.', '.$middle.', '.
 6025: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
 6026:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 6027:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 6028:     } else {
 6029:         $logmsg .= ' during self creation';
 6030:     }
 6031:     &logthis($logmsg);
 6032:     return 'ok';
 6033: }
 6034: 
 6035: # -------------------------------------------------------------- Modify student
 6036: 
 6037: sub modifystudent {
 6038:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 6039:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 6040:         $selfenroll,$context,$inststatus)=@_;
 6041:     if (!$cid) {
 6042: 	unless ($cid=$env{'request.course.id'}) {
 6043: 	    return 'not_in_class';
 6044: 	}
 6045:     }
 6046: # --------------------------------------------------------------- Make the user
 6047:     my $reply=&modifyuser
 6048: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 6049:          $desiredhome,$email,$inststatus);
 6050:     unless ($reply eq 'ok') { return $reply; }
 6051:     # This will cause &modify_student_enrollment to get the uid from the
 6052:     # students environment
 6053:     $uid = undef if (!$forceid);
 6054:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 6055: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 6056:     return $reply;
 6057: }
 6058: 
 6059: sub modify_student_enrollment {
 6060:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 6061:     my ($cdom,$cnum,$chome);
 6062:     if (!$cid) {
 6063: 	unless ($cid=$env{'request.course.id'}) {
 6064: 	    return 'not_in_class';
 6065: 	}
 6066: 	$cdom=$env{'course.'.$cid.'.domain'};
 6067: 	$cnum=$env{'course.'.$cid.'.num'};
 6068:     } else {
 6069: 	($cdom,$cnum)=split(/_/,$cid);
 6070:     }
 6071:     $chome=$env{'course.'.$cid.'.home'};
 6072:     if (!$chome) {
 6073: 	$chome=&homeserver($cnum,$cdom);
 6074:     }
 6075:     if (!$chome) { return 'unknown_course'; }
 6076:     # Make sure the user exists
 6077:     my $uhome=&homeserver($uname,$udom);
 6078:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6079: 	return 'error: no such user';
 6080:     }
 6081:     # Get student data if we were not given enough information
 6082:     if (!defined($first)  || $first  eq '' || 
 6083:         !defined($last)   || $last   eq '' || 
 6084:         !defined($uid)    || $uid    eq '' || 
 6085:         !defined($middle) || $middle eq '' || 
 6086:         !defined($gene)   || $gene   eq '') {
 6087:         # They did not supply us with enough data to enroll the student, so
 6088:         # we need to pick up more information.
 6089:         my %tmp = &get('environment',
 6090:                        ['firstname','middlename','lastname', 'generation','id']
 6091:                        ,$udom,$uname);
 6092: 
 6093:         #foreach my $key (keys(%tmp)) {
 6094:         #    &logthis("key $key = ".$tmp{$key});
 6095:         #}
 6096:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 6097:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 6098:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 6099:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 6100:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 6101:     }
 6102:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 6103:     my $reply=cput('classlist',
 6104: 		   {"$uname:$udom" => 
 6105: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 6106: 		   $cdom,$cnum);
 6107:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 6108: 	return 'error: '.$reply;
 6109:     } else {
 6110: 	&devalidate_getsection_cache($udom,$uname,$cid);
 6111:     }
 6112:     # Add student role to user
 6113:     my $uurl='/'.$cid;
 6114:     $uurl=~s/\_/\//g;
 6115:     if ($usec) {
 6116: 	$uurl.='/'.$usec;
 6117:     }
 6118:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 6119: }
 6120: 
 6121: sub format_name {
 6122:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 6123:     my $name;
 6124:     if ($first ne 'lastname') {
 6125: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 6126:     } else {
 6127: 	if ($lastname=~/\S/) {
 6128: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 6129: 	    $name=~s/\s+,/,/;
 6130: 	} else {
 6131: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 6132: 	}
 6133:     }
 6134:     $name=~s/^\s+//;
 6135:     $name=~s/\s+$//;
 6136:     $name=~s/\s+/ /g;
 6137:     return $name;
 6138: }
 6139: 
 6140: # ------------------------------------------------- Write to course preferences
 6141: 
 6142: sub writecoursepref {
 6143:     my ($courseid,%prefs)=@_;
 6144:     $courseid=~s/^\///;
 6145:     $courseid=~s/\_/\//g;
 6146:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6147:     my $chome=homeserver($cnum,$cdomain);
 6148:     if (($chome eq '') || ($chome eq 'no_host')) { 
 6149: 	return 'error: no such course';
 6150:     }
 6151:     my $cstring='';
 6152:     foreach my $pref (keys(%prefs)) {
 6153: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 6154:     }
 6155:     $cstring=~s/\&$//;
 6156:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 6157: }
 6158: 
 6159: # ---------------------------------------------------------- Make/modify course
 6160: 
 6161: sub createcourse {
 6162:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 6163:         $course_owner,$crstype)=@_;
 6164:     $url=&declutter($url);
 6165:     my $cid='';
 6166:     unless (&allowed('ccc',$udom)) {
 6167:         return 'refused';
 6168:     }
 6169: # ------------------------------------------------------------------- Create ID
 6170:    my $uname=int(1+rand(9)).
 6171:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6172:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6173:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6174: # ----------------------------------------------- Make sure that does not exist
 6175:    my $uhome=&homeserver($uname,$udom,'true');
 6176:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6177:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6178:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6179:        $uhome=&homeserver($uname,$udom,'true');       
 6180:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6181:            return 'error: unable to generate unique course-ID';
 6182:        } 
 6183:    }
 6184: # ------------------------------------------------ Check supplied server name
 6185:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 6186:     if (! &is_library($course_server)) {
 6187:         return 'error:bad server name '.$course_server;
 6188:     }
 6189: # ------------------------------------------------------------- Make the course
 6190:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 6191:                       $course_server);
 6192:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 6193:     $uhome=&homeserver($uname,$udom,'true');
 6194:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6195: 	return 'error: no such course';
 6196:     }
 6197: # ----------------------------------------------------------------- Course made
 6198: # log existence
 6199:     my $newcourse = {
 6200:                     $udom.'_'.$uname => {
 6201:                                      description => $description,
 6202:                                      inst_code   => $inst_code,
 6203:                                      owner       => $course_owner,
 6204:                                      type        => $crstype,
 6205:                                                 },
 6206:                     };
 6207:     &courseidput($udom,$newcourse,$uhome,'notime');
 6208: # set toplevel url
 6209:     my $topurl=$url;
 6210:     unless ($nonstandard) {
 6211: # ------------------------------------------ For standard courses, make top url
 6212:         my $mapurl=&clutter($url);
 6213:         if ($mapurl eq '/res/') { $mapurl=''; }
 6214:         $env{'form.initmap'}=(<<ENDINITMAP);
 6215: <map>
 6216: <resource id="1" type="start"></resource>
 6217: <resource id="2" src="$mapurl"></resource>
 6218: <resource id="3" type="finish"></resource>
 6219: <link index="1" from="1" to="2"></link>
 6220: <link index="2" from="2" to="3"></link>
 6221: </map>
 6222: ENDINITMAP
 6223:         $topurl=&declutter(
 6224:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 6225:                           );
 6226:     }
 6227: # ----------------------------------------------------------- Write preferences
 6228:     &writecoursepref($udom.'_'.$uname,
 6229:                      ('description' => $description,
 6230:                       'url'         => $topurl));
 6231:     return '/'.$udom.'/'.$uname;
 6232: }
 6233: 
 6234: sub is_course {
 6235:     my ($cdom,$cnum) = @_;
 6236:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 6237: 				undef,'.');
 6238:     if (exists($courses{$cdom.'_'.$cnum})) {
 6239:         return 1;
 6240:     }
 6241:     return 0;
 6242: }
 6243: 
 6244: # ---------------------------------------------------------- Assign Custom Role
 6245: 
 6246: sub assigncustomrole {
 6247:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 6248:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 6249:                        $end,$start,$deleteflag,$selfenroll,$context);
 6250: }
 6251: 
 6252: # ----------------------------------------------------------------- Revoke Role
 6253: 
 6254: sub revokerole {
 6255:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 6256:     my $now=time;
 6257:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 6258: }
 6259: 
 6260: # ---------------------------------------------------------- Revoke Custom Role
 6261: 
 6262: sub revokecustomrole {
 6263:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 6264:     my $now=time;
 6265:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 6266:            $deleteflag,$selfenroll,$context);
 6267: }
 6268: 
 6269: # ------------------------------------------------------------ Disk usage
 6270: sub diskusage {
 6271:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 6272:     $directorypath =~ s/\/$//;
 6273:     my $listing=&reply('du2:'.&escape($directorypath).':'
 6274:                        .&escape($getpropath).':'.&escape($uname).':'
 6275:                        .&escape($udom),homeserver($uname,$udom));
 6276:     if ($listing eq 'unknown_cmd') {
 6277:         if ($getpropath) {
 6278:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 6279:         }
 6280:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 6281:     }
 6282:     return $listing;
 6283: }
 6284: 
 6285: sub is_locked {
 6286:     my ($file_name, $domain, $user) = @_;
 6287:     my @check;
 6288:     my $is_locked;
 6289:     push @check, $file_name;
 6290:     my %locked = &get('file_permissions',\@check,
 6291: 		      $env{'user.domain'},$env{'user.name'});
 6292:     my ($tmp)=keys(%locked);
 6293:     if ($tmp=~/^error:/) { undef(%locked); }
 6294:     
 6295:     if (ref($locked{$file_name}) eq 'ARRAY') {
 6296:         $is_locked = 'false';
 6297:         foreach my $entry (@{$locked{$file_name}}) {
 6298:            if (ref($entry) eq 'ARRAY') { 
 6299:                $is_locked = 'true';
 6300:                last;
 6301:            }
 6302:        }
 6303:     } else {
 6304:         $is_locked = 'false';
 6305:     }
 6306: }
 6307: 
 6308: sub declutter_portfile {
 6309:     my ($file) = @_;
 6310:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 6311:     return $file;
 6312: }
 6313: 
 6314: # ------------------------------------------------------------- Mark as Read Only
 6315: 
 6316: sub mark_as_readonly {
 6317:     my ($domain,$user,$files,$what) = @_;
 6318:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6319:     my ($tmp)=keys(%current_permissions);
 6320:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6321:     foreach my $file (@{$files}) {
 6322: 	$file = &declutter_portfile($file);
 6323:         push(@{$current_permissions{$file}},$what);
 6324:     }
 6325:     &put('file_permissions',\%current_permissions,$domain,$user);
 6326:     return;
 6327: }
 6328: 
 6329: # ------------------------------------------------------------Save Selected Files
 6330: 
 6331: sub save_selected_files {
 6332:     my ($user, $path, @files) = @_;
 6333:     my $filename = $user."savedfiles";
 6334:     my @other_files = &files_not_in_path($user, $path);
 6335:     open (OUT, '>'.$tmpdir.$filename);
 6336:     foreach my $file (@files) {
 6337:         print (OUT $env{'form.currentpath'}.$file."\n");
 6338:     }
 6339:     foreach my $file (@other_files) {
 6340:         print (OUT $file."\n");
 6341:     }
 6342:     close (OUT);
 6343:     return 'ok';
 6344: }
 6345: 
 6346: sub clear_selected_files {
 6347:     my ($user) = @_;
 6348:     my $filename = $user."savedfiles";
 6349:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6350:     print (OUT undef);
 6351:     close (OUT);
 6352:     return ("ok");    
 6353: }
 6354: 
 6355: sub files_in_path {
 6356:     my ($user, $path) = @_;
 6357:     my $filename = $user."savedfiles";
 6358:     my %return_files;
 6359:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6360:     while (my $line_in = <IN>) {
 6361:         chomp ($line_in);
 6362:         my @paths_and_file = split (m!/!, $line_in);
 6363:         my $file_part = pop (@paths_and_file);
 6364:         my $path_part = join ('/', @paths_and_file);
 6365:         $path_part.='/';
 6366:         my $path_and_file = $path_part.$file_part;
 6367:         if ($path_part eq $path) {
 6368:             $return_files{$file_part}= 'selected';
 6369:         }
 6370:     }
 6371:     close (IN);
 6372:     return (\%return_files);
 6373: }
 6374: 
 6375: # called in portfolio select mode, to show files selected NOT in current directory
 6376: sub files_not_in_path {
 6377:     my ($user, $path) = @_;
 6378:     my $filename = $user."savedfiles";
 6379:     my @return_files;
 6380:     my $path_part;
 6381:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6382:     while (my $line = <IN>) {
 6383:         #ok, I know it's clunky, but I want it to work
 6384:         my @paths_and_file = split(m|/|, $line);
 6385:         my $file_part = pop(@paths_and_file);
 6386:         chomp($file_part);
 6387:         my $path_part = join('/', @paths_and_file);
 6388:         $path_part .= '/';
 6389:         my $path_and_file = $path_part.$file_part;
 6390:         if ($path_part ne $path) {
 6391:             push(@return_files, ($path_and_file));
 6392:         }
 6393:     }
 6394:     close(OUT);
 6395:     return (@return_files);
 6396: }
 6397: 
 6398: #----------------------------------------------Get portfolio file permissions
 6399: 
 6400: sub get_portfile_permissions {
 6401:     my ($domain,$user) = @_;
 6402:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6403:     my ($tmp)=keys(%current_permissions);
 6404:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6405:     return \%current_permissions;
 6406: }
 6407: 
 6408: #---------------------------------------------Get portfolio file access controls
 6409: 
 6410: sub get_access_controls {
 6411:     my ($current_permissions,$group,$file) = @_;
 6412:     my %access;
 6413:     my $real_file = $file;
 6414:     $file =~ s/\.meta$//;
 6415:     if (defined($file)) {
 6416:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 6417:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 6418:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 6419:             }
 6420:         }
 6421:     } else {
 6422:         foreach my $key (keys(%{$current_permissions})) {
 6423:             if ($key =~ /\0accesscontrol$/) {
 6424:                 if (defined($group)) {
 6425:                     if ($key !~ m-^\Q$group\E/-) {
 6426:                         next;
 6427:                     }
 6428:                 }
 6429:                 my ($fullpath) = split(/\0/,$key);
 6430:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 6431:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 6432:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 6433:                     }
 6434:                 }
 6435:             }
 6436:         }
 6437:     }
 6438:     return %access;
 6439: }
 6440: 
 6441: sub modify_access_controls {
 6442:     my ($file_name,$changes,$domain,$user)=@_;
 6443:     my ($outcome,$deloutcome);
 6444:     my %store_permissions;
 6445:     my %new_values;
 6446:     my %new_control;
 6447:     my %translation;
 6448:     my @deletions = ();
 6449:     my $now = time;
 6450:     if (exists($$changes{'activate'})) {
 6451:         if (ref($$changes{'activate'}) eq 'HASH') {
 6452:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 6453:             my $numnew = scalar(@newitems);
 6454:             for (my $i=0; $i<$numnew; $i++) {
 6455:                 my $newkey = $newitems[$i];
 6456:                 my $newid = &Apache::loncommon::get_cgi_id();
 6457:                 if ($newkey =~ /^\d+:/) { 
 6458:                     $newkey =~ s/^(\d+)/$newid/;
 6459:                     $translation{$1} = $newid;
 6460:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 6461:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 6462:                     $translation{$1} = $newid;
 6463:                 }
 6464:                 $new_values{$file_name."\0".$newkey} = 
 6465:                                           $$changes{'activate'}{$newitems[$i]};
 6466:                 $new_control{$newkey} = $now;
 6467:             }
 6468:         }
 6469:     }
 6470:     my %todelete;
 6471:     my %changed_items;
 6472:     foreach my $action ('delete','update') {
 6473:         if (exists($$changes{$action})) {
 6474:             if (ref($$changes{$action}) eq 'HASH') {
 6475:                 foreach my $key (keys(%{$$changes{$action}})) {
 6476:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 6477:                     if ($action eq 'delete') { 
 6478:                         $todelete{$itemnum} = 1;
 6479:                     } else {
 6480:                         $changed_items{$itemnum} = $key;
 6481:                     }
 6482:                 }
 6483:             }
 6484:         }
 6485:     }
 6486:     # get lock on access controls for file.
 6487:     my $lockhash = {
 6488:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 6489:                                                        ':'.$env{'user.domain'},
 6490:                    }; 
 6491:     my $tries = 0;
 6492:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6493:    
 6494:     while (($gotlock ne 'ok') && $tries <3) {
 6495:         $tries ++;
 6496:         sleep 1;
 6497:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6498:     }
 6499:     if ($gotlock eq 'ok') {
 6500:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 6501:         my ($tmp)=keys(%curr_permissions);
 6502:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 6503:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 6504:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 6505:             if (ref($curr_controls) eq 'HASH') {
 6506:                 foreach my $control_item (keys(%{$curr_controls})) {
 6507:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 6508:                     if (defined($todelete{$itemnum})) {
 6509:                         push(@deletions,$file_name."\0".$control_item);
 6510:                     } else {
 6511:                         if (defined($changed_items{$itemnum})) {
 6512:                             $new_control{$changed_items{$itemnum}} = $now;
 6513:                             push(@deletions,$file_name."\0".$control_item);
 6514:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 6515:                         } else {
 6516:                             $new_control{$control_item} = $$curr_controls{$control_item};
 6517:                         }
 6518:                     }
 6519:                 }
 6520:             }
 6521:         }
 6522:         my ($group);
 6523:         if (&is_course($domain,$user)) {
 6524:             ($group,my $file) = split(/\//,$file_name,2);
 6525:         }
 6526:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 6527:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 6528:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 6529:         #  remove lock
 6530:         my @del_lock = ($file_name."\0".'locked_access_records');
 6531:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 6532:         my $sqlresult =
 6533:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 6534:                                     $group);
 6535:     } else {
 6536:         $outcome = "error: could not obtain lockfile\n";  
 6537:     }
 6538:     return ($outcome,$deloutcome,\%new_values,\%translation);
 6539: }
 6540: 
 6541: sub make_public_indefinitely {
 6542:     my ($requrl) = @_;
 6543:     my $now = time;
 6544:     my $action = 'activate';
 6545:     my $aclnum = 0;
 6546:     if (&is_portfolio_url($requrl)) {
 6547:         my (undef,$udom,$unum,$file_name,$group) =
 6548:             &parse_portfolio_url($requrl);
 6549:         my $current_perms = &get_portfile_permissions($udom,$unum);
 6550:         my %access_controls = &get_access_controls($current_perms,
 6551:                                                    $group,$file_name);
 6552:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 6553:             my ($num,$scope,$end,$start) = 
 6554:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6555:             if ($scope eq 'public') {
 6556:                 if ($start <= $now && $end == 0) {
 6557:                     $action = 'none';
 6558:                 } else {
 6559:                     $action = 'update';
 6560:                     $aclnum = $num;
 6561:                 }
 6562:                 last;
 6563:             }
 6564:         }
 6565:         if ($action eq 'none') {
 6566:              return 'ok';
 6567:         } else {
 6568:             my %changes;
 6569:             my $newend = 0;
 6570:             my $newstart = $now;
 6571:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 6572:             $changes{$action}{$newkey} = {
 6573:                 type => 'public',
 6574:                 time => {
 6575:                     start => $newstart,
 6576:                     end   => $newend,
 6577:                 },
 6578:             };
 6579:             my ($outcome,$deloutcome,$new_values,$translation) =
 6580:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 6581:             return $outcome;
 6582:         }
 6583:     } else {
 6584:         return 'invalid';
 6585:     }
 6586: }
 6587: 
 6588: #------------------------------------------------------Get Marked as Read Only
 6589: 
 6590: sub get_marked_as_readonly {
 6591:     my ($domain,$user,$what,$group) = @_;
 6592:     my $current_permissions = &get_portfile_permissions($domain,$user);
 6593:     my @readonly_files;
 6594:     my $cmp1=$what;
 6595:     if (ref($what)) { $cmp1=join('',@{$what}) };
 6596:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6597:         if (defined($group)) {
 6598:             if ($file_name !~ m-^\Q$group\E/-) {
 6599:                 next;
 6600:             }
 6601:         }
 6602:         if (ref($value) eq "ARRAY"){
 6603:             foreach my $stored_what (@{$value}) {
 6604:                 my $cmp2=$stored_what;
 6605:                 if (ref($stored_what) eq 'ARRAY') {
 6606:                     $cmp2=join('',@{$stored_what});
 6607:                 }
 6608:                 if ($cmp1 eq $cmp2) {
 6609:                     push(@readonly_files, $file_name);
 6610:                     last;
 6611:                 } elsif (!defined($what)) {
 6612:                     push(@readonly_files, $file_name);
 6613:                     last;
 6614:                 }
 6615:             }
 6616:         }
 6617:     }
 6618:     return @readonly_files;
 6619: }
 6620: #-----------------------------------------------------------Get Marked as Read Only Hash
 6621: 
 6622: sub get_marked_as_readonly_hash {
 6623:     my ($current_permissions,$group,$what) = @_;
 6624:     my %readonly_files;
 6625:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6626:         if (defined($group)) {
 6627:             if ($file_name !~ m-^\Q$group\E/-) {
 6628:                 next;
 6629:             }
 6630:         }
 6631:         if (ref($value) eq "ARRAY"){
 6632:             foreach my $stored_what (@{$value}) {
 6633:                 if (ref($stored_what) eq 'ARRAY') {
 6634:                     foreach my $lock_descriptor(@{$stored_what}) {
 6635:                         if ($lock_descriptor eq 'graded') {
 6636:                             $readonly_files{$file_name} = 'graded';
 6637:                         } elsif ($lock_descriptor eq 'handback') {
 6638:                             $readonly_files{$file_name} = 'handback';
 6639:                         } else {
 6640:                             if (!exists($readonly_files{$file_name})) {
 6641:                                 $readonly_files{$file_name} = 'locked';
 6642:                             }
 6643:                         }
 6644:                     }
 6645:                 } 
 6646:             }
 6647:         } 
 6648:     }
 6649:     return %readonly_files;
 6650: }
 6651: # ------------------------------------------------------------ Unmark as Read Only
 6652: 
 6653: sub unmark_as_readonly {
 6654:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 6655:     # for portfolio submissions, $what contains [$symb,$crsid] 
 6656:     my ($domain,$user,$what,$file_name,$group) = @_;
 6657:     $file_name = &declutter_portfile($file_name);
 6658:     my $symb_crs = $what;
 6659:     if (ref($what)) { $symb_crs=join('',@$what); }
 6660:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 6661:     my ($tmp)=keys(%current_permissions);
 6662:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6663:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 6664:     foreach my $file (@readonly_files) {
 6665: 	my $clean_file = &declutter_portfile($file);
 6666: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 6667: 	my $current_locks = $current_permissions{$file};
 6668:         my @new_locks;
 6669:         my @del_keys;
 6670:         if (ref($current_locks) eq "ARRAY"){
 6671:             foreach my $locker (@{$current_locks}) {
 6672:                 my $compare=$locker;
 6673:                 if (ref($locker) eq 'ARRAY') {
 6674:                     $compare=join('',@{$locker});
 6675:                     if ($compare ne $symb_crs) {
 6676:                         push(@new_locks, $locker);
 6677:                     }
 6678:                 }
 6679:             }
 6680:             if (scalar(@new_locks) > 0) {
 6681:                 $current_permissions{$file} = \@new_locks;
 6682:             } else {
 6683:                 push(@del_keys, $file);
 6684:                 &del('file_permissions',\@del_keys, $domain, $user);
 6685:                 delete($current_permissions{$file});
 6686:             }
 6687:         }
 6688:     }
 6689:     &put('file_permissions',\%current_permissions,$domain,$user);
 6690:     return;
 6691: }
 6692: 
 6693: # ------------------------------------------------------------ Directory lister
 6694: 
 6695: sub dirlist {
 6696:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 6697:     $uri=~s/^\///;
 6698:     $uri=~s/\/$//;
 6699:     my ($udom, $uname);
 6700:     if ($getuserdir) {
 6701:         $udom = $userdomain;
 6702:         $uname = $username;
 6703:     } else {
 6704:         (undef,$udom,$uname)=split(/\//,$uri);
 6705:         if(defined($userdomain)) {
 6706:             $udom = $userdomain;
 6707:         }
 6708:         if(defined($username)) {
 6709:             $uname = $username;
 6710:         }
 6711:     }
 6712:     my ($dirRoot,$listing,@listing_results);
 6713: 
 6714:     $dirRoot = $perlvar{'lonDocRoot'};
 6715:     if (defined($getpropath)) {
 6716:         $dirRoot = &propath($udom,$uname);
 6717:         $dirRoot =~ s/\/$//;
 6718:     } elsif (defined($getuserdir)) {
 6719:         my $subdir=$uname.'__';
 6720:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 6721:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 6722:                    ."/$udom/$subdir/$uname";
 6723:     } elsif (defined($alternateRoot)) {
 6724:         $dirRoot = $alternateRoot;
 6725:     }
 6726: 
 6727:     if($udom) {
 6728:         if($uname) {
 6729:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 6730:                               .$getuserdir.':'.&escape($dirRoot)
 6731:                               .':'.&escape($uname).':'.&escape($udom),
 6732:                               &homeserver($uname,$udom));
 6733:             if ($listing eq 'unknown_cmd') {
 6734:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 6735:                                   &homeserver($uname,$udom));
 6736:             } else {
 6737:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6738:             }
 6739:             if ($listing eq 'unknown_cmd') {
 6740:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 6741: 				  &homeserver($uname,$udom));
 6742:                 @listing_results = split(/:/,$listing);
 6743:             } else {
 6744:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6745:             }
 6746:             return @listing_results;
 6747:         } elsif(!$alternateRoot) {
 6748:             my %allusers;
 6749: 	    my %servers = &get_servers($udom,'library');
 6750:  	    foreach my $tryserver (keys(%servers)) {
 6751:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 6752:                                   &escape($udom),$tryserver);
 6753:                 if ($listing eq 'unknown_cmd') {
 6754: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 6755: 				      $udom, $tryserver);
 6756:                 } else {
 6757:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 6758:                 }
 6759: 		if ($listing eq 'unknown_cmd') {
 6760: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 6761: 				      $udom, $tryserver);
 6762: 		    @listing_results = split(/:/,$listing);
 6763: 		} else {
 6764: 		    @listing_results =
 6765: 			map { &unescape($_); } split(/:/,$listing);
 6766: 		}
 6767: 		if ($listing_results[0] ne 'no_such_dir' && 
 6768: 		    $listing_results[0] ne 'empty'       &&
 6769: 		    $listing_results[0] ne 'con_lost') {
 6770: 		    foreach my $line (@listing_results) {
 6771: 			my ($entry) = split(/&/,$line,2);
 6772: 			$allusers{$entry} = 1;
 6773: 		    }
 6774: 		}
 6775:             }
 6776:             my $alluserstr='';
 6777:             foreach my $user (sort(keys(%allusers))) {
 6778:                 $alluserstr.=$user.'&user:';
 6779:             }
 6780:             $alluserstr=~s/:$//;
 6781:             return split(/:/,$alluserstr);
 6782:         } else {
 6783:             return ('missing user name');
 6784:         }
 6785:     } elsif(!defined($getpropath)) {
 6786:         my @all_domains = sort(&all_domains());
 6787:         foreach my $domain (@all_domains) {
 6788:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 6789:         }
 6790:         return @all_domains;
 6791:     } else {
 6792:         return ('missing domain');
 6793:     }
 6794: }
 6795: 
 6796: # --------------------------------------------- GetFileTimestamp
 6797: # This function utilizes dirlist and returns the date stamp for
 6798: # when it was last modified.  It will also return an error of -1
 6799: # if an error occurs
 6800: 
 6801: sub GetFileTimestamp {
 6802:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 6803:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 6804:     $studentName   = &LONCAPA::clean_username($studentName);
 6805:     my ($fileStat) = 
 6806:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
 6807:                                  undef,$getuserdir);
 6808:     my @stats = split('&', $fileStat);
 6809:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6810:         # @stats contains first the filename, then the stat output
 6811:         return $stats[10]; # so this is 10 instead of 9.
 6812:     } else {
 6813:         return -1;
 6814:     }
 6815: }
 6816: 
 6817: sub stat_file {
 6818:     my ($uri) = @_;
 6819:     $uri = &clutter_with_no_wrapper($uri);
 6820: 
 6821:     my ($udom,$uname,$file);
 6822:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 6823: 	($udom,$uname,$file) =
 6824: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 6825: 	$file = 'userfiles/'.$file;
 6826:     }
 6827:     if ($uri =~ m-^/res/-) {
 6828: 	($udom,$uname) = 
 6829: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 6830: 	$file = $uri;
 6831:     }
 6832: 
 6833:     if (!$udom || !$uname || !$file) {
 6834: 	# unable to handle the uri
 6835: 	return ();
 6836:     }
 6837:     my $getpropath;
 6838:     if ($file =~ /^userfiles\//) {
 6839:         $getpropath = 1;
 6840:     }
 6841:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
 6842:     my @stats = split('&', $result);
 6843:     
 6844:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6845: 	shift(@stats); #filename is first
 6846: 	return @stats;
 6847:     }
 6848:     return ();
 6849: }
 6850: 
 6851: # -------------------------------------------------------- Value of a Condition
 6852: 
 6853: # gets the value of a specific preevaluated condition
 6854: #    stored in the string  $env{user.state.<cid>}
 6855: # or looks up a condition reference in the bighash and if if hasn't
 6856: # already been evaluated recurses into docondval to get the value of
 6857: # the condition, then memoizing it to 
 6858: #   $env{user.state.<cid>.<condition>}
 6859: sub directcondval {
 6860:     my $number=shift;
 6861:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 6862: 	&Apache::lonuserstate::evalstate();
 6863:     }
 6864:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 6865: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 6866:     } elsif ($number =~ /^_/) {
 6867: 	my $sub_condition;
 6868: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6869: 		&GDBM_READER(),0640)) {
 6870: 	    $sub_condition=$bighash{'conditions'.$number};
 6871: 	    untie(%bighash);
 6872: 	}
 6873: 	my $value = &docondval($sub_condition);
 6874: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 6875: 	return $value;
 6876:     }
 6877:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 6878:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 6879:     } else {
 6880:        return 2;
 6881:     }
 6882: }
 6883: 
 6884: # get the collection of conditions for this resource
 6885: sub condval {
 6886:     my $condidx=shift;
 6887:     my $allpathcond='';
 6888:     foreach my $cond (split(/\|/,$condidx)) {
 6889: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 6890: 	    $allpathcond.=
 6891: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 6892: 	}
 6893:     }
 6894:     $allpathcond=~s/\|$//;
 6895:     return &docondval($allpathcond);
 6896: }
 6897: 
 6898: #evaluates an expression of conditions
 6899: sub docondval {
 6900:     my ($allpathcond) = @_;
 6901:     my $result=0;
 6902:     if ($env{'request.course.id'}
 6903: 	&& defined($allpathcond)) {
 6904: 	my $operand='|';
 6905: 	my @stack;
 6906: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 6907: 	    if ($chunk eq '(') {
 6908: 		push @stack,($operand,$result);
 6909: 	    } elsif ($chunk eq ')') {
 6910: 		my $before=pop @stack;
 6911: 		if (pop @stack eq '&') {
 6912: 		    $result=$result>$before?$before:$result;
 6913: 		} else {
 6914: 		    $result=$result>$before?$result:$before;
 6915: 		}
 6916: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 6917: 		$operand=$chunk;
 6918: 	    } else {
 6919: 		my $new=directcondval($chunk);
 6920: 		if ($operand eq '&') {
 6921: 		    $result=$result>$new?$new:$result;
 6922: 		} else {
 6923: 		    $result=$result>$new?$result:$new;
 6924: 		}
 6925: 	    }
 6926: 	}
 6927:     }
 6928:     return $result;
 6929: }
 6930: 
 6931: # ---------------------------------------------------- Devalidate courseresdata
 6932: 
 6933: sub devalidatecourseresdata {
 6934:     my ($coursenum,$coursedomain)=@_;
 6935:     my $hashid=$coursenum.':'.$coursedomain;
 6936:     &devalidate_cache_new('courseres',$hashid);
 6937: }
 6938: 
 6939: 
 6940: # --------------------------------------------------- Course Resourcedata Query
 6941: #
 6942: #  Parameters:
 6943: #      $coursenum    - Number of the course.
 6944: #      $coursedomain - Domain at which the course was created.
 6945: #  Returns:
 6946: #     A hash of the course parameters along (I think) with timestamps
 6947: #     and version info.
 6948: 
 6949: sub get_courseresdata {
 6950:     my ($coursenum,$coursedomain)=@_;
 6951:     my $coursehom=&homeserver($coursenum,$coursedomain);
 6952:     my $hashid=$coursenum.':'.$coursedomain;
 6953:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 6954:     my %dumpreply;
 6955:     unless (defined($cached)) {
 6956: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 6957: 	$result=\%dumpreply;
 6958: 	my ($tmp) = keys(%dumpreply);
 6959: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6960: 	    &do_cache_new('courseres',$hashid,$result,600);
 6961: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 6962: 	    return $tmp;
 6963: 	} elsif ($tmp =~ /^(error)/) {
 6964: 	    $result=undef;
 6965: 	    &do_cache_new('courseres',$hashid,$result,600);
 6966: 	}
 6967:     }
 6968:     return $result;
 6969: }
 6970: 
 6971: sub devalidateuserresdata {
 6972:     my ($uname,$udom)=@_;
 6973:     my $hashid="$udom:$uname";
 6974:     &devalidate_cache_new('userres',$hashid);
 6975: }
 6976: 
 6977: sub get_userresdata {
 6978:     my ($uname,$udom)=@_;
 6979:     #most student don\'t have any data set, check if there is some data
 6980:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 6981: 
 6982:     my $hashid="$udom:$uname";
 6983:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 6984:     if (!defined($cached)) {
 6985: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 6986: 	$result=\%resourcedata;
 6987: 	&do_cache_new('userres',$hashid,$result,600);
 6988:     }
 6989:     my ($tmp)=keys(%$result);
 6990:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 6991: 	return $result;
 6992:     }
 6993:     #error 2 occurs when the .db doesn't exist
 6994:     if ($tmp!~/error: 2 /) {
 6995: 	&logthis("<font color=\"blue\">WARNING:".
 6996: 		 " Trying to get resource data for ".
 6997: 		 $uname." at ".$udom.": ".
 6998: 		 $tmp."</font>");
 6999:     } elsif ($tmp=~/error: 2 /) {
 7000: 	#&EXT_cache_set($udom,$uname);
 7001: 	&do_cache_new('userres',$hashid,undef,600);
 7002: 	undef($tmp); # not really an error so don't send it back
 7003:     }
 7004:     return $tmp;
 7005: }
 7006: #----------------------------------------------- resdata - return resource data
 7007: #  Purpose:
 7008: #    Return resource data for either users or for a course.
 7009: #  Parameters:
 7010: #     $name      - Course/user name.
 7011: #     $domain    - Name of the domain the user/course is registered on.
 7012: #     $type      - Type of thing $name is (must be 'course' or 'user'
 7013: #     @which     - Array of names of resources desired.
 7014: #  Returns:
 7015: #     The value of the first reasource in @which that is found in the
 7016: #     resource hash.
 7017: #  Exceptional Conditions:
 7018: #     If the $type passed in is not valid (not the string 'course' or 
 7019: #     'user', an undefined  reference is returned.
 7020: #     If none of the resources are found, an undef is returned
 7021: sub resdata {
 7022:     my ($name,$domain,$type,@which)=@_;
 7023:     my $result;
 7024:     if ($type eq 'course') {
 7025: 	$result=&get_courseresdata($name,$domain);
 7026:     } elsif ($type eq 'user') {
 7027: 	$result=&get_userresdata($name,$domain);
 7028:     }
 7029:     if (!ref($result)) { return $result; }    
 7030:     foreach my $item (@which) {
 7031: 	if (defined($result->{$item->[0]})) {
 7032: 	    return [$result->{$item->[0]},$item->[1]];
 7033: 	}
 7034:     }
 7035:     return undef;
 7036: }
 7037: 
 7038: #
 7039: # EXT resource caching routines
 7040: #
 7041: 
 7042: sub clear_EXT_cache_status {
 7043:     &delenv('cache.EXT.');
 7044: }
 7045: 
 7046: sub EXT_cache_status {
 7047:     my ($target_domain,$target_user) = @_;
 7048:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7049:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 7050:         # We know already the user has no data
 7051:         return 1;
 7052:     } else {
 7053:         return 0;
 7054:     }
 7055: }
 7056: 
 7057: sub EXT_cache_set {
 7058:     my ($target_domain,$target_user) = @_;
 7059:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7060:     #&appenv({$cachename => time});
 7061: }
 7062: 
 7063: # --------------------------------------------------------- Value of a Variable
 7064: sub EXT {
 7065: 
 7066:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 7067:     unless ($varname) { return ''; }
 7068:     #get real user name/domain, courseid and symb
 7069:     my $courseid;
 7070:     my $publicuser;
 7071:     if ($symbparm) {
 7072: 	$symbparm=&get_symb_from_alias($symbparm);
 7073:     }
 7074:     if (!($uname && $udom)) {
 7075:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 7076:       if (!$symbparm) {	$symbparm=$cursymb; }
 7077:     } else {
 7078: 	$courseid=$env{'request.course.id'};
 7079:     }
 7080:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 7081:     my $rest;
 7082:     if (defined($therest[0])) {
 7083:        $rest=join('.',@therest);
 7084:     } else {
 7085:        $rest='';
 7086:     }
 7087: 
 7088:     my $qualifierrest=$qualifier;
 7089:     if ($rest) { $qualifierrest.='.'.$rest; }
 7090:     my $spacequalifierrest=$space;
 7091:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 7092:     if ($realm eq 'user') {
 7093: # --------------------------------------------------------------- user.resource
 7094: 	if ($space eq 'resource') {
 7095: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 7096: 		  || defined($Apache::lonhomework::parsing_a_task))
 7097: 		 &&
 7098: 		 ($symbparm eq &symbread()) ) {	
 7099: 		# if we are in the middle of processing the resource the
 7100: 		# get the value we are planning on committing
 7101:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 7102:                     return $Apache::lonhomework::results{$qualifierrest};
 7103:                 } else {
 7104:                     return $Apache::lonhomework::history{$qualifierrest};
 7105:                 }
 7106: 	    } else {
 7107: 		my %restored;
 7108: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 7109: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 7110: 		} else {
 7111: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 7112: 		}
 7113: 		return $restored{$qualifierrest};
 7114: 	    }
 7115: # ----------------------------------------------------------------- user.access
 7116:         } elsif ($space eq 'access') {
 7117: 	    # FIXME - not supporting calls for a specific user
 7118:             return &allowed($qualifier,$rest);
 7119: # ------------------------------------------ user.preferences, user.environment
 7120:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 7121: 	    if (($uname eq $env{'user.name'}) &&
 7122: 		($udom eq $env{'user.domain'})) {
 7123: 		return $env{join('.',('environment',$qualifierrest))};
 7124: 	    } else {
 7125: 		my %returnhash;
 7126: 		if (!$publicuser) {
 7127: 		    %returnhash=&userenvironment($udom,$uname,
 7128: 						 $qualifierrest);
 7129: 		}
 7130: 		return $returnhash{$qualifierrest};
 7131: 	    }
 7132: # ----------------------------------------------------------------- user.course
 7133:         } elsif ($space eq 'course') {
 7134: 	    # FIXME - not supporting calls for a specific user
 7135:             return $env{join('.',('request.course',$qualifier))};
 7136: # ------------------------------------------------------------------- user.role
 7137:         } elsif ($space eq 'role') {
 7138: 	    # FIXME - not supporting calls for a specific user
 7139:             my ($role,$where)=split(/\./,$env{'request.role'});
 7140:             if ($qualifier eq 'value') {
 7141: 		return $role;
 7142:             } elsif ($qualifier eq 'extent') {
 7143:                 return $where;
 7144:             }
 7145: # ----------------------------------------------------------------- user.domain
 7146:         } elsif ($space eq 'domain') {
 7147:             return $udom;
 7148: # ------------------------------------------------------------------- user.name
 7149:         } elsif ($space eq 'name') {
 7150:             return $uname;
 7151: # ---------------------------------------------------- Any other user namespace
 7152:         } else {
 7153: 	    my %reply;
 7154: 	    if (!$publicuser) {
 7155: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 7156: 	    }
 7157: 	    return $reply{$qualifierrest};
 7158:         }
 7159:     } elsif ($realm eq 'query') {
 7160: # ---------------------------------------------- pull stuff out of query string
 7161:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 7162: 						[$spacequalifierrest]);
 7163: 	return $env{'form.'.$spacequalifierrest}; 
 7164:    } elsif ($realm eq 'request') {
 7165: # ------------------------------------------------------------- request.browser
 7166:         if ($space eq 'browser') {
 7167: 	    if ($qualifier eq 'textremote') {
 7168: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 7169: 		    return 1;
 7170: 		} else {
 7171: 		    return 0;
 7172: 		}
 7173: 	    } else {
 7174: 		return $env{'browser.'.$qualifier};
 7175: 	    }
 7176: # ------------------------------------------------------------ request.filename
 7177:         } else {
 7178:             return $env{'request.'.$spacequalifierrest};
 7179:         }
 7180:     } elsif ($realm eq 'course') {
 7181: # ---------------------------------------------------------- course.description
 7182:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 7183:     } elsif ($realm eq 'resource') {
 7184: 
 7185: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 7186: 	    if (!$symbparm) { $symbparm=&symbread(); }
 7187: 	}
 7188: 
 7189: 	if ($space eq 'title') {
 7190: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 7191: 	    return &gettitle($symbparm);
 7192: 	}
 7193: 	
 7194: 	if ($space eq 'map') {
 7195: 	    my ($map) = &decode_symb($symbparm);
 7196: 	    return &symbread($map);
 7197: 	}
 7198: 	if ($space eq 'filename') {
 7199: 	    if ($symbparm) {
 7200: 		return &clutter((&decode_symb($symbparm))[2]);
 7201: 	    }
 7202: 	    return &hreflocation('',$env{'request.filename'});
 7203: 	}
 7204: 
 7205: 	my ($section, $group, @groups);
 7206: 	my ($courselevelm,$courselevel);
 7207: 	if ($symbparm && defined($courseid) && 
 7208: 	    $courseid eq $env{'request.course.id'}) {
 7209: 
 7210: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 7211: 
 7212: # ----------------------------------------------------- Cascading lookup scheme
 7213: 	    my $symbp=$symbparm;
 7214: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 7215: 
 7216: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 7217: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 7218: 
 7219: 	    if (($env{'user.name'} eq $uname) &&
 7220: 		($env{'user.domain'} eq $udom)) {
 7221: 		$section=$env{'request.course.sec'};
 7222:                 @groups = split(/:/,$env{'request.course.groups'});  
 7223:                 @groups=&sort_course_groups($courseid,@groups); 
 7224: 	    } else {
 7225: 		if (! defined($usection)) {
 7226: 		    $section=&getsection($udom,$uname,$courseid);
 7227: 		} else {
 7228: 		    $section = $usection;
 7229: 		}
 7230:                 @groups = &get_users_groups($udom,$uname,$courseid);
 7231: 	    }
 7232: 
 7233: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 7234: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 7235: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 7236: 
 7237: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 7238: 	    my $courselevelr=$courseid.'.'.$symbparm;
 7239: 	    $courselevelm=$courseid.'.'.$mapparm;
 7240: 
 7241: # ----------------------------------------------------------- first, check user
 7242: 
 7243: 	    my $userreply=&resdata($uname,$udom,'user',
 7244: 				       ([$courselevelr,'resource'],
 7245: 					[$courselevelm,'map'     ],
 7246: 					[$courselevel, 'course'  ]));
 7247: 	    if (defined($userreply)) { return &get_reply($userreply); }
 7248: 
 7249: # ------------------------------------------------ second, check some of course
 7250:             my $coursereply;
 7251:             if (@groups > 0) {
 7252:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 7253:                                        $mapparm,$spacequalifierrest);
 7254:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 7255:             }
 7256: 
 7257: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7258: 				  $env{'course.'.$courseid.'.domain'},
 7259: 				  'course',
 7260: 				  ([$seclevelr,   'resource'],
 7261: 				   [$seclevelm,   'map'     ],
 7262: 				   [$seclevel,    'course'  ],
 7263: 				   [$courselevelr,'resource']));
 7264: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7265: 
 7266: # ------------------------------------------------------ third, check map parms
 7267: 	    my %parmhash=();
 7268: 	    my $thisparm='';
 7269: 	    if (tie(%parmhash,'GDBM_File',
 7270: 		    $env{'request.course.fn'}.'_parms.db',
 7271: 		    &GDBM_READER(),0640)) {
 7272: 		$thisparm=$parmhash{$symbparm};
 7273: 		untie(%parmhash);
 7274: 	    }
 7275: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 7276: 	}
 7277: # ------------------------------------------ fourth, look in resource metadata
 7278: 
 7279: 	$spacequalifierrest=~s/\./\_/;
 7280: 	my $filename;
 7281: 	if (!$symbparm) { $symbparm=&symbread(); }
 7282: 	if ($symbparm) {
 7283: 	    $filename=(&decode_symb($symbparm))[2];
 7284: 	} else {
 7285: 	    $filename=$env{'request.filename'};
 7286: 	}
 7287: 	my $metadata=&metadata($filename,$spacequalifierrest);
 7288: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7289: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 7290: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7291: 
 7292: # ---------------------------------------------- fourth, look in rest of course
 7293: 	if ($symbparm && defined($courseid) && 
 7294: 	    $courseid eq $env{'request.course.id'}) {
 7295: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7296: 				     $env{'course.'.$courseid.'.domain'},
 7297: 				     'course',
 7298: 				     ([$courselevelm,'map'   ],
 7299: 				      [$courselevel, 'course']));
 7300: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7301: 	}
 7302: # ------------------------------------------------------------------ Cascade up
 7303: 	unless ($space eq '0') {
 7304: 	    my @parts=split(/_/,$space);
 7305: 	    my $id=pop(@parts);
 7306: 	    my $part=join('_',@parts);
 7307: 	    if ($part eq '') { $part='0'; }
 7308: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 7309: 				 $symbparm,$udom,$uname,$section,1);
 7310: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 7311: 	}
 7312: 	if ($recurse) { return undef; }
 7313: 	my $pack_def=&packages_tab_default($filename,$varname);
 7314: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 7315: # ---------------------------------------------------- Any other user namespace
 7316:     } elsif ($realm eq 'environment') {
 7317: # ----------------------------------------------------------------- environment
 7318: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 7319: 	    return $env{'environment.'.$spacequalifierrest};
 7320: 	} else {
 7321: 	    if ($uname eq 'anonymous' && $udom eq '') {
 7322: 		return '';
 7323: 	    }
 7324: 	    my %returnhash=&userenvironment($udom,$uname,
 7325: 					    $spacequalifierrest);
 7326: 	    return $returnhash{$spacequalifierrest};
 7327: 	}
 7328:     } elsif ($realm eq 'system') {
 7329: # ----------------------------------------------------------------- system.time
 7330: 	if ($space eq 'time') {
 7331: 	    return time;
 7332:         }
 7333:     } elsif ($realm eq 'server') {
 7334: # ----------------------------------------------------------------- system.time
 7335: 	if ($space eq 'name') {
 7336: 	    return $ENV{'SERVER_NAME'};
 7337:         }
 7338:     }
 7339:     return '';
 7340: }
 7341: 
 7342: sub get_reply {
 7343:     my ($reply_value) = @_;
 7344:     if (ref($reply_value) eq 'ARRAY') {
 7345:         if (wantarray) {
 7346: 	    return @$reply_value;
 7347:         }
 7348:         return $reply_value->[0];
 7349:     } else {
 7350:         return $reply_value;
 7351:     }
 7352: }
 7353: 
 7354: sub check_group_parms {
 7355:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 7356:     my @groupitems = ();
 7357:     my $resultitem;
 7358:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 7359:     foreach my $group (@{$groups}) {
 7360:         foreach my $level (@levels) {
 7361:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 7362:              push(@groupitems,[$item,$level->[1]]);
 7363:         }
 7364:     }
 7365:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 7366:                             $env{'course.'.$courseid.'.domain'},
 7367:                                      'course',@groupitems);
 7368:     return $coursereply;
 7369: }
 7370: 
 7371: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 7372:     my ($courseid,@groups) = @_;
 7373:     @groups = sort(@groups);
 7374:     return @groups;
 7375: }
 7376: 
 7377: sub packages_tab_default {
 7378:     my ($uri,$varname)=@_;
 7379:     my (undef,$part,$name)=split(/\./,$varname);
 7380: 
 7381:     my (@extension,@specifics,$do_default);
 7382:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 7383: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 7384: 	if ($pack_type eq 'default') {
 7385: 	    $do_default=1;
 7386: 	} elsif ($pack_type eq 'extension') {
 7387: 	    push(@extension,[$package,$pack_type,$pack_part]);
 7388: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 7389: 	    # only look at packages defaults for packages that this id is
 7390: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 7391: 	}
 7392:     }
 7393:     # first look for a package that matches the requested part id
 7394:     foreach my $package (@specifics) {
 7395: 	my (undef,$pack_type,$pack_part)=@{$package};
 7396: 	next if ($pack_part ne $part);
 7397: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7398: 	    return $packagetab{"$pack_type&$name&default"};
 7399: 	}
 7400:     }
 7401:     # look for any possible matching non extension_ package
 7402:     foreach my $package (@specifics) {
 7403: 	my (undef,$pack_type,$pack_part)=@{$package};
 7404: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7405: 	    return $packagetab{"$pack_type&$name&default"};
 7406: 	}
 7407: 	if ($pack_type eq 'part') { $pack_part='0'; }
 7408: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 7409: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 7410: 	}
 7411:     }
 7412:     # look for any posible extension_ match
 7413:     foreach my $package (@extension) {
 7414: 	my ($package,$pack_type)=@{$package};
 7415: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7416: 	    return $packagetab{"$pack_type&$name&default"};
 7417: 	}
 7418: 	if (defined($packagetab{$package."&$name&default"})) {
 7419: 	    return $packagetab{$package."&$name&default"};
 7420: 	}
 7421:     }
 7422:     # look for a global default setting
 7423:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 7424: 	return $packagetab{"default&$name&default"};
 7425:     }
 7426:     return undef;
 7427: }
 7428: 
 7429: sub add_prefix_and_part {
 7430:     my ($prefix,$part)=@_;
 7431:     my $keyroot;
 7432:     if (defined($prefix) && $prefix !~ /^__/) {
 7433: 	# prefix that has a part already
 7434: 	$keyroot=$prefix;
 7435:     } elsif (defined($prefix)) {
 7436: 	# prefix that is missing a part
 7437: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 7438:     } else {
 7439: 	# no prefix at all
 7440: 	if (defined($part)) { $keyroot='_'.$part; }
 7441:     }
 7442:     return $keyroot;
 7443: }
 7444: 
 7445: # ---------------------------------------------------------------- Get metadata
 7446: 
 7447: my %metaentry;
 7448: sub metadata {
 7449:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 7450:     $uri=&declutter($uri);
 7451:     # if it is a non metadata possible uri return quickly
 7452:     if (($uri eq '') || 
 7453: 	(($uri =~ m|^/*adm/|) && 
 7454: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 7455:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 7456: 	return undef;
 7457:     }
 7458:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 7459: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 7460: 	return undef;
 7461:     }
 7462:     my $filename=$uri;
 7463:     $uri=~s/\.meta$//;
 7464: #
 7465: # Is the metadata already cached?
 7466: # Look at timestamp of caching
 7467: # Everything is cached by the main uri, libraries are never directly cached
 7468: #
 7469:     if (!defined($liburi)) {
 7470: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 7471: 	if (defined($cached)) { return $result->{':'.$what}; }
 7472:     }
 7473:     {
 7474: #
 7475: # Is this a recursive call for a library?
 7476: #
 7477: #	if (! exists($metacache{$uri})) {
 7478: #	    $metacache{$uri}={};
 7479: #	}
 7480: 	my $cachetime = 60*60;
 7481:         if ($liburi) {
 7482: 	    $liburi=&declutter($liburi);
 7483:             $filename=$liburi;
 7484:         } else {
 7485: 	    &devalidate_cache_new('meta',$uri);
 7486: 	    undef(%metaentry);
 7487: 	}
 7488:         my %metathesekeys=();
 7489:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 7490: 	my $metastring;
 7491: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 7492: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 7493: 	    $metastring = 
 7494: 		&Apache::lonnet::ssi_body($which,
 7495: 					  ('grade_target' => 'meta'));
 7496: 	    $cachetime = 1; # only want this cached in the child not long term
 7497: 	} elsif ($uri !~ m -^(editupload)/-) {
 7498: 	    my $file=&filelocation('',&clutter($filename));
 7499: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 7500: 	    $metastring=&getfile($file);
 7501: 	}
 7502:         my $parser=HTML::LCParser->new(\$metastring);
 7503:         my $token;
 7504:         undef %metathesekeys;
 7505:         while ($token=$parser->get_token) {
 7506: 	    if ($token->[0] eq 'S') {
 7507: 		if (defined($token->[2]->{'package'})) {
 7508: #
 7509: # This is a package - get package info
 7510: #
 7511: 		    my $package=$token->[2]->{'package'};
 7512: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7513: 		    if (defined($token->[2]->{'id'})) { 
 7514: 			$keyroot.='_'.$token->[2]->{'id'}; 
 7515: 		    }
 7516: 		    if ($metaentry{':packages'}) {
 7517: 			$metaentry{':packages'}.=','.$package.$keyroot;
 7518: 		    } else {
 7519: 			$metaentry{':packages'}=$package.$keyroot;
 7520: 		    }
 7521: 		    foreach my $pack_entry (keys(%packagetab)) {
 7522: 			my $part=$keyroot;
 7523: 			$part=~s/^\_//;
 7524: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 7525: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 7526: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 7527: 			    # ignore package.tab specified default values
 7528:                             # here &package_tab_default() will fetch those
 7529: 			    if ($subp eq 'default') { next; }
 7530: 			    my $value=$packagetab{$pack_entry};
 7531: 			    my $unikey;
 7532: 			    if ($pack =~ /_0$/) {
 7533: 				$unikey='parameter_0_'.$name;
 7534: 				$part=0;
 7535: 			    } else {
 7536: 				$unikey='parameter'.$keyroot.'_'.$name;
 7537: 			    }
 7538: 			    if ($subp eq 'display') {
 7539: 				$value.=' [Part: '.$part.']';
 7540: 			    }
 7541: 			    $metaentry{':'.$unikey.'.part'}=$part;
 7542: 			    $metathesekeys{$unikey}=1;
 7543: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7544: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 7545: 			    }
 7546: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 7547: 				$metaentry{':'.$unikey}=
 7548: 				    $metaentry{':'.$unikey.'.default'};
 7549: 			    }
 7550: 			}
 7551: 		    }
 7552: 		} else {
 7553: #
 7554: # This is not a package - some other kind of start tag
 7555: #
 7556: 		    my $entry=$token->[1];
 7557: 		    my $unikey;
 7558: 		    if ($entry eq 'import') {
 7559: 			$unikey='';
 7560: 		    } else {
 7561: 			$unikey=$entry;
 7562: 		    }
 7563: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7564: 
 7565: 		    if (defined($token->[2]->{'id'})) { 
 7566: 			$unikey.='_'.$token->[2]->{'id'}; 
 7567: 		    }
 7568: 
 7569: 		    if ($entry eq 'import') {
 7570: #
 7571: # Importing a library here
 7572: #
 7573: 			if ($depthcount<20) {
 7574: 			    my $location=$parser->get_text('/import');
 7575: 			    my $dir=$filename;
 7576: 			    $dir=~s|[^/]*$||;
 7577: 			    $location=&filelocation($dir,$location);
 7578: 			    my $metadata = 
 7579: 				&metadata($uri,'keys', $location,$unikey,
 7580: 					  $depthcount+1);
 7581: 			    foreach my $meta (split(',',$metadata)) {
 7582: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 7583: 				$metathesekeys{$meta}=1;
 7584: 			    }
 7585: 			}
 7586: 		    } else { 
 7587: 			
 7588: 			if (defined($token->[2]->{'name'})) { 
 7589: 			    $unikey.='_'.$token->[2]->{'name'}; 
 7590: 			}
 7591: 			$metathesekeys{$unikey}=1;
 7592: 			foreach my $param (@{$token->[3]}) {
 7593: 			    $metaentry{':'.$unikey.'.'.$param} =
 7594: 				$token->[2]->{$param};
 7595: 			}
 7596: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 7597: 			my $default=$metaentry{':'.$unikey.'.default'};
 7598: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 7599: 		 # only ws inside the tag, and not in default, so use default
 7600: 		 # as value
 7601: 			    $metaentry{':'.$unikey}=$default;
 7602: 			} elsif ( $internaltext =~ /\S/ ) {
 7603: 		  # something interesting inside the tag
 7604: 			    $metaentry{':'.$unikey}=$internaltext;
 7605: 			} else {
 7606: 		  # no interesting values, don't set a default
 7607: 			}
 7608: # end of not-a-package not-a-library import
 7609: 		    }
 7610: # end of not-a-package start tag
 7611: 		}
 7612: # the next is the end of "start tag"
 7613: 	    }
 7614: 	}
 7615: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 7616: 	$extension = lc($extension);
 7617: 	if ($extension eq 'htm') { $extension='html'; }
 7618: 
 7619: 	foreach my $key (keys(%packagetab)) {
 7620: 	    #no specific packages #how's our extension
 7621: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 7622: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 7623: 					 \%metathesekeys);
 7624: 	}
 7625: 
 7626: 	if (!exists($metaentry{':packages'})
 7627: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 7628: 	    foreach my $key (keys(%packagetab)) {
 7629: 		#no specific packages well let's get default then
 7630: 		if ($key!~/^default&/) { next; }
 7631: 		&metadata_create_package_def($uri,$key,'default',
 7632: 					     \%metathesekeys);
 7633: 	    }
 7634: 	}
 7635: # are there custom rights to evaluate
 7636: 	if ($metaentry{':copyright'} eq 'custom') {
 7637: 
 7638:     #
 7639:     # Importing a rights file here
 7640:     #
 7641: 	    unless ($depthcount) {
 7642: 		my $location=$metaentry{':customdistributionfile'};
 7643: 		my $dir=$filename;
 7644: 		$dir=~s|[^/]*$||;
 7645: 		$location=&filelocation($dir,$location);
 7646: 		my $rights_metadata =
 7647: 		    &metadata($uri,'keys',$location,'_rights',
 7648: 			      $depthcount+1);
 7649: 		foreach my $rights (split(',',$rights_metadata)) {
 7650: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 7651: 		    $metathesekeys{$rights}=1;
 7652: 		}
 7653: 	    }
 7654: 	}
 7655: 	# uniqifiy package listing
 7656: 	my %seen;
 7657: 	my @uniq_packages =
 7658: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 7659: 	$metaentry{':packages'} = join(',',@uniq_packages);
 7660: 
 7661: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 7662: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 7663: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 7664: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 7665: # this is the end of "was not already recently cached
 7666:     }
 7667:     return $metaentry{':'.$what};
 7668: }
 7669: 
 7670: sub metadata_create_package_def {
 7671:     my ($uri,$key,$package,$metathesekeys)=@_;
 7672:     my ($pack,$name,$subp)=split(/\&/,$key);
 7673:     if ($subp eq 'default') { next; }
 7674:     
 7675:     if (defined($metaentry{':packages'})) {
 7676: 	$metaentry{':packages'}.=','.$package;
 7677:     } else {
 7678: 	$metaentry{':packages'}=$package;
 7679:     }
 7680:     my $value=$packagetab{$key};
 7681:     my $unikey;
 7682:     $unikey='parameter_0_'.$name;
 7683:     $metaentry{':'.$unikey.'.part'}=0;
 7684:     $$metathesekeys{$unikey}=1;
 7685:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7686: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 7687:     }
 7688:     if (defined($metaentry{':'.$unikey.'.default'})) {
 7689: 	$metaentry{':'.$unikey}=
 7690: 	    $metaentry{':'.$unikey.'.default'};
 7691:     }
 7692: }
 7693: 
 7694: sub metadata_generate_part0 {
 7695:     my ($metadata,$metacache,$uri) = @_;
 7696:     my %allnames;
 7697:     foreach my $metakey (keys(%$metadata)) {
 7698: 	if ($metakey=~/^parameter\_(.*)/) {
 7699: 	  my $part=$$metacache{':'.$metakey.'.part'};
 7700: 	  my $name=$$metacache{':'.$metakey.'.name'};
 7701: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 7702: 	    $allnames{$name}=$part;
 7703: 	  }
 7704: 	}
 7705:     }
 7706:     foreach my $name (keys(%allnames)) {
 7707:       $$metadata{"parameter_0_$name"}=1;
 7708:       my $key=":parameter_0_$name";
 7709:       $$metacache{"$key.part"}='0';
 7710:       $$metacache{"$key.name"}=$name;
 7711:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 7712: 					   $allnames{$name}.'_'.$name.
 7713: 					   '.type'};
 7714:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 7715: 			     '.display'};
 7716:       my $expr='[Part: '.$allnames{$name}.']';
 7717:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 7718:       $$metacache{"$key.display"}=$olddis;
 7719:     }
 7720: }
 7721: 
 7722: # ------------------------------------------------------ Devalidate title cache
 7723: 
 7724: sub devalidate_title_cache {
 7725:     my ($url)=@_;
 7726:     if (!$env{'request.course.id'}) { return; }
 7727:     my $symb=&symbread($url);
 7728:     if (!$symb) { return; }
 7729:     my $key=$env{'request.course.id'}."\0".$symb;
 7730:     &devalidate_cache_new('title',$key);
 7731: }
 7732: 
 7733: # ------------------------------------------------- Get the title of a resource
 7734: 
 7735: sub gettitle {
 7736:     my $urlsymb=shift;
 7737:     my $symb=&symbread($urlsymb);
 7738:     if ($symb) {
 7739: 	my $key=$env{'request.course.id'}."\0".$symb;
 7740: 	my ($result,$cached)=&is_cached_new('title',$key);
 7741: 	if (defined($cached)) { 
 7742: 	    return $result;
 7743: 	}
 7744: 	my ($map,$resid,$url)=&decode_symb($symb);
 7745: 	my $title='';
 7746: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 7747: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 7748: 	} else {
 7749: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7750: 		    &GDBM_READER(),0640)) {
 7751: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 7752: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 7753: 		untie(%bighash);
 7754: 	    }
 7755: 	}
 7756: 	$title=~s/\&colon\;/\:/gs;
 7757: 	if ($title) {
 7758: 	    return &do_cache_new('title',$key,$title,600);
 7759: 	}
 7760: 	$urlsymb=$url;
 7761:     }
 7762:     my $title=&metadata($urlsymb,'title');
 7763:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 7764:     return $title;
 7765: }
 7766: 
 7767: sub get_slot {
 7768:     my ($which,$cnum,$cdom)=@_;
 7769:     if (!$cnum || !$cdom) {
 7770: 	(undef,my $courseid)=&whichuser();
 7771: 	$cdom=$env{'course.'.$courseid.'.domain'};
 7772: 	$cnum=$env{'course.'.$courseid.'.num'};
 7773:     }
 7774:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 7775:     my %slotinfo;
 7776:     if (exists($remembered{$key})) {
 7777: 	$slotinfo{$which} = $remembered{$key};
 7778:     } else {
 7779: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 7780: 	&Apache::lonhomework::showhash(%slotinfo);
 7781: 	my ($tmp)=keys(%slotinfo);
 7782: 	if ($tmp=~/^error:/) { return (); }
 7783: 	$remembered{$key} = $slotinfo{$which};
 7784:     }
 7785:     if (ref($slotinfo{$which}) eq 'HASH') {
 7786: 	return %{$slotinfo{$which}};
 7787:     }
 7788:     return $slotinfo{$which};
 7789: }
 7790: # ------------------------------------------------- Update symbolic store links
 7791: 
 7792: sub symblist {
 7793:     my ($mapname,%newhash)=@_;
 7794:     $mapname=&deversion(&declutter($mapname));
 7795:     my %hash;
 7796:     if (($env{'request.course.fn'}) && (%newhash)) {
 7797:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7798:                       &GDBM_WRCREAT(),0640)) {
 7799: 	    foreach my $url (keys %newhash) {
 7800: 		next if ($url eq 'last_known'
 7801: 			 && $env{'form.no_update_last_known'});
 7802: 		$hash{declutter($url)}=&encode_symb($mapname,
 7803: 						    $newhash{$url}->[1],
 7804: 						    $newhash{$url}->[0]);
 7805:             }
 7806:             if (untie(%hash)) {
 7807: 		return 'ok';
 7808:             }
 7809:         }
 7810:     }
 7811:     return 'error';
 7812: }
 7813: 
 7814: # --------------------------------------------------------------- Verify a symb
 7815: 
 7816: sub symbverify {
 7817:     my ($symb,$thisurl)=@_;
 7818:     my $thisfn=$thisurl;
 7819:     $thisfn=&declutter($thisfn);
 7820: # direct jump to resource in page or to a sequence - will construct own symbs
 7821:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 7822: # check URL part
 7823:     my ($map,$resid,$url)=&decode_symb($symb);
 7824: 
 7825:     unless ($url eq $thisfn) { return 0; }
 7826: 
 7827:     $symb=&symbclean($symb);
 7828:     $thisurl=&deversion($thisurl);
 7829:     $thisfn=&deversion($thisfn);
 7830: 
 7831:     my %bighash;
 7832:     my $okay=0;
 7833: 
 7834:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7835:                             &GDBM_READER(),0640)) {
 7836:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 7837:         unless ($ids) { 
 7838:            $ids=$bighash{'ids_/'.$thisurl};
 7839:         }
 7840:         if ($ids) {
 7841: # ------------------------------------------------------------------- Has ID(s)
 7842: 	    foreach my $id (split(/\,/,$ids)) {
 7843: 	       my ($mapid,$resid)=split(/\./,$id);
 7844:                if (
 7845:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 7846:    eq $symb) { 
 7847: 		   if (($env{'request.role.adv'}) ||
 7848: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 7849: 		       $okay=1; 
 7850: 		   }
 7851: 	       }
 7852: 	   }
 7853:         }
 7854: 	untie(%bighash);
 7855:     }
 7856:     return $okay;
 7857: }
 7858: 
 7859: # --------------------------------------------------------------- Clean-up symb
 7860: 
 7861: sub symbclean {
 7862:     my $symb=shift;
 7863:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7864: # remove version from map
 7865:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 7866: 
 7867: # remove version from URL
 7868:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 7869: 
 7870: # remove wrapper
 7871: 
 7872:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 7873:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 7874:     return $symb;
 7875: }
 7876: 
 7877: # ---------------------------------------------- Split symb to find map and url
 7878: 
 7879: sub encode_symb {
 7880:     my ($map,$resid,$url)=@_;
 7881:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 7882: }
 7883: 
 7884: sub decode_symb {
 7885:     my $symb=shift;
 7886:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7887:     my ($map,$resid,$url)=split(/___/,$symb);
 7888:     return (&fixversion($map),$resid,&fixversion($url));
 7889: }
 7890: 
 7891: sub fixversion {
 7892:     my $fn=shift;
 7893:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 7894:     my %bighash;
 7895:     my $uri=&clutter($fn);
 7896:     my $key=$env{'request.course.id'}.'_'.$uri;
 7897: # is this cached?
 7898:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 7899:     if (defined($cached)) { return $result; }
 7900: # unfortunately not cached, or expired
 7901:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7902: 	    &GDBM_READER(),0640)) {
 7903:  	if ($bighash{'version_'.$uri}) {
 7904:  	    my $version=$bighash{'version_'.$uri};
 7905:  	    unless (($version eq 'mostrecent') || 
 7906: 		    ($version==&getversion($uri))) {
 7907:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 7908:  	    }
 7909:  	}
 7910:  	untie %bighash;
 7911:     }
 7912:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 7913: }
 7914: 
 7915: sub deversion {
 7916:     my $url=shift;
 7917:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 7918:     return $url;
 7919: }
 7920: 
 7921: # ------------------------------------------------------ Return symb list entry
 7922: 
 7923: sub symbread {
 7924:     my ($thisfn,$donotrecurse)=@_;
 7925:     my $cache_str='request.symbread.cached.'.$thisfn;
 7926:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 7927: # no filename provided? try from environment
 7928:     unless ($thisfn) {
 7929:         if ($env{'request.symb'}) {
 7930: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 7931: 	}
 7932: 	$thisfn=$env{'request.filename'};
 7933:     }
 7934:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7935: # is that filename actually a symb? Verify, clean, and return
 7936:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 7937: 	if (&symbverify($thisfn,$1)) {
 7938: 	    return $env{$cache_str}=&symbclean($thisfn);
 7939: 	}
 7940:     }
 7941:     $thisfn=declutter($thisfn);
 7942:     my %hash;
 7943:     my %bighash;
 7944:     my $syval='';
 7945:     if (($env{'request.course.fn'}) && ($thisfn)) {
 7946:         my $targetfn = $thisfn;
 7947:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 7948:             $targetfn = 'adm/wrapper/'.$thisfn;
 7949:         }
 7950: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 7951: 	    $targetfn=$1;
 7952: 	}
 7953:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7954:                       &GDBM_READER(),0640)) {
 7955: 	    $syval=$hash{$targetfn};
 7956:             untie(%hash);
 7957:         }
 7958: # ---------------------------------------------------------- There was an entry
 7959:         if ($syval) {
 7960: 	    #unless ($syval=~/\_\d+$/) {
 7961: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 7962: 		    #&appenv({'request.ambiguous' => $thisfn});
 7963: 		    #return $env{$cache_str}='';
 7964: 		#}    
 7965: 		#$syval.=$1;
 7966: 	    #}
 7967:         } else {
 7968: # ------------------------------------------------------- Was not in symb table
 7969:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7970:                             &GDBM_READER(),0640)) {
 7971: # ---------------------------------------------- Get ID(s) for current resource
 7972:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 7973:               unless ($ids) { 
 7974:                  $ids=$bighash{'ids_/'.$thisfn};
 7975:               }
 7976:               unless ($ids) {
 7977: # alias?
 7978: 		  $ids=$bighash{'mapalias_'.$thisfn};
 7979:               }
 7980:               if ($ids) {
 7981: # ------------------------------------------------------------------- Has ID(s)
 7982:                  my @possibilities=split(/\,/,$ids);
 7983:                  if ($#possibilities==0) {
 7984: # ----------------------------------------------- There is only one possibility
 7985: 		     my ($mapid,$resid)=split(/\./,$ids);
 7986: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7987: 						    $resid,$thisfn);
 7988:                  } elsif (!$donotrecurse) {
 7989: # ------------------------------------------ There is more than one possibility
 7990:                      my $realpossible=0;
 7991:                      foreach my $id (@possibilities) {
 7992: 			 my $file=$bighash{'src_'.$id};
 7993:                          if (&allowed('bre',$file)) {
 7994:          		    my ($mapid,$resid)=split(/\./,$id);
 7995:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 7996: 				$realpossible++;
 7997:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7998: 						    $resid,$thisfn);
 7999:                             }
 8000: 			 }
 8001:                      }
 8002: 		     if ($realpossible!=1) { $syval=''; }
 8003:                  } else {
 8004:                      $syval='';
 8005:                  }
 8006: 	      }
 8007:               untie(%bighash)
 8008:            }
 8009:         }
 8010:         if ($syval) {
 8011: 	    return $env{$cache_str}=$syval;
 8012:         }
 8013:     }
 8014:     &appenv({'request.ambiguous' => $thisfn});
 8015:     return $env{$cache_str}='';
 8016: }
 8017: 
 8018: # ---------------------------------------------------------- Return random seed
 8019: 
 8020: sub numval {
 8021:     my $txt=shift;
 8022:     $txt=~tr/A-J/0-9/;
 8023:     $txt=~tr/a-j/0-9/;
 8024:     $txt=~tr/K-T/0-9/;
 8025:     $txt=~tr/k-t/0-9/;
 8026:     $txt=~tr/U-Z/0-5/;
 8027:     $txt=~tr/u-z/0-5/;
 8028:     $txt=~s/\D//g;
 8029:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 8030:     return int($txt);
 8031: }
 8032: 
 8033: sub numval2 {
 8034:     my $txt=shift;
 8035:     $txt=~tr/A-J/0-9/;
 8036:     $txt=~tr/a-j/0-9/;
 8037:     $txt=~tr/K-T/0-9/;
 8038:     $txt=~tr/k-t/0-9/;
 8039:     $txt=~tr/U-Z/0-5/;
 8040:     $txt=~tr/u-z/0-5/;
 8041:     $txt=~s/\D//g;
 8042:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8043:     my $total;
 8044:     foreach my $val (@txts) { $total+=$val; }
 8045:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 8046:     return int($total);
 8047: }
 8048: 
 8049: sub numval3 {
 8050:     use integer;
 8051:     my $txt=shift;
 8052:     $txt=~tr/A-J/0-9/;
 8053:     $txt=~tr/a-j/0-9/;
 8054:     $txt=~tr/K-T/0-9/;
 8055:     $txt=~tr/k-t/0-9/;
 8056:     $txt=~tr/U-Z/0-5/;
 8057:     $txt=~tr/u-z/0-5/;
 8058:     $txt=~s/\D//g;
 8059:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8060:     my $total;
 8061:     foreach my $val (@txts) { $total+=$val; }
 8062:     if ($_64bit) { $total=(($total<<32)>>32); }
 8063:     return $total;
 8064: }
 8065: 
 8066: sub digest {
 8067:     my ($data)=@_;
 8068:     my $digest=&Digest::MD5::md5($data);
 8069:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 8070:     my ($e,$f);
 8071:     {
 8072:         use integer;
 8073:         $e=($a+$b);
 8074:         $f=($c+$d);
 8075:         if ($_64bit) {
 8076:             $e=(($e<<32)>>32);
 8077:             $f=(($f<<32)>>32);
 8078:         }
 8079:     }
 8080:     if (wantarray) {
 8081: 	return ($e,$f);
 8082:     } else {
 8083: 	my $g;
 8084: 	{
 8085: 	    use integer;
 8086: 	    $g=($e+$f);
 8087: 	    if ($_64bit) {
 8088: 		$g=(($g<<32)>>32);
 8089: 	    }
 8090: 	}
 8091: 	return $g;
 8092:     }
 8093: }
 8094: 
 8095: sub latest_rnd_algorithm_id {
 8096:     return '64bit5';
 8097: }
 8098: 
 8099: sub get_rand_alg {
 8100:     my ($courseid)=@_;
 8101:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 8102:     if ($courseid) {
 8103: 	return $env{"course.$courseid.rndseed"};
 8104:     }
 8105:     return &latest_rnd_algorithm_id();
 8106: }
 8107: 
 8108: sub validCODE {
 8109:     my ($CODE)=@_;
 8110:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 8111:     return 0;
 8112: }
 8113: 
 8114: sub getCODE {
 8115:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 8116:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 8117: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 8118: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 8119: 	return $Apache::lonhomework::history{'resource.CODE'};
 8120:     }
 8121:     return undef;
 8122: }
 8123: 
 8124: sub rndseed {
 8125:     my ($symb,$courseid,$domain,$username)=@_;
 8126:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 8127:     if (!defined($symb)) {
 8128: 	unless ($symb=$wsymb) { return time; }
 8129:     }
 8130:     if (!$courseid) { $courseid=$wcourseid; }
 8131:     if (!$domain) { $domain=$wdomain; }
 8132:     if (!$username) { $username=$wusername }
 8133:     my $which=&get_rand_alg();
 8134: 
 8135:     if (defined(&getCODE())) {
 8136: 	if ($which eq '64bit5') {
 8137: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 8138: 	} elsif ($which eq '64bit4') {
 8139: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 8140: 	} else {
 8141: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 8142: 	}
 8143:     } elsif ($which eq '64bit5') {
 8144: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 8145:     } elsif ($which eq '64bit4') {
 8146: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 8147:     } elsif ($which eq '64bit3') {
 8148: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 8149:     } elsif ($which eq '64bit2') {
 8150: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 8151:     } elsif ($which eq '64bit') {
 8152: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 8153:     }
 8154:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 8155: }
 8156: 
 8157: sub rndseed_32bit {
 8158:     my ($symb,$courseid,$domain,$username)=@_;
 8159:     {
 8160: 	use integer;
 8161: 	my $symbchck=unpack("%32C*",$symb) << 27;
 8162: 	my $symbseed=numval($symb) << 22;
 8163: 	my $namechck=unpack("%32C*",$username) << 17;
 8164: 	my $nameseed=numval($username) << 12;
 8165: 	my $domainseed=unpack("%32C*",$domain) << 7;
 8166: 	my $courseseed=unpack("%32C*",$courseid);
 8167: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 8168: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8169: 	#&logthis("rndseed :$num:$symb");
 8170: 	if ($_64bit) { $num=(($num<<32)>>32); }
 8171: 	return $num;
 8172:     }
 8173: }
 8174: 
 8175: sub rndseed_64bit {
 8176:     my ($symb,$courseid,$domain,$username)=@_;
 8177:     {
 8178: 	use integer;
 8179: 	my $symbchck=unpack("%32S*",$symb) << 21;
 8180: 	my $symbseed=numval($symb) << 10;
 8181: 	my $namechck=unpack("%32S*",$username);
 8182: 	
 8183: 	my $nameseed=numval($username) << 21;
 8184: 	my $domainseed=unpack("%32S*",$domain) << 10;
 8185: 	my $courseseed=unpack("%32S*",$courseid);
 8186: 	
 8187: 	my $num1=$symbchck+$symbseed+$namechck;
 8188: 	my $num2=$nameseed+$domainseed+$courseseed;
 8189: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8190: 	#&logthis("rndseed :$num:$symb");
 8191: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8192: 	return "$num1,$num2";
 8193:     }
 8194: }
 8195: 
 8196: sub rndseed_64bit2 {
 8197:     my ($symb,$courseid,$domain,$username)=@_;
 8198:     {
 8199: 	use integer;
 8200: 	# strings need to be an even # of cahracters long, it it is odd the
 8201:         # last characters gets thrown away
 8202: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8203: 	my $symbseed=numval($symb) << 10;
 8204: 	my $namechck=unpack("%32S*",$username.' ');
 8205: 	
 8206: 	my $nameseed=numval($username) << 21;
 8207: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8208: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8209: 	
 8210: 	my $num1=$symbchck+$symbseed+$namechck;
 8211: 	my $num2=$nameseed+$domainseed+$courseseed;
 8212: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8213: 	#&logthis("rndseed :$num:$symb");
 8214: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8215: 	return "$num1,$num2";
 8216:     }
 8217: }
 8218: 
 8219: sub rndseed_64bit3 {
 8220:     my ($symb,$courseid,$domain,$username)=@_;
 8221:     {
 8222: 	use integer;
 8223: 	# strings need to be an even # of cahracters long, it it is odd the
 8224:         # last characters gets thrown away
 8225: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8226: 	my $symbseed=numval2($symb) << 10;
 8227: 	my $namechck=unpack("%32S*",$username.' ');
 8228: 	
 8229: 	my $nameseed=numval2($username) << 21;
 8230: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8231: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8232: 	
 8233: 	my $num1=$symbchck+$symbseed+$namechck;
 8234: 	my $num2=$nameseed+$domainseed+$courseseed;
 8235: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8236: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8237: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8238: 	
 8239: 	return "$num1:$num2";
 8240:     }
 8241: }
 8242: 
 8243: sub rndseed_64bit4 {
 8244:     my ($symb,$courseid,$domain,$username)=@_;
 8245:     {
 8246: 	use integer;
 8247: 	# strings need to be an even # of cahracters long, it it is odd the
 8248:         # last characters gets thrown away
 8249: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8250: 	my $symbseed=numval3($symb) << 10;
 8251: 	my $namechck=unpack("%32S*",$username.' ');
 8252: 	
 8253: 	my $nameseed=numval3($username) << 21;
 8254: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8255: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8256: 	
 8257: 	my $num1=$symbchck+$symbseed+$namechck;
 8258: 	my $num2=$nameseed+$domainseed+$courseseed;
 8259: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8260: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8261: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8262: 	
 8263: 	return "$num1:$num2";
 8264:     }
 8265: }
 8266: 
 8267: sub rndseed_64bit5 {
 8268:     my ($symb,$courseid,$domain,$username)=@_;
 8269:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 8270:     return "$num1:$num2";
 8271: }
 8272: 
 8273: sub rndseed_CODE_64bit {
 8274:     my ($symb,$courseid,$domain,$username)=@_;
 8275:     {
 8276: 	use integer;
 8277: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8278: 	my $symbseed=numval2($symb);
 8279: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8280: 	my $CODEseed=numval(&getCODE());
 8281: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8282: 	my $num1=$symbseed+$CODEchck;
 8283: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8284: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8285: 	#&logthis("rndseed :$num1:$num2:$symb");
 8286: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8287: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8288: 	return "$num1:$num2";
 8289:     }
 8290: }
 8291: 
 8292: sub rndseed_CODE_64bit4 {
 8293:     my ($symb,$courseid,$domain,$username)=@_;
 8294:     {
 8295: 	use integer;
 8296: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8297: 	my $symbseed=numval3($symb);
 8298: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8299: 	my $CODEseed=numval3(&getCODE());
 8300: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8301: 	my $num1=$symbseed+$CODEchck;
 8302: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8303: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8304: 	#&logthis("rndseed :$num1:$num2:$symb");
 8305: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8306: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8307: 	return "$num1:$num2";
 8308:     }
 8309: }
 8310: 
 8311: sub rndseed_CODE_64bit5 {
 8312:     my ($symb,$courseid,$domain,$username)=@_;
 8313:     my $code = &getCODE();
 8314:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 8315:     return "$num1:$num2";
 8316: }
 8317: 
 8318: sub setup_random_from_rndseed {
 8319:     my ($rndseed)=@_;
 8320:     if ($rndseed =~/([,:])/) {
 8321: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 8322: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 8323:     } else {
 8324: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 8325:     }
 8326: }
 8327: 
 8328: sub latest_receipt_algorithm_id {
 8329:     return 'receipt3';
 8330: }
 8331: 
 8332: sub recunique {
 8333:     my $fucourseid=shift;
 8334:     my $unique;
 8335:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 8336: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8337: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 8338:     } else {
 8339: 	$unique=$perlvar{'lonReceipt'};
 8340:     }
 8341:     return unpack("%32C*",$unique);
 8342: }
 8343: 
 8344: sub recprefix {
 8345:     my $fucourseid=shift;
 8346:     my $prefix;
 8347:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 8348: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8349: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 8350:     } else {
 8351: 	$prefix=$perlvar{'lonHostID'};
 8352:     }
 8353:     return unpack("%32C*",$prefix);
 8354: }
 8355: 
 8356: sub ireceipt {
 8357:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 8358: 
 8359:     my $return =&recprefix($fucourseid).'-';
 8360: 
 8361:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 8362: 	$env{'request.state'} eq 'construct') {
 8363: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 8364: 	return $return;
 8365:     }
 8366: 
 8367:     my $cuname=unpack("%32C*",$funame);
 8368:     my $cudom=unpack("%32C*",$fudom);
 8369:     my $cucourseid=unpack("%32C*",$fucourseid);
 8370:     my $cusymb=unpack("%32C*",$fusymb);
 8371:     my $cunique=&recunique($fucourseid);
 8372:     my $cpart=unpack("%32S*",$part);
 8373:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 8374: 
 8375: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 8376: 			       
 8377: 	$return.= ($cunique%$cuname+
 8378: 		   $cunique%$cudom+
 8379: 		   $cusymb%$cuname+
 8380: 		   $cusymb%$cudom+
 8381: 		   $cucourseid%$cuname+
 8382: 		   $cucourseid%$cudom+
 8383: 		   $cpart%$cuname+
 8384: 		   $cpart%$cudom);
 8385:     } else {
 8386: 	$return.= ($cunique%$cuname+
 8387: 		   $cunique%$cudom+
 8388: 		   $cusymb%$cuname+
 8389: 		   $cusymb%$cudom+
 8390: 		   $cucourseid%$cuname+
 8391: 		   $cucourseid%$cudom);
 8392:     }
 8393:     return $return;
 8394: }
 8395: 
 8396: sub receipt {
 8397:     my ($part)=@_;
 8398:     my ($symb,$courseid,$domain,$name) = &whichuser();
 8399:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 8400: }
 8401: 
 8402: sub whichuser {
 8403:     my ($passedsymb)=@_;
 8404:     my ($symb,$courseid,$domain,$name,$publicuser);
 8405:     if (defined($env{'form.grade_symb'})) {
 8406: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 8407: 	my $allowed=&allowed('vgr',$tmp_courseid);
 8408: 	if (!$allowed &&
 8409: 	    exists($env{'request.course.sec'}) &&
 8410: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 8411: 	    $allowed=&allowed('vgr',$tmp_courseid.
 8412: 			      '/'.$env{'request.course.sec'});
 8413: 	}
 8414: 	if ($allowed) {
 8415: 	    ($symb)=&get_env_multiple('form.grade_symb');
 8416: 	    $courseid=$tmp_courseid;
 8417: 	    ($domain)=&get_env_multiple('form.grade_domain');
 8418: 	    ($name)=&get_env_multiple('form.grade_username');
 8419: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 8420: 	}
 8421:     }
 8422:     if (!$passedsymb) {
 8423: 	$symb=&symbread();
 8424:     } else {
 8425: 	$symb=$passedsymb;
 8426:     }
 8427:     $courseid=$env{'request.course.id'};
 8428:     $domain=$env{'user.domain'};
 8429:     $name=$env{'user.name'};
 8430:     if ($name eq 'public' && $domain eq 'public') {
 8431: 	if (!defined($env{'form.username'})) {
 8432: 	    $env{'form.username'}.=time.rand(10000000);
 8433: 	}
 8434: 	$name.=$env{'form.username'};
 8435:     }
 8436:     return ($symb,$courseid,$domain,$name,$publicuser);
 8437: 
 8438: }
 8439: 
 8440: # ------------------------------------------------------------ Serves up a file
 8441: # returns either the contents of the file or 
 8442: # -1 if the file doesn't exist
 8443: #
 8444: # if the target is a file that was uploaded via DOCS, 
 8445: # a check will be made to see if a current copy exists on the local server,
 8446: # if it does this will be served, otherwise a copy will be retrieved from
 8447: # the home server for the course and stored in /home/httpd/html/userfiles on
 8448: # the local server.   
 8449: 
 8450: sub getfile {
 8451:     my ($file) = @_;
 8452:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8453:     &repcopy($file);
 8454:     return &readfile($file);
 8455: }
 8456: 
 8457: sub repcopy_userfile {
 8458:     my ($file)=@_;
 8459:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8460:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 8461:     my ($cdom,$cnum,$filename) = 
 8462: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 8463:     my $uri="/uploaded/$cdom/$cnum/$filename";
 8464:     if (-e "$file") {
 8465: # we already have a local copy, check it out
 8466: 	my @fileinfo = stat($file);
 8467: 	my $rtncode;
 8468: 	my $info;
 8469: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 8470: 	if ($lwpresp ne 'ok') {
 8471: # there is no such file anymore, even though we had a local copy
 8472: 	    if ($rtncode eq '404') {
 8473: 		unlink($file);
 8474: 	    }
 8475: 	    return -1;
 8476: 	}
 8477: 	if ($info < $fileinfo[9]) {
 8478: # nice, the file we have is up-to-date, just say okay
 8479: 	    return 'ok';
 8480: 	} else {
 8481: # the file is outdated, get rid of it
 8482: 	    unlink($file);
 8483: 	}
 8484:     }
 8485: # one way or the other, at this point, we don't have the file
 8486: # construct the correct path for the file
 8487:     my @parts = ($cdom,$cnum); 
 8488:     if ($filename =~ m|^(.+)/[^/]+$|) {
 8489: 	push @parts, split(/\//,$1);
 8490:     }
 8491:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 8492:     foreach my $part (@parts) {
 8493: 	$path .= '/'.$part;
 8494: 	if (!-e $path) {
 8495: 	    mkdir($path,0770);
 8496: 	}
 8497:     }
 8498: # now the path exists for sure
 8499: # get a user agent
 8500:     my $ua=new LWP::UserAgent;
 8501:     my $transferfile=$file.'.in.transfer';
 8502: # FIXME: this should flock
 8503:     if (-e $transferfile) { return 'ok'; }
 8504:     my $request;
 8505:     $uri=~s/^\///;
 8506:     my $homeserver = &homeserver($cnum,$cdom);
 8507:     my $protocol = $protocol{$homeserver};
 8508:     $protocol = 'http' if ($protocol ne 'https');
 8509:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
 8510:     my $response=$ua->request($request,$transferfile);
 8511: # did it work?
 8512:     if ($response->is_error()) {
 8513: 	unlink($transferfile);
 8514: 	&logthis("Userfile repcopy failed for $uri");
 8515: 	return -1;
 8516:     }
 8517: # worked, rename the transfer file
 8518:     rename($transferfile,$file);
 8519:     return 'ok';
 8520: }
 8521: 
 8522: sub tokenwrapper {
 8523:     my $uri=shift;
 8524:     $uri=~s|^https?\://([^/]+)||;
 8525:     $uri=~s|^/||;
 8526:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 8527:     my $token=$1;
 8528:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 8529:     if ($udom && $uname && $file) {
 8530: 	$file=~s|(\?\.*)*$||;
 8531:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 8532:         my $homeserver = &homeserver($uname,$udom);
 8533:         my $protocol = $protocol{$homeserver};
 8534:         $protocol = 'http' if ($protocol ne 'https');
 8535:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
 8536:                (($uri=~/\?/)?'&':'?').'token='.$token.
 8537:                                '&tokenissued='.$perlvar{'lonHostID'};
 8538:     } else {
 8539:         return '/adm/notfound.html';
 8540:     }
 8541: }
 8542: 
 8543: # call with reqtype HEAD: get last modification time
 8544: # call with reqtype GET: get the file contents
 8545: # Do not call this with reqtype GET for large files! It loads everything into memory
 8546: #
 8547: sub getuploaded {
 8548:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 8549:     $uri=~s/^\///;
 8550:     my $homeserver = &homeserver($cnum,$cdom);
 8551:     my $protocol = $protocol{$homeserver};
 8552:     $protocol = 'http' if ($protocol ne 'https');
 8553:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
 8554:     my $ua=new LWP::UserAgent;
 8555:     my $request=new HTTP::Request($reqtype,$uri);
 8556:     my $response=$ua->request($request);
 8557:     $$rtncode = $response->code;
 8558:     if (! $response->is_success()) {
 8559: 	return 'failed';
 8560:     }      
 8561:     if ($reqtype eq 'HEAD') {
 8562: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 8563:     } elsif ($reqtype eq 'GET') {
 8564: 	$$info = $response->content;
 8565:     }
 8566:     return 'ok';
 8567: }
 8568: 
 8569: sub readfile {
 8570:     my $file = shift;
 8571:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 8572:     my $fh;
 8573:     open($fh,"<$file");
 8574:     my $a='';
 8575:     while (my $line = <$fh>) { $a .= $line; }
 8576:     return $a;
 8577: }
 8578: 
 8579: sub filelocation {
 8580:     my ($dir,$file) = @_;
 8581:     my $location;
 8582:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 8583: 
 8584:     if ($file =~ m-^/adm/-) {
 8585: 	$file=~s-^/adm/wrapper/-/-;
 8586: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8587:     }
 8588: 
 8589:     if ($file=~m:^/~:) { # is a contruction space reference
 8590:         $location = $file;
 8591:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 8592:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 8593: 	# is a correct contruction space reference
 8594:         $location = $file;
 8595:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
 8596:         $location = $file;
 8597:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 8598:         my ($udom,$uname,$filename)=
 8599:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 8600:         my $home=&homeserver($uname,$udom);
 8601:         my $is_me=0;
 8602:         my @ids=&current_machine_ids();
 8603:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 8604:         if ($is_me) {
 8605:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
 8606:         } else {
 8607:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 8608:   	      $udom.'/'.$uname.'/'.$filename;
 8609:         }
 8610:     } elsif ($file =~ m-^/adm/-) {
 8611: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 8612:     } else {
 8613:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8614:         $file=~s:^/res/:/:;
 8615:         if ( !( $file =~ m:^/:) ) {
 8616:             $location = $dir. '/'.$file;
 8617:         } else {
 8618:             $location = '/home/httpd/html/res'.$file;
 8619:         }
 8620:     }
 8621:     $location=~s://+:/:g; # remove duplicate /
 8622:     while ($location=~m{/\.\./}) {
 8623: 	if ($location =~ m{/[^/]+/\.\./}) {
 8624: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 8625: 	} else {
 8626: 	    $location=~ s{/\.\./}{/}g;
 8627: 	}
 8628:     } #remove dir/..
 8629:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 8630:     return $location;
 8631: }
 8632: 
 8633: sub hreflocation {
 8634:     my ($dir,$file)=@_;
 8635:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
 8636: 	$file=filelocation($dir,$file);
 8637:     } elsif ($file=~m-^/adm/-) {
 8638: 	$file=~s-^/adm/wrapper/-/-;
 8639: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8640:     }
 8641:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 8642: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 8643:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 8644: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 8645:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 8646: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 8647: 	    -/uploaded/$1/$2/-x;
 8648:     }
 8649:     if ($file=~ m{^/userfiles/}) {
 8650: 	$file =~ s{^/userfiles/}{/uploaded/};
 8651:     }
 8652:     return $file;
 8653: }
 8654: 
 8655: sub current_machine_domains {
 8656:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 8657: }
 8658: 
 8659: sub machine_domains {
 8660:     my ($hostname) = @_;
 8661:     my @domains;
 8662:     my %hostname = &all_hostnames();
 8663:     while( my($id, $name) = each(%hostname)) {
 8664: #	&logthis("-$id-$name-$hostname-");
 8665: 	if ($hostname eq $name) {
 8666: 	    push(@domains,&host_domain($id));
 8667: 	}
 8668:     }
 8669:     return @domains;
 8670: }
 8671: 
 8672: sub current_machine_ids {
 8673:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 8674: }
 8675: 
 8676: sub machine_ids {
 8677:     my ($hostname) = @_;
 8678:     $hostname ||= &hostname($perlvar{'lonHostID'});
 8679:     my @ids;
 8680:     my %name_to_host = &all_names();
 8681:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 8682: 	return @{ $name_to_host{$hostname} };
 8683:     }
 8684:     return;
 8685: }
 8686: 
 8687: sub additional_machine_domains {
 8688:     my @domains;
 8689:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 8690:     while( my $line = <$fh>) {
 8691:         $line =~ s/\s//g;
 8692:         push(@domains,$line);
 8693:     }
 8694:     return @domains;
 8695: }
 8696: 
 8697: sub default_login_domain {
 8698:     my $domain = $perlvar{'lonDefDomain'};
 8699:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 8700:     foreach my $posdom (&current_machine_domains(),
 8701:                         &additional_machine_domains()) {
 8702:         if (lc($posdom) eq lc($testdomain)) {
 8703:             $domain=$posdom;
 8704:             last;
 8705:         }
 8706:     }
 8707:     return $domain;
 8708: }
 8709: 
 8710: # ------------------------------------------------------------- Declutters URLs
 8711: 
 8712: sub declutter {
 8713:     my $thisfn=shift;
 8714:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8715:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8716:     $thisfn=~s/^\///;
 8717:     $thisfn=~s|^adm/wrapper/||;
 8718:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 8719:     $thisfn=~s/^res\///;
 8720:     $thisfn=~s/\?.+$//;
 8721:     return $thisfn;
 8722: }
 8723: 
 8724: # ------------------------------------------------------------- Clutter up URLs
 8725: 
 8726: sub clutter {
 8727:     my $thisfn='/'.&declutter(shift);
 8728:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 8729: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 8730:        $thisfn='/res'.$thisfn; 
 8731:     }
 8732:     if ($thisfn !~m|/adm|) {
 8733: 	if ($thisfn =~ m|/ext/|) {
 8734: 	    $thisfn='/adm/wrapper'.$thisfn;
 8735: 	} else {
 8736: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 8737: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 8738: 	    if ($embstyle eq 'ssi'
 8739: 		|| ($embstyle eq 'hdn')
 8740: 		|| ($embstyle eq 'rat')
 8741: 		|| ($embstyle eq 'prv')
 8742: 		|| ($embstyle eq 'ign')) {
 8743: 		#do nothing with these
 8744: 	    } elsif (($embstyle eq 'img') 
 8745: 		|| ($embstyle eq 'emb')
 8746: 		|| ($embstyle eq 'wrp')) {
 8747: 		$thisfn='/adm/wrapper'.$thisfn;
 8748: 	    } elsif ($embstyle eq 'unk'
 8749: 		     && $thisfn!~/\.(sequence|page)$/) {
 8750: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 8751: 	    } else {
 8752: #		&logthis("Got a blank emb style");
 8753: 	    }
 8754: 	}
 8755:     }
 8756:     return $thisfn;
 8757: }
 8758: 
 8759: sub clutter_with_no_wrapper {
 8760:     my $uri = &clutter(shift);
 8761:     if ($uri =~ m-^/adm/-) {
 8762: 	$uri =~ s-^/adm/wrapper/-/-;
 8763: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 8764:     }
 8765:     return $uri;
 8766: }
 8767: 
 8768: sub freeze_escape {
 8769:     my ($value)=@_;
 8770:     if (ref($value)) {
 8771: 	$value=&nfreeze($value);
 8772: 	return '__FROZEN__'.&escape($value);
 8773:     }
 8774:     return &escape($value);
 8775: }
 8776: 
 8777: 
 8778: sub thaw_unescape {
 8779:     my ($value)=@_;
 8780:     if ($value =~ /^__FROZEN__/) {
 8781: 	substr($value,0,10,undef);
 8782: 	$value=&unescape($value);
 8783: 	return &thaw($value);
 8784:     }
 8785:     return &unescape($value);
 8786: }
 8787: 
 8788: sub correct_line_ends {
 8789:     my ($result)=@_;
 8790:     $$result =~s/\r\n/\n/mg;
 8791:     $$result =~s/\r/\n/mg;
 8792: }
 8793: # ================================================================ Main Program
 8794: 
 8795: sub goodbye {
 8796:    &logthis("Starting Shut down");
 8797: #not converted to using infrastruture and probably shouldn't be
 8798:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 8799: #converted
 8800: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 8801:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 8802: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 8803: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 8804: #1.1 only
 8805: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 8806: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 8807: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 8808: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 8809:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 8810:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 8811:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 8812:    &flushcourselogs();
 8813:    &logthis("Shutting down");
 8814: }
 8815: 
 8816: sub get_dns {
 8817:     my ($url,$func,$ignore_cache) = @_;
 8818:     if (!$ignore_cache) {
 8819: 	my ($content,$cached)=
 8820: 	    &Apache::lonnet::is_cached_new('dns',$url);
 8821: 	if ($cached) {
 8822: 	    &$func($content);
 8823: 	    return;
 8824: 	}
 8825:     }
 8826: 
 8827:     my %alldns;
 8828:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8829:     foreach my $dns (<$config>) {
 8830: 	next if ($dns !~ /^\^(\S*)/x);
 8831:         my $line = $1;
 8832:         my ($host,$protocol) = split(/:/,$line);
 8833:         if ($protocol ne 'https') {
 8834:             $protocol = 'http';
 8835:         }
 8836: 	$alldns{$host} = $protocol;
 8837:     }
 8838:     while (%alldns) {
 8839: 	my ($dns) = keys(%alldns);
 8840: 	my $ua=new LWP::UserAgent;
 8841: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
 8842: 	my $response=$ua->request($request);
 8843:         delete($alldns{$dns});
 8844: 	next if ($response->is_error());
 8845: 	my @content = split("\n",$response->content);
 8846: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 8847: 	&$func(\@content);
 8848: 	return;
 8849:     }
 8850:     close($config);
 8851:     my $which = (split('/',$url))[3];
 8852:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 8853:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 8854:     my @content = <$config>;
 8855:     &$func(\@content);
 8856:     return;
 8857: }
 8858: # ------------------------------------------------------------ Read domain file
 8859: {
 8860:     my $loaded;
 8861:     my %domain;
 8862: 
 8863:     sub parse_domain_tab {
 8864: 	my ($lines) = @_;
 8865: 	foreach my $line (@$lines) {
 8866: 	    next if ($line =~ /^(\#|\s*$ )/x);
 8867: 
 8868: 	    chomp($line);
 8869: 	    my ($name,@elements) = split(/:/,$line,9);
 8870: 	    my %this_domain;
 8871: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 8872: 			       'lang_def', 'city', 'longi', 'lati',
 8873: 			       'primary') {
 8874: 		$this_domain{$field} = shift(@elements);
 8875: 	    }
 8876: 	    $domain{$name} = \%this_domain;
 8877: 	}
 8878:     }
 8879: 
 8880:     sub reset_domain_info {
 8881: 	undef($loaded);
 8882: 	undef(%domain);
 8883:     }
 8884: 
 8885:     sub load_domain_tab {
 8886: 	my ($ignore_cache) = @_;
 8887: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 8888: 	my $fh;
 8889: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 8890: 	    my @lines = <$fh>;
 8891: 	    &parse_domain_tab(\@lines);
 8892: 	}
 8893: 	close($fh);
 8894: 	$loaded = 1;
 8895:     }
 8896: 
 8897:     sub domain {
 8898: 	&load_domain_tab() if (!$loaded);
 8899: 
 8900: 	my ($name,$what) = @_;
 8901: 	return if ( !exists($domain{$name}) );
 8902: 
 8903: 	if (!$what) {
 8904: 	    return $domain{$name}{'description'};
 8905: 	}
 8906: 	return $domain{$name}{$what};
 8907:     }
 8908: 
 8909:     sub domain_info {
 8910:         &load_domain_tab() if (!$loaded);
 8911:         return %domain;
 8912:     }
 8913: 
 8914: }
 8915: 
 8916: 
 8917: # ------------------------------------------------------------- Read hosts file
 8918: {
 8919:     my %hostname;
 8920:     my %hostdom;
 8921:     my %libserv;
 8922:     my $loaded;
 8923:     my %name_to_host;
 8924: 
 8925:     sub parse_hosts_tab {
 8926: 	my ($file) = @_;
 8927: 	foreach my $configline (@$file) {
 8928: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 8929: 	    next if ($configline =~ /^\^/);
 8930: 	    chomp($configline);
 8931: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
 8932: 	    $name=~s/\s//g;
 8933: 	    if ($id && $domain && $role && $name) {
 8934: 		$hostname{$id}=$name;
 8935: 		push(@{$name_to_host{$name}}, $id);
 8936: 		$hostdom{$id}=$domain;
 8937: 		if ($role eq 'library') { $libserv{$id}=$name; }
 8938:                 if (defined($protocol)) {
 8939:                     if ($protocol eq 'https') {
 8940:                         $protocol{$id} = $protocol;
 8941:                     } else {
 8942:                         $protocol{$id} = 'http'; 
 8943:                     }
 8944:                 } else {
 8945:                     $protocol{$id} = 'http';
 8946:                 }
 8947: 	    }
 8948: 	}
 8949:     }
 8950:     
 8951:     sub reset_hosts_info {
 8952: 	&purge_remembered();
 8953: 	&reset_domain_info();
 8954: 	&reset_hosts_ip_info();
 8955: 	undef(%name_to_host);
 8956: 	undef(%hostname);
 8957: 	undef(%hostdom);
 8958: 	undef(%libserv);
 8959: 	undef($loaded);
 8960:     }
 8961: 
 8962:     sub load_hosts_tab {
 8963: 	my ($ignore_cache) = @_;
 8964: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 8965: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8966: 	my @config = <$config>;
 8967: 	&parse_hosts_tab(\@config);
 8968: 	close($config);
 8969: 	$loaded=1;
 8970:     }
 8971: 
 8972:     sub hostname {
 8973: 	&load_hosts_tab() if (!$loaded);
 8974: 
 8975: 	my ($lonid) = @_;
 8976: 	return $hostname{$lonid};
 8977:     }
 8978: 
 8979:     sub all_hostnames {
 8980: 	&load_hosts_tab() if (!$loaded);
 8981: 
 8982: 	return %hostname;
 8983:     }
 8984: 
 8985:     sub all_names {
 8986: 	&load_hosts_tab() if (!$loaded);
 8987: 
 8988: 	return %name_to_host;
 8989:     }
 8990: 
 8991:     sub all_host_domain {
 8992:         &load_hosts_tab() if (!$loaded);
 8993:         return %hostdom;
 8994:     }
 8995: 
 8996:     sub is_library {
 8997: 	&load_hosts_tab() if (!$loaded);
 8998: 
 8999: 	return exists($libserv{$_[0]});
 9000:     }
 9001: 
 9002:     sub all_library {
 9003: 	&load_hosts_tab() if (!$loaded);
 9004: 
 9005: 	return %libserv;
 9006:     }
 9007: 
 9008:     sub get_servers {
 9009: 	&load_hosts_tab() if (!$loaded);
 9010: 
 9011: 	my ($domain,$type) = @_;
 9012: 	my %possible_hosts = ($type eq 'library') ? %libserv
 9013: 	                                          : %hostname;
 9014: 	my %result;
 9015: 	if (ref($domain) eq 'ARRAY') {
 9016: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9017: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 9018: 		    $result{$host} = $hostname;
 9019: 		}
 9020: 	    }
 9021: 	} else {
 9022: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9023: 		if ($hostdom{$host} eq $domain) {
 9024: 		    $result{$host} = $hostname;
 9025: 		}
 9026: 	    }
 9027: 	}
 9028: 	return %result;
 9029:     }
 9030: 
 9031:     sub host_domain {
 9032: 	&load_hosts_tab() if (!$loaded);
 9033: 
 9034: 	my ($lonid) = @_;
 9035: 	return $hostdom{$lonid};
 9036:     }
 9037: 
 9038:     sub all_domains {
 9039: 	&load_hosts_tab() if (!$loaded);
 9040: 
 9041: 	my %seen;
 9042: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 9043: 	return @uniq;
 9044:     }
 9045: }
 9046: 
 9047: { 
 9048:     my %iphost;
 9049:     my %name_to_ip;
 9050:     my %lonid_to_ip;
 9051: 
 9052:     sub get_hosts_from_ip {
 9053: 	my ($ip) = @_;
 9054: 	my %iphosts = &get_iphost();
 9055: 	if (ref($iphosts{$ip})) {
 9056: 	    return @{$iphosts{$ip}};
 9057: 	}
 9058: 	return;
 9059:     }
 9060:     
 9061:     sub reset_hosts_ip_info {
 9062: 	undef(%iphost);
 9063: 	undef(%name_to_ip);
 9064: 	undef(%lonid_to_ip);
 9065:     }
 9066: 
 9067:     sub get_host_ip {
 9068: 	my ($lonid) = @_;
 9069: 	if (exists($lonid_to_ip{$lonid})) {
 9070: 	    return $lonid_to_ip{$lonid};
 9071: 	}
 9072: 	my $name=&hostname($lonid);
 9073:    	my $ip = gethostbyname($name);
 9074: 	return if (!$ip || length($ip) ne 4);
 9075: 	$ip=inet_ntoa($ip);
 9076: 	$name_to_ip{$name}   = $ip;
 9077: 	$lonid_to_ip{$lonid} = $ip;
 9078: 	return $ip;
 9079:     }
 9080:     
 9081:     sub get_iphost {
 9082: 	my ($ignore_cache) = @_;
 9083: 
 9084: 	if (!$ignore_cache) {
 9085: 	    if (%iphost) {
 9086: 		return %iphost;
 9087: 	    }
 9088: 	    my ($ip_info,$cached)=
 9089: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 9090: 	    if ($cached) {
 9091: 		%iphost      = %{$ip_info->[0]};
 9092: 		%name_to_ip  = %{$ip_info->[1]};
 9093: 		%lonid_to_ip = %{$ip_info->[2]};
 9094: 		return %iphost;
 9095: 	    }
 9096: 	}
 9097: 
 9098: 	# get yesterday's info for fallback
 9099: 	my %old_name_to_ip;
 9100: 	my ($ip_info,$cached)=
 9101: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 9102: 	if ($cached) {
 9103: 	    %old_name_to_ip = %{$ip_info->[1]};
 9104: 	}
 9105: 
 9106: 	my %name_to_host = &all_names();
 9107: 	foreach my $name (keys(%name_to_host)) {
 9108: 	    my $ip;
 9109: 	    if (!exists($name_to_ip{$name})) {
 9110: 		$ip = gethostbyname($name);
 9111: 		if (!$ip || length($ip) ne 4) {
 9112: 		    if (defined($old_name_to_ip{$name})) {
 9113: 			$ip = $old_name_to_ip{$name};
 9114: 			&logthis("Can't find $name defaulting to old $ip");
 9115: 		    } else {
 9116: 			&logthis("Name $name no IP found");
 9117: 			next;
 9118: 		    }
 9119: 		} else {
 9120: 		    $ip=inet_ntoa($ip);
 9121: 		}
 9122: 		$name_to_ip{$name} = $ip;
 9123: 	    } else {
 9124: 		$ip = $name_to_ip{$name};
 9125: 	    }
 9126: 	    foreach my $id (@{ $name_to_host{$name} }) {
 9127: 		$lonid_to_ip{$id} = $ip;
 9128: 	    }
 9129: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 9130: 	}
 9131: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 9132: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 9133: 				      48*60*60);
 9134: 
 9135: 	return %iphost;
 9136:     }
 9137: 
 9138:     #
 9139:     #  Given a DNS returns the loncapa host name for that DNS 
 9140:     # 
 9141:     sub host_from_dns {
 9142:         my ($dns) = @_;
 9143:         my @hosts;
 9144:         my $ip;
 9145: 
 9146:         if (exists($name_to_ip{$dns})) {
 9147:             $ip = $name_to_ip{$dns};
 9148:         }
 9149:         if (!$ip) {
 9150:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
 9151:             if (length($ip) == 4) { 
 9152: 	        $ip   = &IO::Socket::inet_ntoa($ip);
 9153:             }
 9154:         }
 9155:         if ($ip) {
 9156: 	    @hosts = get_hosts_from_ip($ip);
 9157: 	    return $hosts[0];
 9158:         }
 9159:         return undef;
 9160:     }
 9161: 
 9162: }
 9163: 
 9164: BEGIN {
 9165: 
 9166: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 9167:     unless ($readit) {
 9168: {
 9169:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 9170:     %perlvar = (%perlvar,%{$configvars});
 9171: }
 9172: 
 9173: 
 9174: # ------------------------------------------------------ Read spare server file
 9175: {
 9176:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 9177: 
 9178:     while (my $configline=<$config>) {
 9179:        chomp($configline);
 9180:        if ($configline) {
 9181: 	   my ($host,$type) = split(':',$configline,2);
 9182: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 9183: 	   push(@{ $spareid{$type} }, $host);
 9184:        }
 9185:     }
 9186:     close($config);
 9187: }
 9188: # ------------------------------------------------------------ Read permissions
 9189: {
 9190:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 9191: 
 9192:     while (my $configline=<$config>) {
 9193: 	chomp($configline);
 9194: 	if ($configline) {
 9195: 	    my ($role,$perm)=split(/ /,$configline);
 9196: 	    if ($perm ne '') { $pr{$role}=$perm; }
 9197: 	}
 9198:     }
 9199:     close($config);
 9200: }
 9201: 
 9202: # -------------------------------------------- Read plain texts for permissions
 9203: {
 9204:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 9205: 
 9206:     while (my $configline=<$config>) {
 9207: 	chomp($configline);
 9208: 	if ($configline) {
 9209: 	    my ($short,@plain)=split(/:/,$configline);
 9210:             %{$prp{$short}} = ();
 9211: 	    if (@plain > 0) {
 9212:                 $prp{$short}{'std'} = $plain[0];
 9213:                 for (my $i=1; $i<@plain; $i++) {
 9214:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 9215:                 }
 9216:             }
 9217: 	}
 9218:     }
 9219:     close($config);
 9220: }
 9221: 
 9222: # ---------------------------------------------------------- Read package table
 9223: {
 9224:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 9225: 
 9226:     while (my $configline=<$config>) {
 9227: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 9228: 	chomp($configline);
 9229: 	my ($short,$plain)=split(/:/,$configline);
 9230: 	my ($pack,$name)=split(/\&/,$short);
 9231: 	if ($plain ne '') {
 9232: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 9233: 	    $packagetab{$short}=$plain; 
 9234: 	}
 9235:     }
 9236:     close($config);
 9237: }
 9238: 
 9239: # ------------- set up temporary directory
 9240: {
 9241:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 9242: 
 9243: }
 9244: 
 9245: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 9246: 				'compress_threshold'=> 20_000,
 9247:  			        });
 9248: 
 9249: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 9250: $dumpcount=0;
 9251: $locknum=0;
 9252: 
 9253: &logtouch();
 9254: &logthis('<font color="yellow">INFO: Read configuration</font>');
 9255: $readit=1;
 9256:     {
 9257: 	use integer;
 9258: 	my $test=(2**32)+1;
 9259: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 9260: 	&logthis(" Detected 64bit platform ($_64bit)");
 9261:     }
 9262: }
 9263: }
 9264: 
 9265: 1;
 9266: __END__
 9267: 
 9268: =pod
 9269: 
 9270: =head1 NAME
 9271: 
 9272: Apache::lonnet - Subroutines to ask questions about things in the network.
 9273: 
 9274: =head1 SYNOPSIS
 9275: 
 9276: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 9277: 
 9278:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 9279: 
 9280: Common parameters:
 9281: 
 9282: =over 4
 9283: 
 9284: =item *
 9285: 
 9286: $uname : an internal username (if $cname expecting a course Id specifically)
 9287: 
 9288: =item *
 9289: 
 9290: $udom : a domain (if $cdom expecting a course's domain specifically)
 9291: 
 9292: =item *
 9293: 
 9294: $symb : a resource instance identifier
 9295: 
 9296: =item *
 9297: 
 9298: $namespace : the name of a .db file that contains the data needed or
 9299: being set.
 9300: 
 9301: =back
 9302: 
 9303: =head1 OVERVIEW
 9304: 
 9305: lonnet provides subroutines which interact with the
 9306: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 9307: about classes, users, and resources.
 9308: 
 9309: For many of these objects you can also use this to store data about
 9310: them or modify them in various ways.
 9311: 
 9312: =head2 Symbs
 9313: 
 9314: To identify a specific instance of a resource, LON-CAPA uses symbols
 9315: or "symbs"X<symb>. These identifiers are built from the URL of the
 9316: map, the resource number of the resource in the map, and the URL of
 9317: the resource itself. The latter is somewhat redundant, but might help
 9318: if maps change.
 9319: 
 9320: An example is
 9321: 
 9322:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 9323: 
 9324: The respective map entry is
 9325: 
 9326:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 9327:   title="Problem 2">
 9328:  </resource>
 9329: 
 9330: Symbs are used by the random number generator, as well as to store and
 9331: restore data specific to a certain instance of for example a problem.
 9332: 
 9333: =head2 Storing And Retrieving Data
 9334: 
 9335: X<store()>X<cstore()>X<restore()>Three of the most important functions
 9336: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 9337: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 9338: is is the non-critical message twin of cstore. These functions are for
 9339: handlers to store a perl hash to a user's permanent data space in an
 9340: easy manner, and to retrieve it again on another call. It is expected
 9341: that a handler would use this once at the beginning to retrieve data,
 9342: and then again once at the end to send only the new data back.
 9343: 
 9344: The data is stored in the user's data directory on the user's
 9345: homeserver under the ID of the course.
 9346: 
 9347: The hash that is returned by restore will have all of the previous
 9348: value for all of the elements of the hash.
 9349: 
 9350: Example:
 9351: 
 9352:  #creating a hash
 9353:  my %hash;
 9354:  $hash{'foo'}='bar';
 9355: 
 9356:  #storing it
 9357:  &Apache::lonnet::cstore(\%hash);
 9358: 
 9359:  #changing a value
 9360:  $hash{'foo'}='notbar';
 9361: 
 9362:  #adding a new value
 9363:  $hash{'bar'}='foo';
 9364:  &Apache::lonnet::cstore(\%hash);
 9365: 
 9366:  #retrieving the hash
 9367:  my %history=&Apache::lonnet::restore();
 9368: 
 9369:  #print the hash
 9370:  foreach my $key (sort(keys(%history))) {
 9371:    print("\%history{$key} = $history{$key}");
 9372:  }
 9373: 
 9374: Will print out:
 9375: 
 9376:  %history{1:foo} = bar
 9377:  %history{1:keys} = foo:timestamp
 9378:  %history{1:timestamp} = 990455579
 9379:  %history{2:bar} = foo
 9380:  %history{2:foo} = notbar
 9381:  %history{2:keys} = foo:bar:timestamp
 9382:  %history{2:timestamp} = 990455580
 9383:  %history{bar} = foo
 9384:  %history{foo} = notbar
 9385:  %history{timestamp} = 990455580
 9386:  %history{version} = 2
 9387: 
 9388: Note that the special hash entries C<keys>, C<version> and
 9389: C<timestamp> were added to the hash. C<version> will be equal to the
 9390: total number of versions of the data that have been stored. The
 9391: C<timestamp> attribute will be the UNIX time the hash was
 9392: stored. C<keys> is available in every historical section to list which
 9393: keys were added or changed at a specific historical revision of a
 9394: hash.
 9395: 
 9396: B<Warning>: do not store the hash that restore returns directly. This
 9397: will cause a mess since it will restore the historical keys as if the
 9398: were new keys. I.E. 1:foo will become 1:1:foo etc.
 9399: 
 9400: Calling convention:
 9401: 
 9402:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 9403:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 9404: 
 9405: For more detailed information, see lonnet specific documentation.
 9406: 
 9407: =head1 RETURN MESSAGES
 9408: 
 9409: =over 4
 9410: 
 9411: =item * B<con_lost>: unable to contact remote host
 9412: 
 9413: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 9414: when the connection is brought back up
 9415: 
 9416: =item * B<con_failed>: unable to contact remote host and unable to save message
 9417: for later delivery
 9418: 
 9419: =item * B<error:>: an error a occurred, a description of the error follows the :
 9420: 
 9421: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 9422: that was requested
 9423: 
 9424: =back
 9425: 
 9426: =head1 PUBLIC SUBROUTINES
 9427: 
 9428: =head2 Session Environment Functions
 9429: 
 9430: =over 4
 9431: 
 9432: =item * 
 9433: X<appenv()>
 9434: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
 9435: the user envirnoment file, and will be restored for each access this
 9436: user makes during this session, also modifies the %env for the current
 9437: process. Optional rolesarrayref - if defined contains a reference to an array
 9438: of roles which are exempt from the restriction on modifying user.role entries 
 9439: in the user's environment.db and in %env.    
 9440: 
 9441: =item *
 9442: X<delenv()>
 9443: B<delenv($delthis,$regexp)>: removes all items from the session
 9444: environment file that begin with $delthis. If the 
 9445: optional second arg - $regexp - is true, $delthis is treated as a 
 9446: regular expression, otherwise \Q$delthis\E is used. 
 9447: The values are also deleted from the current processes %env.
 9448: 
 9449: =item * get_env_multiple($name) 
 9450: 
 9451: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9452: values may be defined and end up as an array ref.
 9453: 
 9454: returns an array of values
 9455: 
 9456: =back
 9457: 
 9458: =head2 User Information
 9459: 
 9460: =over 4
 9461: 
 9462: =item *
 9463: X<queryauthenticate()>
 9464: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 9465: authentication scheme
 9466: 
 9467: =item *
 9468: X<authenticate()>
 9469: B<authenticate($uname,$upass,$udom)>: try to
 9470: authenticate user from domain's lib servers (first use the current
 9471: one). C<$upass> should be the users password.
 9472: 
 9473: =item *
 9474: X<homeserver()>
 9475: B<homeserver($uname,$udom)>: find the server which has
 9476: the user's directory and files (there must be only one), this caches
 9477: the answer, and also caches if there is a borken connection.
 9478: 
 9479: =item *
 9480: X<idget()>
 9481: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 9482: (IDs are a unique resource in a domain, there must be only 1 ID per
 9483: username, and only 1 username per ID in a specific domain) (returns
 9484: hash: id=>name,id=>name)
 9485: 
 9486: =item *
 9487: X<idrget()>
 9488: B<idrget($udom,@unames)>: find the IDs behind a list of
 9489: usernames (returns hash: name=>id,name=>id)
 9490: 
 9491: =item *
 9492: X<idput()>
 9493: B<idput($udom,%ids)>: store away a list of names and associated IDs
 9494: 
 9495: =item *
 9496: X<rolesinit()>
 9497: B<rolesinit($udom,$username,$authhost)>: get user privileges
 9498: 
 9499: =item *
 9500: X<getsection()>
 9501: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 9502: course $cname, return section name/number or '' for "not in course"
 9503: and '-1' for "no section"
 9504: 
 9505: =item *
 9506: X<userenvironment()>
 9507: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 9508: passed in @what from the requested user's environment, returns a hash
 9509: 
 9510: =item * 
 9511: X<userlog_query()>
 9512: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 9513: activity.log file. %filters defines filters applied when parsing the
 9514: log file. These can be start or end timestamps, or the type of action
 9515: - log to look for Login or Logout events, check for Checkin or
 9516: Checkout, role for role selection. The response is in the form
 9517: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 9518: escaped strings of the action recorded in the activity.log file.
 9519: 
 9520: =back
 9521: 
 9522: =head2 User Roles
 9523: 
 9524: =over 4
 9525: 
 9526: =item *
 9527: 
 9528: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 9529:  F: full access
 9530:  U,I,K: authentication modes (cxx only)
 9531:  '': forbidden
 9532:  1: user needs to choose course
 9533:  2: browse allowed
 9534:  A: passphrase authentication needed
 9535: 
 9536: =item *
 9537: 
 9538: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 9539: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 9540: and course level
 9541: 
 9542: =item *
 9543: 
 9544: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
 9545: (rolesplain.tab); plain text explanation of a user role term.
 9546: $type is Course (default) or Group.
 9547: If $forcedefault evaluates to true, text returned will be default 
 9548: text for $type. Otherwise, if this is a course, the text returned 
 9549: will be a custom name for the role (if defined in the course's 
 9550: environment).  If no custom name is defined the default is returned.
 9551:    
 9552: =item *
 9553: 
 9554: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
 9555: All arguments are optional. Returns a hash of a roles, either for
 9556: co-author/assistant author roles for a user's Construction Space
 9557: (default), or if $context is 'userroles', roles for the user himself,
 9558: In the hash, keys are set to colon-separated $uname,$udom,$role, and
 9559: (optionally) if $withsec is true, a fourth colon-separated item - $section.
 9560: For each key, value is set to colon-separated start and end times for
 9561: the role.  If no username and domain are specified, will default to
 9562: current user/domain. Types, roles, and roledoms are references to arrays
 9563: of role statuses (active, future or previous), roles 
 9564: (e.g., cc,in, st etc.) and domains of the roles which can be used
 9565: to restrict the list of roles reported. If no array ref is 
 9566: provided for types, will default to return only active roles.
 9567: 
 9568: =back
 9569: 
 9570: =head2 User Modification
 9571: 
 9572: =over 4
 9573: 
 9574: =item *
 9575: 
 9576: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
 9577: user for the level given by URL.  Optional start and end dates (leave empty
 9578: string or zero for "no date")
 9579: 
 9580: =item *
 9581: 
 9582: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 9583: change a users, password, possible return values are: ok,
 9584: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 9585: refused
 9586: 
 9587: =item *
 9588: 
 9589: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 9590: 
 9591: =item *
 9592: 
 9593: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
 9594:            $forceid,$desiredhome,$email,$inststatus) : 
 9595: modify user
 9596: 
 9597: =item *
 9598: 
 9599: modifystudent
 9600: 
 9601: modify a student's enrollment and identification information.
 9602: The course id is resolved based on the current users environment.  
 9603: This means the envoking user must be a course coordinator or otherwise
 9604: associated with a course.
 9605: 
 9606: This call is essentially a wrapper for lonnet::modifyuser and
 9607: lonnet::modify_student_enrollment
 9608: 
 9609: Inputs: 
 9610: 
 9611: =over 4
 9612: 
 9613: =item B<$udom> Student's loncapa domain
 9614: 
 9615: =item B<$uname> Student's loncapa login name
 9616: 
 9617: =item B<$uid> Student/Employee ID
 9618: 
 9619: =item B<$umode> Student's authentication mode
 9620: 
 9621: =item B<$upass> Student's password
 9622: 
 9623: =item B<$first> Student's first name
 9624: 
 9625: =item B<$middle> Student's middle name
 9626: 
 9627: =item B<$last> Student's last name
 9628: 
 9629: =item B<$gene> Student's generation
 9630: 
 9631: =item B<$usec> Student's section in course
 9632: 
 9633: =item B<$end> Unix time of the roles expiration
 9634: 
 9635: =item B<$start> Unix time of the roles start date
 9636: 
 9637: =item B<$forceid> If defined, allow $uid to be changed
 9638: 
 9639: =item B<$desiredhome> server to use as home server for student
 9640: 
 9641: =item B<$email> Student's permanent e-mail address
 9642: 
 9643: =item B<$type> Type of enrollment (auto or manual)
 9644: 
 9645: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
 9646: 
 9647: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
 9648: 
 9649: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
 9650: 
 9651: =item B<$context> role change context (shown in User Management Logs display in a course)
 9652: 
 9653: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
 9654: 
 9655: =back
 9656: 
 9657: =item *
 9658: 
 9659: modify_student_enrollment
 9660: 
 9661: Change a students enrollment status in a class.  The environment variable
 9662: 'role.request.course' must be defined for this function to proceed.
 9663: 
 9664: Inputs:
 9665: 
 9666: =over 4
 9667: 
 9668: =item $udom, students domain
 9669: 
 9670: =item $uname, students name
 9671: 
 9672: =item $uid, students user id
 9673: 
 9674: =item $first, students first name
 9675: 
 9676: =item $middle
 9677: 
 9678: =item $last
 9679: 
 9680: =item $gene
 9681: 
 9682: =item $usec
 9683: 
 9684: =item $end
 9685: 
 9686: =item $start
 9687: 
 9688: =item $type
 9689: 
 9690: =item $locktype
 9691: 
 9692: =item $cid
 9693: 
 9694: =item $selfenroll
 9695: 
 9696: =item $context
 9697: 
 9698: =back
 9699: 
 9700: 
 9701: =item *
 9702: 
 9703: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 9704: custom role; give a custom role to a user for the level given by URL.  Specify
 9705: name and domain of role author, and role name
 9706: 
 9707: =item *
 9708: 
 9709: revokerole($udom,$uname,$url,$role) : revoke a role for url
 9710: 
 9711: =item *
 9712: 
 9713: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 9714: 
 9715: =back
 9716: 
 9717: =head2 Course Infomation
 9718: 
 9719: =over 4
 9720: 
 9721: =item *
 9722: 
 9723: coursedescription($courseid) : returns a hash of information about the
 9724: specified course id, including all environment settings for the
 9725: course, the description of the course will be in the hash under the
 9726: key 'description'
 9727: 
 9728: =item *
 9729: 
 9730: resdata($name,$domain,$type,@which) : request for current parameter
 9731: setting for a specific $type, where $type is either 'course' or 'user',
 9732: @what should be a list of parameters to ask about. This routine caches
 9733: answers for 5 minutes.
 9734: 
 9735: =item *
 9736: 
 9737: get_courseresdata($courseid, $domain) : dump the entire course resource
 9738: data base, returning a hash that is keyed by the resource name and has
 9739: values that are the resource value.  I believe that the timestamps and
 9740: versions are also returned.
 9741: 
 9742: 
 9743: =back
 9744: 
 9745: =head2 Course Modification
 9746: 
 9747: =over 4
 9748: 
 9749: =item *
 9750: 
 9751: writecoursepref($courseid,%prefs) : write preferences (environment
 9752: database) for a course
 9753: 
 9754: =item *
 9755: 
 9756: createcourse($udom,$description,$url) : make/modify course
 9757: 
 9758: =back
 9759: 
 9760: =head2 Resource Subroutines
 9761: 
 9762: =over 4
 9763: 
 9764: =item *
 9765: 
 9766: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 9767: 
 9768: =item *
 9769: 
 9770: repcopy($filename) : subscribes to the requested file, and attempts to
 9771: replicate from the owning library server, Might return
 9772: 'unavailable', 'not_found', 'forbidden', 'ok', or
 9773: 'bad_request', also attempts to grab the metadata for the
 9774: resource. Expects the local filesystem pathname
 9775: (/home/httpd/html/res/....)
 9776: 
 9777: =back
 9778: 
 9779: =head2 Resource Information
 9780: 
 9781: =over 4
 9782: 
 9783: =item *
 9784: 
 9785: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 9786: a vairety of different possible values, $varname should be a request
 9787: string, and the other parameters can be used to specify who and what
 9788: one is asking about.
 9789: 
 9790: Possible values for $varname are environment.lastname (or other item
 9791: from the envirnment hash), user.name (or someother aspect about the
 9792: user), resource.0.maxtries (or some other part and parameter of a
 9793: resource)
 9794: 
 9795: =item *
 9796: 
 9797: directcondval($number) : get current value of a condition; reads from a state
 9798: string
 9799: 
 9800: =item *
 9801: 
 9802: condval($condidx) : value of condition index based on state
 9803: 
 9804: =item *
 9805: 
 9806: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 9807: resource's metadata, $what should be either a specific key, or either
 9808: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 9809: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 9810: 
 9811: this function automatically caches all requests
 9812: 
 9813: =item *
 9814: 
 9815: metadata_query($query,$custom,$customshow) : make a metadata query against the
 9816: network of library servers; returns file handle of where SQL and regex results
 9817: will be stored for query
 9818: 
 9819: =item *
 9820: 
 9821: symbread($filename) : return symbolic list entry (filename argument optional);
 9822: returns the data handle
 9823: 
 9824: =item *
 9825: 
 9826: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 9827: a possible symb for the URL in $thisfn, and if is an encryypted
 9828: resource that the user accessed using /enc/ returns a 1 on success, 0
 9829: on failure, user must be in a course, as it assumes the existance of
 9830: the course initial hash, and uses $env('request.course.id'}
 9831: 
 9832: 
 9833: =item *
 9834: 
 9835: symbclean($symb) : removes versions numbers from a symb, returns the
 9836: cleaned symb
 9837: 
 9838: =item *
 9839: 
 9840: is_on_map($uri) : checks if the $uri is somewhere on the current
 9841: course map, user must be in a course for it to work.
 9842: 
 9843: =item *
 9844: 
 9845: numval($salt) : return random seed value (addend for rndseed)
 9846: 
 9847: =item *
 9848: 
 9849: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 9850: a random seed, all arguments are optional, if they aren't sent it uses the
 9851: environment to derive them. Note: if symb isn't sent and it can't get one
 9852: from &symbread it will use the current time as its return value
 9853: 
 9854: =item *
 9855: 
 9856: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 9857: unfakeable, receipt
 9858: 
 9859: =item *
 9860: 
 9861: receipt() : API to ireceipt working off of env values; given out to users
 9862: 
 9863: =item *
 9864: 
 9865: countacc($url) : count the number of accesses to a given URL
 9866: 
 9867: =item *
 9868: 
 9869: 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
 9870: 
 9871: =item *
 9872: 
 9873: 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)
 9874: 
 9875: =item *
 9876: 
 9877: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 9878: 
 9879: =item *
 9880: 
 9881: devalidate($symb) : devalidate temporary spreadsheet calculations,
 9882: forcing spreadsheet to reevaluate the resource scores next time.
 9883: 
 9884: =back
 9885: 
 9886: =head2 Storing/Retreiving Data
 9887: 
 9888: =over 4
 9889: 
 9890: =item *
 9891: 
 9892: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 9893: for this url; hashref needs to be given and should be a \%hashname; the
 9894: remaining args aren't required and if they aren't passed or are '' they will
 9895: be derived from the env
 9896: 
 9897: =item *
 9898: 
 9899: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 9900: uses critical subroutine
 9901: 
 9902: =item *
 9903: 
 9904: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 9905: all args are optional
 9906: 
 9907: =item *
 9908: 
 9909: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 9910: dumps the complete (or key matching regexp) namespace into a hash
 9911: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 9912: normally &store()ed into
 9913: 
 9914: $range should be either an integer '100' (give me the first 100
 9915:                                            matching records)
 9916:               or be  two integers sperated by a - with no spaces
 9917:                  '30-50' (give me the 30th through the 50th matching
 9918:                           records)
 9919: 
 9920: 
 9921: =item *
 9922: 
 9923: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 9924: replaces a &store() version of data with a replacement set of data
 9925: for a particular resource in a namespace passed in the $storehash hash 
 9926: reference
 9927: 
 9928: =item *
 9929: 
 9930: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 9931: works very similar to store/cstore, but all data is stored in a
 9932: temporary location and can be reset using tmpreset, $storehash should
 9933: be a hash reference, returns nothing on success
 9934: 
 9935: =item *
 9936: 
 9937: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 9938: similar to restore, but all data is stored in a temporary location and
 9939: can be reset using tmpreset. Returns a hash of values on success,
 9940: error string otherwise.
 9941: 
 9942: =item *
 9943: 
 9944: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 9945: deltes all keys for $symb form the temporary storage hash.
 9946: 
 9947: =item *
 9948: 
 9949: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9950: reference filled in from namesp ($udom and $uname are optional)
 9951: 
 9952: =item *
 9953: 
 9954: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 9955: namesp ($udom and $uname are optional)
 9956: 
 9957: =item *
 9958: 
 9959: dump($namespace,$udom,$uname,$regexp,$range) : 
 9960: dumps the complete (or key matching regexp) namespace into a hash
 9961: ($udom, $uname, $regexp, $range are optional)
 9962: 
 9963: $range should be either an integer '100' (give me the first 100
 9964:                                            matching records)
 9965:               or be  two integers sperated by a - with no spaces
 9966:                  '30-50' (give me the 30th through the 50th matching
 9967:                           records)
 9968: =item *
 9969: 
 9970: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 9971: $store can be a scalar, an array reference, or if the amount to be 
 9972: incremented is > 1, a hash reference.
 9973: 
 9974: ($udom and $uname are optional)
 9975: 
 9976: =item *
 9977: 
 9978: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 9979: ($udom and $uname are optional)
 9980: 
 9981: =item *
 9982: 
 9983: cput($namespace,$storehash,$udom,$uname) : critical put
 9984: ($udom and $uname are optional)
 9985: 
 9986: =item *
 9987: 
 9988: newput($namespace,$storehash,$udom,$uname) :
 9989: 
 9990: Attempts to store the items in the $storehash, but only if they don't
 9991: currently exist, if this succeeds you can be certain that you have 
 9992: successfully created a new key value pair in the $namespace db.
 9993: 
 9994: 
 9995: Args:
 9996:  $namespace: name of database to store values to
 9997:  $storehash: hashref to store to the db
 9998:  $udom: (optional) domain of user containing the db
 9999:  $uname: (optional) name of user caontaining the db
10000: 
10001: Returns:
10002:  'ok' -> succeeded in storing all keys of $storehash
10003:  'key_exists: <key>' -> failed to anything out of $storehash, as at
10004:                         least <key> already existed in the db (other
10005:                         requested keys may also already exist)
10006:  'error: <msg>' -> unable to tie the DB or other error occurred
10007:  'con_lost' -> unable to contact request server
10008:  'refused' -> action was not allowed by remote machine
10009: 
10010: 
10011: =item *
10012: 
10013: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10014: reference filled in from namesp (encrypts the return communication)
10015: ($udom and $uname are optional)
10016: 
10017: =item *
10018: 
10019: log($udom,$name,$home,$message) : write to permanent log for user; use
10020: critical subroutine
10021: 
10022: =item *
10023: 
10024: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
10025: array reference filled in from namespace found in domain level on either
10026: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
10027: 
10028: =item *
10029: 
10030: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
10031: domain level either on specified domain server ($uhome) or primary domain 
10032: server ($udom and $uhome are optional)
10033: 
10034: =item * 
10035: 
10036: get_domain_defaults($target_domain) : returns hash with defaults for
10037: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
10038: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
10039: or localauth), initial password or a kerberos realm, language (e.g., en-us).
10040: Values are retrieved from cache (if current), or from domain's configuration.db
10041: (if available), or lastly from values in lonTabs/dns_domain,tab, 
10042: or lonTabs/domain.tab. 
10043: 
10044: %domdefaults = &get_auth_defaults($target_domain);
10045: 
10046: =back
10047: 
10048: =head2 Network Status Functions
10049: 
10050: =over 4
10051: 
10052: =item *
10053: 
10054: dirlist($uri) : return directory list based on URI
10055: 
10056: =item *
10057: 
10058: spareserver() : find server with least workload from spare.tab
10059: 
10060: 
10061: =item *
10062: 
10063: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
10064: if there is no corresponding loncapa host.
10065: 
10066: =back
10067: 
10068: 
10069: =head2 Apache Request
10070: 
10071: =over 4
10072: 
10073: =item *
10074: 
10075: ssi($url,%hash) : server side include, does a complete request cycle on url to
10076: localhost, posts hash
10077: 
10078: =back
10079: 
10080: =head2 Data to String to Data
10081: 
10082: =over 4
10083: 
10084: =item *
10085: 
10086: hash2str(%hash) : convert a hash into a string complete with escaping and '='
10087: and '&' separators, supports elements that are arrayrefs and hashrefs
10088: 
10089: =item *
10090: 
10091: hashref2str($hashref) : convert a hashref into a string complete with
10092: escaping and '=' and '&' separators, supports elements that are
10093: arrayrefs and hashrefs
10094: 
10095: =item *
10096: 
10097: arrayref2str($arrayref) : convert an arrayref into a string complete
10098: with escaping and '&' separators, supports elements that are arrayrefs
10099: and hashrefs
10100: 
10101: =item *
10102: 
10103: str2hash($string) : convert string to hash using unescaping and
10104: splitting on '=' and '&', supports elements that are arrayrefs and
10105: hashrefs
10106: 
10107: =item *
10108: 
10109: str2array($string) : convert string to hash using unescaping and
10110: splitting on '&', supports elements that are arrayrefs and hashrefs
10111: 
10112: =back
10113: 
10114: =head2 Logging Routines
10115: 
10116: =over 4
10117: 
10118: These routines allow one to make log messages in the lonnet.log and
10119: lonnet.perm logfiles.
10120: 
10121: =item *
10122: 
10123: logtouch() : make sure the logfile, lonnet.log, exists
10124: 
10125: =item *
10126: 
10127: logthis() : append message to the normal lonnet.log file, it gets
10128: preiodically rolled over and deleted.
10129: 
10130: =item *
10131: 
10132: logperm() : append a permanent message to lonnet.perm.log, this log
10133: file never gets deleted by any automated portion of the system, only
10134: messages of critical importance should go in here.
10135: 
10136: =back
10137: 
10138: =head2 General File Helper Routines
10139: 
10140: =over 4
10141: 
10142: =item *
10143: 
10144: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10145: (a) files in /uploaded
10146:   (i) If a local copy of the file exists - 
10147:       compares modification date of local copy with last-modified date for 
10148:       definitive version stored on home server for course. If local copy is 
10149:       stale, requests a new version from the home server and stores it. 
10150:       If the original has been removed from the home server, then local copy 
10151:       is unlinked.
10152:   (ii) If local copy does not exist -
10153:       requests the file from the home server and stores it. 
10154:   
10155:   If $caller is 'uploadrep':  
10156:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10157:     for request for files originally uploaded via DOCS. 
10158:      - returns 'ok' if fresh local copy now available, -1 otherwise.
10159:   
10160:   Otherwise:
10161:      This indicates a call from the content generation phase of the request.
10162:      -  returns the entire contents of the file or -1.
10163:      
10164: (b) files in /res
10165:    - returns the entire contents of a file or -1; 
10166:    it properly subscribes to and replicates the file if neccessary.
10167: 
10168: 
10169: =item *
10170: 
10171: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10172:                   reference
10173: 
10174: returns either a stat() list of data about the file or an empty list
10175: if the file doesn't exist or couldn't find out about it (connection
10176: problems or user unknown)
10177: 
10178: =item *
10179: 
10180: filelocation($dir,$file) : returns file system location of a file
10181: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10182: directory that relative $file lookups are to looked in ($dir of /a/dir
10183: and a file of ../bob will become /a/bob)
10184: 
10185: =item *
10186: 
10187: hreflocation($dir,$file) : returns file system location or a URL; same as
10188: filelocation except for hrefs
10189: 
10190: =item *
10191: 
10192: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10193: 
10194: =back
10195: 
10196: =head2 Usererfile file routines (/uploaded*)
10197: 
10198: =over 4
10199: 
10200: =item *
10201: 
10202: userfileupload(): main rotine for putting a file in a user or course's
10203:                   filespace, arguments are,
10204: 
10205:  formname - required - this is the name of the element in $env where the
10206:            filename, and the contents of the file to create/modifed exist
10207:            the filename is in $env{'form.'.$formname.'.filename'} and the
10208:            contents of the file is located in $env{'form.'.$formname}
10209:  coursedoc - if true, store the file in the course of the active role
10210:              of the current user
10211:  subdir - required - subdirectory to put the file in under ../userfiles/
10212:          if undefined, it will be placed in "unknown"
10213: 
10214:  (This routine calls clean_filename() to remove any dangerous
10215:  characters from the filename, and then calls finuserfileupload() to
10216:  complete the transaction)
10217: 
10218:  returns either the url of the uploaded file (/uploaded/....) if successful
10219:  and /adm/notfound.html if unsuccessful
10220: 
10221: =item *
10222: 
10223: clean_filename(): routine for cleaing a filename up for storage in
10224:                  userfile space, argument is:
10225: 
10226:  filename - proposed filename
10227: 
10228: returns: the new clean filename
10229: 
10230: =item *
10231: 
10232: finishuserfileupload(): routine that creaes and sends the file to
10233: userspace, probably shouldn't be called directly
10234: 
10235:   docuname: username or courseid of destination for the file
10236:   docudom: domain of user/course of destination for the file
10237:   formname: same as for userfileupload()
10238:   fname: filename (inculding subdirectories) for the file
10239: 
10240:  returns either the url of the uploaded file (/uploaded/....) if successful
10241:  and /adm/notfound.html if unsuccessful
10242: 
10243: =item *
10244: 
10245: renameuserfile(): renames an existing userfile to a new name
10246: 
10247:   Args:
10248:    docuname: username or courseid of destination for the file
10249:    docudom: domain of user/course of destination for the file
10250:    old: current file name (including any subdirs under userfiles)
10251:    new: desired file name (including any subdirs under userfiles)
10252: 
10253: =item *
10254: 
10255: mkdiruserfile(): creates a directory is a userfiles dir
10256: 
10257:   Args:
10258:    docuname: username or courseid of destination for the file
10259:    docudom: domain of user/course of destination for the file
10260:    dir: dir to create (including any subdirs under userfiles)
10261: 
10262: =item *
10263: 
10264: removeuserfile(): removes a file that exists in userfiles
10265: 
10266:   Args:
10267:    docuname: username or courseid of destination for the file
10268:    docudom: domain of user/course of destination for the file
10269:    fname: filname to delete (including any subdirs under userfiles)
10270: 
10271: =item *
10272: 
10273: removeuploadedurl(): convience function for removeuserfile()
10274: 
10275:   Args:
10276:    url:  a full /uploaded/... url to delete
10277: 
10278: =item * 
10279: 
10280: get_portfile_permissions():
10281:   Args:
10282:     domain: domain of user or course contain the portfolio files
10283:     user: name of user or num of course contain the portfolio files
10284:   Returns:
10285:     hashref of a dump of the proper file_permissions.db
10286:    
10287: 
10288: =item * 
10289: 
10290: get_access_controls():
10291: 
10292: Args:
10293:   current_permissions: the hash ref returned from get_portfile_permissions()
10294:   group: (optional) the group you want the files associated with
10295:   file: (optional) the file you want access info on
10296: 
10297: Returns:
10298:     a hash (keys are file names) of hashes containing
10299:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10300:         values are XML containing access control settings (see below) 
10301: 
10302: Internal notes:
10303: 
10304:  access controls are stored in file_permissions.db as key=value pairs.
10305:     key -> path to file/file_name\0uniqueID:scope_end_start
10306:         where scope -> public,guest,course,group,domains or users.
10307:               end -> UNIX time for end of access (0 -> no end date)
10308:               start -> UNIX time for start of access
10309: 
10310:     value -> XML description of access control
10311:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10312:             <start></start>
10313:             <end></end>
10314: 
10315:             <password></password>  for scope type = guest
10316: 
10317:             <domain></domain>     for scope type = course or group
10318:             <number></number>
10319:             <roles id="">
10320:              <role></role>
10321:              <access></access>
10322:              <section></section>
10323:              <group></group>
10324:             </roles>
10325: 
10326:             <dom></dom>         for scope type = domains
10327: 
10328:             <users>             for scope type = users
10329:              <user>
10330:               <uname></uname>
10331:               <udom></udom>
10332:              </user>
10333:             </users>
10334:            </scope> 
10335:               
10336:  Access data is also aggregated for each file in an additional key=value pair:
10337:  key -> path to file/file_name\0accesscontrol 
10338:  value -> reference to hash
10339:           hash contains key = value pairs
10340:           where key = uniqueID:scope_end_start
10341:                 value = UNIX time record was last updated
10342: 
10343:           Used to improve speed of look-ups of access controls for each file.  
10344:  
10345:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10346: 
10347: modify_access_controls():
10348: 
10349: Modifies access controls for a portfolio file
10350: Args
10351: 1. file name
10352: 2. reference to hash of required changes,
10353: 3. domain
10354: 4. username
10355:   where domain,username are the domain of the portfolio owner 
10356:   (either a user or a course) 
10357: 
10358: Returns:
10359: 1. result of additions or updates ('ok' or 'error', with error message). 
10360: 2. result of deletions ('ok' or 'error', with error message).
10361: 3. reference to hash of any new or updated access controls.
10362: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10363:    key = integer (inbound ID)
10364:    value = uniqueID  
10365: 
10366: =back
10367: 
10368: =head2 HTTP Helper Routines
10369: 
10370: =over 4
10371: 
10372: =item *
10373: 
10374: escape() : unpack non-word characters into CGI-compatible hex codes
10375: 
10376: =item *
10377: 
10378: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10379: 
10380: =back
10381: 
10382: =head1 PRIVATE SUBROUTINES
10383: 
10384: =head2 Underlying communication routines (Shouldn't call)
10385: 
10386: =over 4
10387: 
10388: =item *
10389: 
10390: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10391: 
10392: =item *
10393: 
10394: reply() : uses subreply to send a message to remote machine, logs all failures
10395: 
10396: =item *
10397: 
10398: critical() : passes a critical message to another server; if cannot
10399: get through then place message in connection buffer directory and
10400: returns con_delayed, if incapable of saving message, returns
10401: con_failed
10402: 
10403: =item *
10404: 
10405: reconlonc() : tries to reconnect lonc client processes.
10406: 
10407: =back
10408: 
10409: =head2 Resource Access Logging
10410: 
10411: =over 4
10412: 
10413: =item *
10414: 
10415: flushcourselogs() : flush (save) buffer logs and access logs
10416: 
10417: =item *
10418: 
10419: courselog($what) : save message for course in hash
10420: 
10421: =item *
10422: 
10423: courseacclog($what) : save message for course using &courselog().  Perform
10424: special processing for specific resource types (problems, exams, quizzes, etc).
10425: 
10426: =item *
10427: 
10428: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10429: as a PerlChildExitHandler
10430: 
10431: =back
10432: 
10433: =head2 Other
10434: 
10435: =over 4
10436: 
10437: =item *
10438: 
10439: symblist($mapname,%newhash) : update symbolic storage links
10440: 
10441: =back
10442: 
10443: =cut
10444: 

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