File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.995: download - view: text, annotated - select for diffs
Tue May 5 00:42:35 2009 UTC (15 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Upload scantron data file.
 - Eliminate copy and pasted code from lonnet::userfileupload() by calling the routine directly.
 - Pass scantron as a subdir name (although files still currently stored in top level userfiles directory).

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.995 2009/05/05 00:42:35 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:     if ($subdir eq 'scantron') {
 2170:         $fname = 'scantron_orig_'.$fname;
 2171:     } else {   
 2172: # Create the directory if not present
 2173:         $fname="$subdir/$fname";
 2174:     }
 2175:     if ($coursedoc) {
 2176: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2177: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2178:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2179:             return &finishuserfileupload($docuname,$docudom,
 2180: 					 $formname,$fname,$parser,$allfiles,
 2181: 					 $codebase,$thumbwidth,$thumbheight);
 2182:         } else {
 2183:             $fname=$env{'form.folder'}.'/'.$fname;
 2184:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2185: 				       $fname,$formname,$parser,
 2186: 				       $allfiles,$codebase);
 2187:         }
 2188:     } elsif (defined($destuname)) {
 2189:         my $docuname=$destuname;
 2190:         my $docudom=$destudom;
 2191: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2192: 				     $parser,$allfiles,$codebase,
 2193:                                      $thumbwidth,$thumbheight);
 2194:         
 2195:     } else {
 2196:         my $docuname=$env{'user.name'};
 2197:         my $docudom=$env{'user.domain'};
 2198:         if (exists($env{'form.group'})) {
 2199:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2200:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2201:         }
 2202: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2203: 				     $parser,$allfiles,$codebase,
 2204:                                      $thumbwidth,$thumbheight);
 2205:     }
 2206: }
 2207: 
 2208: sub finishuserfileupload {
 2209:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2210:         $thumbwidth,$thumbheight) = @_;
 2211:     my $path=$docudom.'/'.$docuname.'/';
 2212:     my $filepath=$perlvar{'lonDocRoot'};
 2213:   
 2214:     my ($fnamepath,$file,$fetchthumb);
 2215:     $file=$fname;
 2216:     if ($fname=~m|/|) {
 2217:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2218: 	$path.=$fnamepath.'/';
 2219:     }
 2220:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2221:     my $count;
 2222:     for ($count=4;$count<=$#parts;$count++) {
 2223:         $filepath.="/$parts[$count]";
 2224:         if ((-e $filepath)!=1) {
 2225: 	    mkdir($filepath,0777);
 2226:         }
 2227:     }
 2228: 
 2229: # Save the file
 2230:     {
 2231: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2232: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2233: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2234: 	    return '/adm/notfound.html';
 2235: 	}
 2236: 	if (!print FH ($env{'form.'.$formname})) {
 2237: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2238: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2239: 	    return '/adm/notfound.html';
 2240: 	}
 2241: 	close(FH);
 2242: 	if($upload_photo_form==1)
 2243: 	{
 2244: 		resizeImage($filepath.'/'.$file);		
 2245: 		$upload_photo_form = 0;
 2246: 	}
 2247:     }
 2248:     if ($parser eq 'parse') {
 2249:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
 2250: 						   $codebase);
 2251:         unless ($parse_result eq 'ok') {
 2252:             &logthis('Failed to parse '.$filepath.$file.
 2253: 		     ' for embedded media: '.$parse_result); 
 2254:         }
 2255:     }
 2256:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2257:         my $input = $filepath.'/'.$file;
 2258:         my $output = $filepath.'/'.'tn-'.$file;
 2259:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2260:         system("convert -sample $thumbsize $input $output");
 2261:         if (-e $filepath.'/'.'tn-'.$file) {
 2262:             $fetchthumb  = 1; 
 2263:         }
 2264:     }
 2265:  
 2266: # Notify homeserver to grep it
 2267: #
 2268:     my $docuhome=&homeserver($docuname,$docudom);	
 2269:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2270:     if ($fetchresult eq 'ok') {
 2271:         if ($fetchthumb) {
 2272:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2273:             if ($thumbresult ne 'ok') {
 2274:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2275:                          $docuhome.': '.$thumbresult);
 2276:             }
 2277:         }
 2278: #
 2279: # Return the URL to it
 2280:         return '/uploaded/'.$path.$file;
 2281:     } else {
 2282:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2283: 		 ': '.$fetchresult);
 2284:         return '/adm/notfound.html';
 2285:     }
 2286: }
 2287: 
 2288: sub extract_embedded_items {
 2289:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 2290:     my @state = ();
 2291:     my %javafiles = (
 2292:                       codebase => '',
 2293:                       code => '',
 2294:                       archive => ''
 2295:                     );
 2296:     my %mediafiles = (
 2297:                       src => '',
 2298:                       movie => '',
 2299:                      );
 2300:     my $p;
 2301:     if ($content) {
 2302:         $p = HTML::LCParser->new($content);
 2303:     } else {
 2304:         $p = HTML::LCParser->new($fullpath);
 2305:     }
 2306:     while (my $t=$p->get_token()) {
 2307: 	if ($t->[0] eq 'S') {
 2308: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2309: 	    push(@state, $tagname);
 2310:             if (lc($tagname) eq 'allow') {
 2311:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2312:             }
 2313: 	    if (lc($tagname) eq 'img') {
 2314: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2315: 	    }
 2316: 	    if (lc($tagname) eq 'a') {
 2317: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2318: 	    }
 2319:             if (lc($tagname) eq 'script') {
 2320:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2321:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2322:                 } else {
 2323:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2324:                 }
 2325:             }
 2326:             if (lc($tagname) eq 'link') {
 2327:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2328:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2329:                 }
 2330:             }
 2331: 	    if (lc($tagname) eq 'object' ||
 2332: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2333: 		foreach my $item (keys(%javafiles)) {
 2334: 		    $javafiles{$item} = '';
 2335: 		}
 2336: 	    }
 2337: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2338: 		my $name = lc($attr->{'name'});
 2339: 		foreach my $item (keys(%javafiles)) {
 2340: 		    if ($name eq $item) {
 2341: 			$javafiles{$item} = $attr->{'value'};
 2342: 			last;
 2343: 		    }
 2344: 		}
 2345: 		foreach my $item (keys(%mediafiles)) {
 2346: 		    if ($name eq $item) {
 2347: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2348: 			last;
 2349: 		    }
 2350: 		}
 2351: 	    }
 2352: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2353: 		foreach my $item (keys(%javafiles)) {
 2354: 		    if ($attr->{$item}) {
 2355: 			$javafiles{$item} = $attr->{$item};
 2356: 			last;
 2357: 		    }
 2358: 		}
 2359: 		foreach my $item (keys(%mediafiles)) {
 2360: 		    if ($attr->{$item}) {
 2361: 			&add_filetype($allfiles,$attr->{$item},$item);
 2362: 			last;
 2363: 		    }
 2364: 		}
 2365: 	    }
 2366: 	} elsif ($t->[0] eq 'E') {
 2367: 	    my ($tagname) = ($t->[1]);
 2368: 	    if ($javafiles{'codebase'} ne '') {
 2369: 		$javafiles{'codebase'} .= '/';
 2370: 	    }  
 2371: 	    if (lc($tagname) eq 'applet' ||
 2372: 		lc($tagname) eq 'object' ||
 2373: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2374: 		) {
 2375: 		foreach my $item (keys(%javafiles)) {
 2376: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2377: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2378: 			&add_filetype($allfiles,$file,$item);
 2379: 		    }
 2380: 		}
 2381: 	    } 
 2382: 	    pop @state;
 2383: 	}
 2384:     }
 2385:     return 'ok';
 2386: }
 2387: 
 2388: sub add_filetype {
 2389:     my ($allfiles,$file,$type)=@_;
 2390:     if (exists($allfiles->{$file})) {
 2391: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2392: 	    push(@{$allfiles->{$file}}, &escape($type));
 2393: 	}
 2394:     } else {
 2395: 	@{$allfiles->{$file}} = (&escape($type));
 2396:     }
 2397: }
 2398: 
 2399: sub removeuploadedurl {
 2400:     my ($url)=@_;	
 2401:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 2402:     return &removeuserfile($uname,$udom,$fname);
 2403: }
 2404: 
 2405: sub removeuserfile {
 2406:     my ($docuname,$docudom,$fname)=@_;
 2407:     my $home=&homeserver($docuname,$docudom);    
 2408:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2409:     if ($result eq 'ok') {	
 2410:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2411:             my $metafile = $fname.'.meta';
 2412:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2413: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2414:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 2415:             my $sqlresult = 
 2416:                 &update_portfolio_table($docuname,$docudom,$file,
 2417:                                         'portfolio_metadata',$group,
 2418:                                         'delete');
 2419:         }
 2420:     }
 2421:     return $result;
 2422: }
 2423: 
 2424: sub mkdiruserfile {
 2425:     my ($docuname,$docudom,$dir)=@_;
 2426:     my $home=&homeserver($docuname,$docudom);
 2427:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2428: }
 2429: 
 2430: sub renameuserfile {
 2431:     my ($docuname,$docudom,$old,$new)=@_;
 2432:     my $home=&homeserver($docuname,$docudom);
 2433:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2434:                         &escape("$old").':'.&escape("$new"),$home);
 2435:     if ($result eq 'ok') {
 2436:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2437:             my $oldmeta = $old.'.meta';
 2438:             my $newmeta = $new.'.meta';
 2439:             my $metaresult = 
 2440:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2441: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2442:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2443:             my $sqlresult = 
 2444:                 &update_portfolio_table($docuname,$docudom,$file,
 2445:                                         'portfolio_metadata',$group,
 2446:                                         'delete');
 2447:         }
 2448:     }
 2449:     return $result;
 2450: }
 2451: 
 2452: # ------------------------------------------------------------------------- Log
 2453: 
 2454: sub log {
 2455:     my ($dom,$nam,$hom,$what)=@_;
 2456:     return critical("log:$dom:$nam:$what",$hom);
 2457: }
 2458: 
 2459: # ------------------------------------------------------------------ Course Log
 2460: #
 2461: # This routine flushes several buffers of non-mission-critical nature
 2462: #
 2463: 
 2464: sub flushcourselogs {
 2465:     &logthis('Flushing log buffers');
 2466: #
 2467: # course logs
 2468: # This is a log of all transactions in a course, which can be used
 2469: # for data mining purposes
 2470: #
 2471: # It also collects the courseid database, which lists last transaction
 2472: # times and course titles for all courseids
 2473: #
 2474:     my %courseidbuffer=();
 2475:     foreach my $crsid (keys(%courselogs)) {
 2476:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2477: 		          &escape($courselogs{$crsid}),
 2478: 		          $coursehombuf{$crsid}) eq 'ok') {
 2479: 	    delete $courselogs{$crsid};
 2480:         } else {
 2481:             &logthis('Failed to flush log buffer for '.$crsid);
 2482:             if (length($courselogs{$crsid})>40000) {
 2483:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2484:                         " exceeded maximum size, deleting.</font>");
 2485:                delete $courselogs{$crsid};
 2486:             }
 2487:         }
 2488:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2489:             'description' => $coursedescrbuf{$crsid},
 2490:             'inst_code'    => $courseinstcodebuf{$crsid},
 2491:             'type'        => $coursetypebuf{$crsid},
 2492:             'owner'       => $courseownerbuf{$crsid},
 2493:         };
 2494:     }
 2495: #
 2496: # Write course id database (reverse lookup) to homeserver of courses 
 2497: # Is used in pickcourse
 2498: #
 2499:     foreach my $crs_home (keys(%courseidbuffer)) {
 2500:         my $response = &courseidput(&host_domain($crs_home),
 2501:                                     $courseidbuffer{$crs_home},
 2502:                                     $crs_home,'timeonly');
 2503:     }
 2504: #
 2505: # File accesses
 2506: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2507: #
 2508:     foreach my $entry (keys(%accesshash)) {
 2509:         if ($entry =~ /___count$/) {
 2510:             my ($dom,$name);
 2511:             ($dom,$name,undef)=
 2512: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2513:             if (! defined($dom) || $dom eq '' || 
 2514:                 ! defined($name) || $name eq '') {
 2515:                 my $cid = $env{'request.course.id'};
 2516:                 $dom  = $env{'request.'.$cid.'.domain'};
 2517:                 $name = $env{'request.'.$cid.'.num'};
 2518:             }
 2519:             my $value = $accesshash{$entry};
 2520:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2521:             my %temphash=($url => $value);
 2522:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2523:             if ($result eq 'ok') {
 2524:                 delete $accesshash{$entry};
 2525:             } elsif ($result eq 'unknown_cmd') {
 2526:                 # Target server has old code running on it.
 2527:                 my %temphash=($entry => $value);
 2528:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2529:                     delete $accesshash{$entry};
 2530:                 }
 2531:             }
 2532:         } else {
 2533:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2534:             my %temphash=($entry => $accesshash{$entry});
 2535:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2536:                 delete $accesshash{$entry};
 2537:             }
 2538:         }
 2539:     }
 2540: #
 2541: # Roles
 2542: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2543: #
 2544:     foreach my $entry (keys(%userrolehash)) {
 2545:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2546: 	    split(/\:/,$entry);
 2547:         if (&Apache::lonnet::put('nohist_userroles',
 2548:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2549:                 $rudom,$runame) eq 'ok') {
 2550: 	    delete $userrolehash{$entry};
 2551:         }
 2552:     }
 2553: #
 2554: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2555: #
 2556:     my %domrolebuffer = ();
 2557:     foreach my $entry (keys %domainrolehash) {
 2558:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2559:         if ($domrolebuffer{$rudom}) {
 2560:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2561:                       '='.&escape($domainrolehash{$entry});
 2562:         } else {
 2563:             $domrolebuffer{$rudom}.=&escape($entry).
 2564:                       '='.&escape($domainrolehash{$entry});
 2565:         }
 2566:         delete $domainrolehash{$entry};
 2567:     }
 2568:     foreach my $dom (keys(%domrolebuffer)) {
 2569: 	my %servers = &get_servers($dom,'library');
 2570: 	foreach my $tryserver (keys(%servers)) {
 2571: 	    unless (&reply('domroleput:'.$dom.':'.
 2572: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2573: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2574: 	    }
 2575:         }
 2576:     }
 2577:     $dumpcount++;
 2578: }
 2579: 
 2580: sub courselog {
 2581:     my $what=shift;
 2582:     $what=time.':'.$what;
 2583:     unless ($env{'request.course.id'}) { return ''; }
 2584:     $coursedombuf{$env{'request.course.id'}}=
 2585:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2586:     $coursenumbuf{$env{'request.course.id'}}=
 2587:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2588:     $coursehombuf{$env{'request.course.id'}}=
 2589:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2590:     $coursedescrbuf{$env{'request.course.id'}}=
 2591:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2592:     $courseinstcodebuf{$env{'request.course.id'}}=
 2593:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2594:     $courseownerbuf{$env{'request.course.id'}}=
 2595:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2596:     $coursetypebuf{$env{'request.course.id'}}=
 2597:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2598:     if (defined $courselogs{$env{'request.course.id'}}) {
 2599: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2600:     } else {
 2601: 	$courselogs{$env{'request.course.id'}}.=$what;
 2602:     }
 2603:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2604: 	&flushcourselogs();
 2605:     }
 2606: }
 2607: 
 2608: sub courseacclog {
 2609:     my $fnsymb=shift;
 2610:     unless ($env{'request.course.id'}) { return ''; }
 2611:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2612:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2613:         $what.=':POST';
 2614:         # FIXME: Probably ought to escape things....
 2615: 	foreach my $key (keys(%env)) {
 2616:             if ($key=~/^form\.(.*)/) {
 2617:                 my $formitem = $1;
 2618:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 2619:                     $what.=':'.$formitem.'='.$env{$key};
 2620:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 2621:                     $what.=':'.$formitem.'='.$env{$key};
 2622:                 }
 2623:             }
 2624:         }
 2625:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2626:         # FIXME: We should not be depending on a form parameter that someone
 2627:         # editing lonsearchcat.pm might change in the future.
 2628:         if ($env{'form.phase'} eq 'course_search') {
 2629:             $what.= ':POST';
 2630:             # FIXME: Probably ought to escape things....
 2631:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2632:                                  'crsdiscuss') {
 2633:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2634:             }
 2635:         }
 2636:     }
 2637:     &courselog($what);
 2638: }
 2639: 
 2640: sub countacc {
 2641:     my $url=&declutter(shift);
 2642:     return if (! defined($url) || $url eq '');
 2643:     unless ($env{'request.course.id'}) { return ''; }
 2644:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2645:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2646:     $accesshash{$key}++;
 2647: }
 2648: 
 2649: sub linklog {
 2650:     my ($from,$to)=@_;
 2651:     $from=&declutter($from);
 2652:     $to=&declutter($to);
 2653:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2654:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2655: }
 2656:   
 2657: sub userrolelog {
 2658:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2659:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2660:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2661:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2662:         ($trole=~/^ta/)) {
 2663:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2664:        $userrolehash
 2665:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2666:                     =$tend.':'.$tstart;
 2667:     }
 2668:     if (($env{'request.role'} =~ /dc\./) &&
 2669: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2670: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2671: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
 2672:        $userrolehash
 2673:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2674:                     =$tend.':'.$tstart;
 2675:     }
 2676:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2677:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2678:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2679:         ($trole=~/^sc/)) {
 2680:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2681:        $domainrolehash
 2682:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2683:                     = $tend.':'.$tstart;
 2684:     }
 2685: }
 2686: 
 2687: sub courserolelog {
 2688:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 2689:     if (($trole eq 'cc') || ($trole eq 'in') ||
 2690:         ($trole eq 'ep') || ($trole eq 'ad') ||
 2691:         ($trole eq 'ta') || ($trole eq 'st') ||
 2692:         ($trole=~/^cr/) || ($trole eq 'gr')) {
 2693:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 2694:             my $cdom = $1;
 2695:             my $cnum = $2;
 2696:             my $sec = $3;
 2697:             my $namespace = 'rolelog';
 2698:             my %storehash = (
 2699:                                role    => $trole,
 2700:                                start   => $tstart,
 2701:                                end     => $tend,
 2702:                                selfenroll => $selfenroll,
 2703:                                context    => $context,
 2704:                             );
 2705:             if ($trole eq 'gr') {
 2706:                 $namespace = 'groupslog';
 2707:                 $storehash{'group'} = $sec;
 2708:             } else {
 2709:                 $storehash{'section'} = $sec;
 2710:             }
 2711:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 2712:         }
 2713:     }
 2714:     return;
 2715: }
 2716: 
 2717: sub get_course_adv_roles {
 2718:     my ($cid,$codes) = @_;
 2719:     $cid=$env{'request.course.id'} unless (defined($cid));
 2720:     my %coursehash=&coursedescription($cid);
 2721:     my $crstype = &Apache::loncommon::course_type($cid);
 2722:     my %nothide=();
 2723:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2724:         if ($user !~ /:/) {
 2725: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2726:         } else {
 2727:             $nothide{$user}=1;
 2728:         }
 2729:     }
 2730:     my %returnhash=();
 2731:     my %dumphash=
 2732:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2733:     my $now=time;
 2734:     foreach my $entry (keys %dumphash) {
 2735: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2736:         if (($tstart) && ($tstart<0)) { next; }
 2737:         if (($tend) && ($tend<$now)) { next; }
 2738:         if (($tstart) && ($now<$tstart)) { next; }
 2739:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2740: 	if ($username eq '' || $domain eq '') { next; }
 2741: 	if ((&privileged($username,$domain)) && 
 2742: 	    (!$nothide{$username.':'.$domain})) { next; }
 2743: 	if ($role eq 'cr') { next; }
 2744:         if ($codes) {
 2745:             if ($section) { $role .= ':'.$section; }
 2746:             if ($returnhash{$role}) {
 2747:                 $returnhash{$role}.=','.$username.':'.$domain;
 2748:             } else {
 2749:                 $returnhash{$role}=$username.':'.$domain;
 2750:             }
 2751:         } else {
 2752:             my $key=&plaintext($role,$crstype);
 2753:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 2754:             if ($returnhash{$key}) {
 2755: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2756:             } else {
 2757:                 $returnhash{$key}=$username.':'.$domain;
 2758:             }
 2759:         }
 2760:     }
 2761:     return %returnhash;
 2762: }
 2763: 
 2764: sub get_my_roles {
 2765:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2766:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2767:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2768:     my (%dumphash,%nothide);
 2769:     if ($context eq 'userroles') { 
 2770:         %dumphash = &dump('roles',$udom,$uname);
 2771:     } else {
 2772:         %dumphash=
 2773:             &dump('nohist_userroles',$udom,$uname);
 2774:         if ($hidepriv) {
 2775:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2776:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2777:                 if ($user !~ /:/) {
 2778:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2779:                 } else {
 2780:                     $nothide{$user} = 1;
 2781:                 }
 2782:             }
 2783:         }
 2784:     }
 2785:     my %returnhash=();
 2786:     my $now=time;
 2787:     foreach my $entry (keys(%dumphash)) {
 2788:         my ($role,$tend,$tstart);
 2789:         if ($context eq 'userroles') {
 2790: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2791:         } else {
 2792:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2793:         }
 2794:         if (($tstart) && ($tstart<0)) { next; }
 2795:         my $status = 'active';
 2796:         if (($tend) && ($tend<=$now)) {
 2797:             $status = 'previous';
 2798:         } 
 2799:         if (($tstart) && ($now<$tstart)) {
 2800:             $status = 'future';
 2801:         }
 2802:         if (ref($types) eq 'ARRAY') {
 2803:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2804:                 next;
 2805:             } 
 2806:         } else {
 2807:             if ($status ne 'active') {
 2808:                 next;
 2809:             }
 2810:         }
 2811:         my ($rolecode,$username,$domain,$section,$area);
 2812:         if ($context eq 'userroles') {
 2813:             ($area,$rolecode) = split(/_/,$entry);
 2814:             (undef,$domain,$username,$section) = split(/\//,$area);
 2815:         } else {
 2816:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2817:         }
 2818:         if (ref($roledoms) eq 'ARRAY') {
 2819:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2820:                 next;
 2821:             }
 2822:         }
 2823:         if (ref($roles) eq 'ARRAY') {
 2824:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2825:                 if ($role =~ /^cr\//) {
 2826:                     if (!grep(/^cr$/,@{$roles})) {
 2827:                         next;
 2828:                     }
 2829:                 } else {
 2830:                     next;
 2831:                 }
 2832:             }
 2833:         }
 2834:         if ($hidepriv) {
 2835:             if ((&privileged($username,$domain)) &&
 2836:                 (!$nothide{$username.':'.$domain})) { 
 2837:                 next;
 2838:             }
 2839:         }
 2840:         if ($withsec) {
 2841:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2842:                 $tstart.':'.$tend;
 2843:         } else {
 2844:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2845:         }
 2846:     }
 2847:     return %returnhash;
 2848: }
 2849: 
 2850: # ----------------------------------------------------- Frontpage Announcements
 2851: #
 2852: #
 2853: 
 2854: sub postannounce {
 2855:     my ($server,$text)=@_;
 2856:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2857:     unless ($text=~/\w/) { $text=''; }
 2858:     return &reply('setannounce:'.&escape($text),$server);
 2859: }
 2860: 
 2861: sub getannounce {
 2862: 
 2863:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2864: 	my $announcement='';
 2865: 	while (my $line = <$fh>) { $announcement .= $line; }
 2866: 	close($fh);
 2867: 	if ($announcement=~/\w/) { 
 2868: 	    return 
 2869:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2870:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2871: 	} else {
 2872: 	    return '';
 2873: 	}
 2874:     } else {
 2875: 	return '';
 2876:     }
 2877: }
 2878: 
 2879: # ---------------------------------------------------------- Course ID routines
 2880: # Deal with domain's nohist_courseid.db files
 2881: #
 2882: 
 2883: sub courseidput {
 2884:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2885:     my $outcome;
 2886:     if ($caller eq 'timeonly') {
 2887:         my $cids = '';
 2888:         foreach my $item (keys(%$storehash)) {
 2889:             $cids.=&escape($item).'&';
 2890:         }
 2891:         $cids=~s/\&$//;
 2892:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 2893:                           $coursehome);       
 2894:     } else {
 2895:         my $items = '';
 2896:         foreach my $item (keys(%$storehash)) {
 2897:             $items.= &escape($item).'='.
 2898:                      &freeze_escape($$storehash{$item}).'&';
 2899:         }
 2900:         $items=~s/\&$//;
 2901:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 2902:                           $coursehome);
 2903:     }
 2904:     if ($outcome eq 'unknown_cmd') {
 2905:         my $what;
 2906:         foreach my $cid (keys(%$storehash)) {
 2907:             $what .= &escape($cid).'=';
 2908:             foreach my $item ('description','inst_code','owner','type') {
 2909:                 $what .= &escape($storehash->{$cid}{$item}).':';
 2910:             }
 2911:             $what =~ s/\:$/&/;
 2912:         }
 2913:         $what =~ s/\&$//;  
 2914:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2915:     } else {
 2916:         return $outcome;
 2917:     }
 2918: }
 2919: 
 2920: sub courseiddump {
 2921:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 2922:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 2923:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
 2924:     my $as_hash = 1;
 2925:     my %returnhash;
 2926:     if (!$domfilter) { $domfilter=''; }
 2927:     my %libserv = &all_library();
 2928:     foreach my $tryserver (keys(%libserv)) {
 2929:         if ( (  $hostidflag == 1 
 2930: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2931: 	     || (!defined($hostidflag)) ) {
 2932: 
 2933: 	    if (($domfilter eq '') ||
 2934: 		(&host_domain($tryserver) eq $domfilter)) {
 2935:                 my $rep = 
 2936:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 2937:                          $sincefilter.':'.&escape($descfilter).':'.
 2938:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 2939:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 2940:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 2941:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 2942:                          $showhidden.':'.$caller,$tryserver);
 2943:                 my @pairs=split(/\&/,$rep);
 2944:                 foreach my $item (@pairs) {
 2945:                     my ($key,$value)=split(/\=/,$item,2);
 2946:                     $key = &unescape($key);
 2947:                     next if ($key =~ /^error: 2 /);
 2948:                     my $result = &thaw_unescape($value);
 2949:                     if (ref($result) eq 'HASH') {
 2950:                         $returnhash{$key}=$result;
 2951:                     } else {
 2952:                         my @responses = split(/:/,$value);
 2953:                         my @items = ('description','inst_code','owner','type');
 2954:                         for (my $i=0; $i<@responses; $i++) {
 2955:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 2956:                         }
 2957:                     } 
 2958:                 }
 2959:             }
 2960:         }
 2961:     }
 2962:     return %returnhash;
 2963: }
 2964: 
 2965: # ---------------------------------------------------------- DC e-mail
 2966: 
 2967: sub dcmailput {
 2968:     my ($domain,$msgid,$message,$server)=@_;
 2969:     my $status = &Apache::lonnet::critical(
 2970:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2971:        &escape($message),$server);
 2972:     return $status;
 2973: }
 2974: 
 2975: sub dcmaildump {
 2976:     my ($dom,$startdate,$enddate,$senders) = @_;
 2977:     my %returnhash=();
 2978: 
 2979:     if (defined(&domain($dom,'primary'))) {
 2980:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2981:                                                          &escape($enddate).':';
 2982: 	my @esc_senders=map { &escape($_)} @$senders;
 2983: 	$cmd.=&escape(join('&',@esc_senders));
 2984: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2985:             my ($key,$value) = split(/\=/,$line,2);
 2986:             if (($key) && ($value)) {
 2987:                 $returnhash{&unescape($key)} = &unescape($value);
 2988:             }
 2989:         }
 2990:     }
 2991:     return %returnhash;
 2992: }
 2993: # ---------------------------------------------------------- Domain roles
 2994: 
 2995: sub get_domain_roles {
 2996:     my ($dom,$roles,$startdate,$enddate)=@_;
 2997:     if (undef($startdate) || $startdate eq '') {
 2998:         $startdate = '.';
 2999:     }
 3000:     if (undef($enddate) || $enddate eq '') {
 3001:         $enddate = '.';
 3002:     }
 3003:     my $rolelist;
 3004:     if (ref($roles) eq 'ARRAY') {
 3005:         $rolelist = join(':',@{$roles});
 3006:     }
 3007:     my %personnel = ();
 3008: 
 3009:     my %servers = &get_servers($dom,'library');
 3010:     foreach my $tryserver (keys(%servers)) {
 3011: 	%{$personnel{$tryserver}}=();
 3012: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 3013: 					    &escape($startdate).':'.
 3014: 					    &escape($enddate).':'.
 3015: 					    &escape($rolelist), $tryserver))) {
 3016: 	    my ($key,$value) = split(/\=/,$line,2);
 3017: 	    if (($key) && ($value)) {
 3018: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 3019: 	    }
 3020: 	}
 3021:     }
 3022:     return %personnel;
 3023: }
 3024: 
 3025: # ----------------------------------------------------------- Check out an item
 3026: 
 3027: sub get_first_access {
 3028:     my ($type,$argsymb)=@_;
 3029:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3030:     if ($argsymb) { $symb=$argsymb; }
 3031:     my ($map,$id,$res)=&decode_symb($symb);
 3032:     if ($type eq 'course') {
 3033: 	$res='course';
 3034:     } elsif ($type eq 'map') {
 3035: 	$res=&symbread($map);
 3036:     } else {
 3037: 	$res=$symb;
 3038:     }
 3039:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 3040:     return $times{"$courseid\0$res"};
 3041: }
 3042: 
 3043: sub set_first_access {
 3044:     my ($type)=@_;
 3045:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3046:     my ($map,$id,$res)=&decode_symb($symb);
 3047:     if ($type eq 'course') {
 3048: 	$res='course';
 3049:     } elsif ($type eq 'map') {
 3050: 	$res=&symbread($map);
 3051:     } else {
 3052: 	$res=$symb;
 3053:     }
 3054:     my $firstaccess=&get_first_access($type,$symb);
 3055:     if (!$firstaccess) {
 3056: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 3057:     }
 3058:     return 'already_set';
 3059: }
 3060: 
 3061: sub checkout {
 3062:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 3063:     my $now=time;
 3064:     my $lonhost=$perlvar{'lonHostID'};
 3065:     my $infostr=&escape(
 3066:                  'CHECKOUTTOKEN&'.
 3067:                  $tuname.'&'.
 3068:                  $tudom.'&'.
 3069:                  $tcrsid.'&'.
 3070:                  $symb.'&'.
 3071: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 3072:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 3073:     if ($token=~/^error\:/) { 
 3074:         &logthis("<font color=\"blue\">WARNING: ".
 3075:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 3076:                  "</font>");
 3077:         return ''; 
 3078:     }
 3079: 
 3080:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 3081:     $token=~tr/a-z/A-Z/;
 3082: 
 3083:     my %infohash=('resource.0.outtoken' => $token,
 3084:                   'resource.0.checkouttime' => $now,
 3085:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 3086: 
 3087:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3088:        return '';
 3089:     } else {
 3090:         &logthis("<font color=\"blue\">WARNING: ".
 3091:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 3092:                  "</font>");
 3093:     }    
 3094: 
 3095:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3096:                          &escape('Checkout '.$infostr.' - '.
 3097:                                                  $token)) ne 'ok') {
 3098: 	return '';
 3099:     } else {
 3100:         &logthis("<font color=\"blue\">WARNING: ".
 3101:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 3102:                  "</font>");
 3103:     }
 3104:     return $token;
 3105: }
 3106: 
 3107: # ------------------------------------------------------------ Check in an item
 3108: 
 3109: sub checkin {
 3110:     my $token=shift;
 3111:     my $now=time;
 3112:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 3113:     $lonhost=~tr/A-Z/a-z/;
 3114:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 3115:     $dtoken=~s/\W/\_/g;
 3116:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 3117:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 3118: 
 3119:     unless (($tuname) && ($tudom)) {
 3120:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 3121:         return '';
 3122:     }
 3123:     
 3124:     unless (&allowed('mgr',$tcrsid)) {
 3125:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 3126:                  $env{'user.name'}.' - '.$env{'user.domain'});
 3127:         return '';
 3128:     }
 3129: 
 3130:     my %infohash=('resource.0.intoken' => $token,
 3131:                   'resource.0.checkintime' => $now,
 3132:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 3133: 
 3134:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3135:        return '';
 3136:     }    
 3137: 
 3138:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3139:                          &escape('Checkin - '.$token)) ne 'ok') {
 3140: 	return '';
 3141:     }
 3142: 
 3143:     return ($symb,$tuname,$tudom,$tcrsid);    
 3144: }
 3145: 
 3146: # --------------------------------------------- Set Expire Date for Spreadsheet
 3147: 
 3148: sub expirespread {
 3149:     my ($uname,$udom,$stype,$usymb)=@_;
 3150:     my $cid=$env{'request.course.id'}; 
 3151:     if ($cid) {
 3152:        my $now=time;
 3153:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3154:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3155:                             $env{'course.'.$cid.'.num'}.
 3156: 	        	    ':nohist_expirationdates:'.
 3157:                             &escape($key).'='.$now,
 3158:                             $env{'course.'.$cid.'.home'})
 3159:     }
 3160:     return 'ok';
 3161: }
 3162: 
 3163: # ----------------------------------------------------- Devalidate Spreadsheets
 3164: 
 3165: sub devalidate {
 3166:     my ($symb,$uname,$udom)=@_;
 3167:     my $cid=$env{'request.course.id'}; 
 3168:     if ($cid) {
 3169:         # delete the stored spreadsheets for
 3170:         # - the student level sheet of this user in course's homespace
 3171:         # - the assessment level sheet for this resource 
 3172:         #   for this user in user's homespace
 3173: 	# - current conditional state info
 3174: 	my $key=$uname.':'.$udom.':';
 3175:         my $status=
 3176: 	    &del('nohist_calculatedsheets',
 3177: 		 [$key.'studentcalc:'],
 3178: 		 $env{'course.'.$cid.'.domain'},
 3179: 		 $env{'course.'.$cid.'.num'})
 3180: 		.' '.
 3181: 	    &del('nohist_calculatedsheets_'.$cid,
 3182: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3183:         unless ($status eq 'ok ok') {
 3184:            &logthis('Could not devalidate spreadsheet '.
 3185:                     $uname.' at '.$udom.' for '.
 3186: 		    $symb.': '.$status);
 3187:         }
 3188: 	&delenv('user.state.'.$cid);
 3189:     }
 3190: }
 3191: 
 3192: sub get_scalar {
 3193:     my ($string,$end) = @_;
 3194:     my $value;
 3195:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3196: 	$value = $1;
 3197:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3198: 	$value = $1;
 3199:     }
 3200:     return &unescape($value);
 3201: }
 3202: 
 3203: sub array2str {
 3204:   my (@array) = @_;
 3205:   my $result=&arrayref2str(\@array);
 3206:   $result=~s/^__ARRAY_REF__//;
 3207:   $result=~s/__END_ARRAY_REF__$//;
 3208:   return $result;
 3209: }
 3210: 
 3211: sub arrayref2str {
 3212:   my ($arrayref) = @_;
 3213:   my $result='__ARRAY_REF__';
 3214:   foreach my $elem (@$arrayref) {
 3215:     if(ref($elem) eq 'ARRAY') {
 3216:       $result.=&arrayref2str($elem).'&';
 3217:     } elsif(ref($elem) eq 'HASH') {
 3218:       $result.=&hashref2str($elem).'&';
 3219:     } elsif(ref($elem)) {
 3220:       #print("Got a ref of ".(ref($elem))." skipping.");
 3221:     } else {
 3222:       $result.=&escape($elem).'&';
 3223:     }
 3224:   }
 3225:   $result=~s/\&$//;
 3226:   $result .= '__END_ARRAY_REF__';
 3227:   return $result;
 3228: }
 3229: 
 3230: sub hash2str {
 3231:   my (%hash) = @_;
 3232:   my $result=&hashref2str(\%hash);
 3233:   $result=~s/^__HASH_REF__//;
 3234:   $result=~s/__END_HASH_REF__$//;
 3235:   return $result;
 3236: }
 3237: 
 3238: sub hashref2str {
 3239:   my ($hashref)=@_;
 3240:   my $result='__HASH_REF__';
 3241:   foreach my $key (sort(keys(%$hashref))) {
 3242:     if (ref($key) eq 'ARRAY') {
 3243:       $result.=&arrayref2str($key).'=';
 3244:     } elsif (ref($key) eq 'HASH') {
 3245:       $result.=&hashref2str($key).'=';
 3246:     } elsif (ref($key)) {
 3247:       $result.='=';
 3248:       #print("Got a ref of ".(ref($key))." skipping.");
 3249:     } else {
 3250: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3251:     }
 3252: 
 3253:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3254:       $result.=&arrayref2str($hashref->{$key}).'&';
 3255:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3256:       $result.=&hashref2str($hashref->{$key}).'&';
 3257:     } elsif(ref($hashref->{$key})) {
 3258:        $result.='&';
 3259:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3260:     } else {
 3261:       $result.=&escape($hashref->{$key}).'&';
 3262:     }
 3263:   }
 3264:   $result=~s/\&$//;
 3265:   $result .= '__END_HASH_REF__';
 3266:   return $result;
 3267: }
 3268: 
 3269: sub str2hash {
 3270:     my ($string)=@_;
 3271:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3272:     return %$hash;
 3273: }
 3274: 
 3275: sub str2hashref {
 3276:   my ($string) = @_;
 3277: 
 3278:   my %hash;
 3279: 
 3280:   if($string !~ /^__HASH_REF__/) {
 3281:       if (! ($string eq '' || !defined($string))) {
 3282: 	  $hash{'error'}='Not hash reference';
 3283:       }
 3284:       return (\%hash, $string);
 3285:   }
 3286: 
 3287:   $string =~ s/^__HASH_REF__//;
 3288: 
 3289:   while($string !~ /^__END_HASH_REF__/) {
 3290:       #key
 3291:       my $key='';
 3292:       if($string =~ /^__HASH_REF__/) {
 3293:           ($key, $string)=&str2hashref($string);
 3294:           if(defined($key->{'error'})) {
 3295:               $hash{'error'}='Bad data';
 3296:               return (\%hash, $string);
 3297:           }
 3298:       } elsif($string =~ /^__ARRAY_REF__/) {
 3299:           ($key, $string)=&str2arrayref($string);
 3300:           if($key->[0] eq 'Array reference error') {
 3301:               $hash{'error'}='Bad data';
 3302:               return (\%hash, $string);
 3303:           }
 3304:       } else {
 3305:           $string =~ s/^(.*?)=//;
 3306: 	  $key=&unescape($1);
 3307:       }
 3308:       $string =~ s/^=//;
 3309: 
 3310:       #value
 3311:       my $value='';
 3312:       if($string =~ /^__HASH_REF__/) {
 3313:           ($value, $string)=&str2hashref($string);
 3314:           if(defined($value->{'error'})) {
 3315:               $hash{'error'}='Bad data';
 3316:               return (\%hash, $string);
 3317:           }
 3318:       } elsif($string =~ /^__ARRAY_REF__/) {
 3319:           ($value, $string)=&str2arrayref($string);
 3320:           if($value->[0] eq 'Array reference error') {
 3321:               $hash{'error'}='Bad data';
 3322:               return (\%hash, $string);
 3323:           }
 3324:       } else {
 3325: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3326:       }
 3327:       $string =~ s/^&//;
 3328: 
 3329:       $hash{$key}=$value;
 3330:   }
 3331: 
 3332:   $string =~ s/^__END_HASH_REF__//;
 3333: 
 3334:   return (\%hash, $string);
 3335: }
 3336: 
 3337: sub str2array {
 3338:     my ($string)=@_;
 3339:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3340:     return @$array;
 3341: }
 3342: 
 3343: sub str2arrayref {
 3344:   my ($string) = @_;
 3345:   my @array;
 3346: 
 3347:   if($string !~ /^__ARRAY_REF__/) {
 3348:       if (! ($string eq '' || !defined($string))) {
 3349: 	  $array[0]='Array reference error';
 3350:       }
 3351:       return (\@array, $string);
 3352:   }
 3353: 
 3354:   $string =~ s/^__ARRAY_REF__//;
 3355: 
 3356:   while($string !~ /^__END_ARRAY_REF__/) {
 3357:       my $value='';
 3358:       if($string =~ /^__HASH_REF__/) {
 3359:           ($value, $string)=&str2hashref($string);
 3360:           if(defined($value->{'error'})) {
 3361:               $array[0] ='Array reference error';
 3362:               return (\@array, $string);
 3363:           }
 3364:       } elsif($string =~ /^__ARRAY_REF__/) {
 3365:           ($value, $string)=&str2arrayref($string);
 3366:           if($value->[0] eq 'Array reference error') {
 3367:               $array[0] ='Array reference error';
 3368:               return (\@array, $string);
 3369:           }
 3370:       } else {
 3371: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3372:       }
 3373:       $string =~ s/^&//;
 3374: 
 3375:       push(@array, $value);
 3376:   }
 3377: 
 3378:   $string =~ s/^__END_ARRAY_REF__//;
 3379: 
 3380:   return (\@array, $string);
 3381: }
 3382: 
 3383: # -------------------------------------------------------------------Temp Store
 3384: 
 3385: sub tmpreset {
 3386:   my ($symb,$namespace,$domain,$stuname) = @_;
 3387:   if (!$symb) {
 3388:     $symb=&symbread();
 3389:     if (!$symb) { $symb= $env{'request.url'}; }
 3390:   }
 3391:   $symb=escape($symb);
 3392: 
 3393:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3394:   $namespace=~s/\//\_/g;
 3395:   $namespace=~s/\W//g;
 3396: 
 3397:   if (!$domain) { $domain=$env{'user.domain'}; }
 3398:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3399:   if ($domain eq 'public' && $stuname eq 'public') {
 3400:       $stuname=$ENV{'REMOTE_ADDR'};
 3401:   }
 3402:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3403:   my %hash;
 3404:   if (tie(%hash,'GDBM_File',
 3405: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3406: 	  &GDBM_WRCREAT(),0640)) {
 3407:     foreach my $key (keys %hash) {
 3408:       if ($key=~ /:$symb/) {
 3409: 	delete($hash{$key});
 3410:       }
 3411:     }
 3412:   }
 3413: }
 3414: 
 3415: sub tmpstore {
 3416:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3417: 
 3418:   if (!$symb) {
 3419:     $symb=&symbread();
 3420:     if (!$symb) { $symb= $env{'request.url'}; }
 3421:   }
 3422:   $symb=escape($symb);
 3423: 
 3424:   if (!$namespace) {
 3425:     # I don't think we would ever want to store this for a course.
 3426:     # it seems this will only be used if we don't have a course.
 3427:     #$namespace=$env{'request.course.id'};
 3428:     #if (!$namespace) {
 3429:       $namespace=$env{'request.state'};
 3430:     #}
 3431:   }
 3432:   $namespace=~s/\//\_/g;
 3433:   $namespace=~s/\W//g;
 3434:   if (!$domain) { $domain=$env{'user.domain'}; }
 3435:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3436:   if ($domain eq 'public' && $stuname eq 'public') {
 3437:       $stuname=$ENV{'REMOTE_ADDR'};
 3438:   }
 3439:   my $now=time;
 3440:   my %hash;
 3441:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3442:   if (tie(%hash,'GDBM_File',
 3443: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3444: 	  &GDBM_WRCREAT(),0640)) {
 3445:     $hash{"version:$symb"}++;
 3446:     my $version=$hash{"version:$symb"};
 3447:     my $allkeys=''; 
 3448:     foreach my $key (keys(%$storehash)) {
 3449:       $allkeys.=$key.':';
 3450:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3451:     }
 3452:     $hash{"$version:$symb:timestamp"}=$now;
 3453:     $allkeys.='timestamp';
 3454:     $hash{"$version:keys:$symb"}=$allkeys;
 3455:     if (untie(%hash)) {
 3456:       return 'ok';
 3457:     } else {
 3458:       return "error:$!";
 3459:     }
 3460:   } else {
 3461:     return "error:$!";
 3462:   }
 3463: }
 3464: 
 3465: # -----------------------------------------------------------------Temp Restore
 3466: 
 3467: sub tmprestore {
 3468:   my ($symb,$namespace,$domain,$stuname) = @_;
 3469: 
 3470:   if (!$symb) {
 3471:     $symb=&symbread();
 3472:     if (!$symb) { $symb= $env{'request.url'}; }
 3473:   }
 3474:   $symb=escape($symb);
 3475: 
 3476:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3477: 
 3478:   if (!$domain) { $domain=$env{'user.domain'}; }
 3479:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3480:   if ($domain eq 'public' && $stuname eq 'public') {
 3481:       $stuname=$ENV{'REMOTE_ADDR'};
 3482:   }
 3483:   my %returnhash;
 3484:   $namespace=~s/\//\_/g;
 3485:   $namespace=~s/\W//g;
 3486:   my %hash;
 3487:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3488:   if (tie(%hash,'GDBM_File',
 3489: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3490: 	  &GDBM_READER(),0640)) {
 3491:     my $version=$hash{"version:$symb"};
 3492:     $returnhash{'version'}=$version;
 3493:     my $scope;
 3494:     for ($scope=1;$scope<=$version;$scope++) {
 3495:       my $vkeys=$hash{"$scope:keys:$symb"};
 3496:       my @keys=split(/:/,$vkeys);
 3497:       my $key;
 3498:       $returnhash{"$scope:keys"}=$vkeys;
 3499:       foreach $key (@keys) {
 3500: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3501: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3502:       }
 3503:     }
 3504:     if (!(untie(%hash))) {
 3505:       return "error:$!";
 3506:     }
 3507:   } else {
 3508:     return "error:$!";
 3509:   }
 3510:   return %returnhash;
 3511: }
 3512: 
 3513: # ----------------------------------------------------------------------- Store
 3514: 
 3515: sub store {
 3516:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3517:     my $home='';
 3518: 
 3519:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3520: 
 3521:     $symb=&symbclean($symb);
 3522:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3523: 
 3524:     if (!$domain) { $domain=$env{'user.domain'}; }
 3525:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3526: 
 3527:     &devalidate($symb,$stuname,$domain);
 3528: 
 3529:     $symb=escape($symb);
 3530:     if (!$namespace) { 
 3531:        unless ($namespace=$env{'request.course.id'}) { 
 3532:           return ''; 
 3533:        } 
 3534:     }
 3535:     if (!$home) { $home=$env{'user.home'}; }
 3536: 
 3537:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3538:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3539: 
 3540:     my $namevalue='';
 3541:     foreach my $key (keys(%$storehash)) {
 3542:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3543:     }
 3544:     $namevalue=~s/\&$//;
 3545:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3546:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3547: }
 3548: 
 3549: # -------------------------------------------------------------- Critical Store
 3550: 
 3551: sub cstore {
 3552:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3553:     my $home='';
 3554: 
 3555:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3556: 
 3557:     $symb=&symbclean($symb);
 3558:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3559: 
 3560:     if (!$domain) { $domain=$env{'user.domain'}; }
 3561:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3562: 
 3563:     &devalidate($symb,$stuname,$domain);
 3564: 
 3565:     $symb=escape($symb);
 3566:     if (!$namespace) { 
 3567:        unless ($namespace=$env{'request.course.id'}) { 
 3568:           return ''; 
 3569:        } 
 3570:     }
 3571:     if (!$home) { $home=$env{'user.home'}; }
 3572: 
 3573:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3574:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3575: 
 3576:     my $namevalue='';
 3577:     foreach my $key (keys(%$storehash)) {
 3578:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3579:     }
 3580:     $namevalue=~s/\&$//;
 3581:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3582:     return critical
 3583:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3584: }
 3585: 
 3586: # --------------------------------------------------------------------- Restore
 3587: 
 3588: sub restore {
 3589:     my ($symb,$namespace,$domain,$stuname) = @_;
 3590:     my $home='';
 3591: 
 3592:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3593: 
 3594:     if (!$symb) {
 3595:       unless ($symb=escape(&symbread())) { return ''; }
 3596:     } else {
 3597:       $symb=&escape(&symbclean($symb));
 3598:     }
 3599:     if (!$namespace) { 
 3600:        unless ($namespace=$env{'request.course.id'}) { 
 3601:           return ''; 
 3602:        } 
 3603:     }
 3604:     if (!$domain) { $domain=$env{'user.domain'}; }
 3605:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3606:     if (!$home) { $home=$env{'user.home'}; }
 3607:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3608: 
 3609:     my %returnhash=();
 3610:     foreach my $line (split(/\&/,$answer)) {
 3611: 	my ($name,$value)=split(/\=/,$line);
 3612:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3613:     }
 3614:     my $version;
 3615:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3616:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3617:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3618:        }
 3619:     }
 3620:     return %returnhash;
 3621: }
 3622: 
 3623: # ---------------------------------------------------------- Course Description
 3624: 
 3625: sub coursedescription {
 3626:     my ($courseid,$args)=@_;
 3627:     $courseid=~s/^\///;
 3628:     $courseid=~s/\_/\//g;
 3629:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3630:     my $chome=&homeserver($cnum,$cdomain);
 3631:     my $normalid=$cdomain.'_'.$cnum;
 3632:     # need to always cache even if we get errors otherwise we keep 
 3633:     # trying and trying and trying to get the course description.
 3634:     my %envhash=();
 3635:     my %returnhash=();
 3636:     
 3637:     my $expiretime=600;
 3638:     if ($env{'request.course.id'} eq $normalid) {
 3639: 	$expiretime=120;
 3640:     }
 3641: 
 3642:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3643:     if (!$args->{'freshen_cache'}
 3644: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3645: 	foreach my $key (keys(%env)) {
 3646: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3647: 	    my ($setting) = $1;
 3648: 	    $returnhash{$setting} = $env{$key};
 3649: 	}
 3650: 	return %returnhash;
 3651:     }
 3652: 
 3653:     # get the data agin
 3654:     if (!$args->{'one_time'}) {
 3655: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3656:     }
 3657: 
 3658:     if ($chome ne 'no_host') {
 3659:        %returnhash=&dump('environment',$cdomain,$cnum);
 3660:        if (!exists($returnhash{'con_lost'})) {
 3661:            $returnhash{'home'}= $chome;
 3662: 	   $returnhash{'domain'} = $cdomain;
 3663: 	   $returnhash{'num'} = $cnum;
 3664:            if (!defined($returnhash{'type'})) {
 3665:                $returnhash{'type'} = 'Course';
 3666:            }
 3667:            while (my ($name,$value) = each %returnhash) {
 3668:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3669:            }
 3670:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3671:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3672: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3673:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3674:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3675:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3676:        }
 3677:     }
 3678:     if (!$args->{'one_time'}) {
 3679: 	&appenv(\%envhash);
 3680:     }
 3681:     return %returnhash;
 3682: }
 3683: 
 3684: # -------------------------------------------------See if a user is privileged
 3685: 
 3686: sub privileged {
 3687:     my ($username,$domain)=@_;
 3688:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3689: 			&homeserver($username,$domain));
 3690:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3691:     my $now=time;
 3692:     if ($rolesdump ne '') {
 3693:         foreach my $entry (split(/&/,$rolesdump)) {
 3694: 	    if ($entry!~/^rolesdef_/) {
 3695: 		my ($area,$role)=split(/=/,$entry);
 3696: 		$area=~s/\_\w\w$//;
 3697: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3698: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3699: 		    my $active=1;
 3700: 		    if ($tend) {
 3701: 			if ($tend<$now) { $active=0; }
 3702: 		    }
 3703: 		    if ($tstart) {
 3704: 			if ($tstart>$now) { $active=0; }
 3705: 		    }
 3706: 		    if ($active) { return 1; }
 3707: 		}
 3708: 	    }
 3709: 	}
 3710:     }
 3711:     return 0;
 3712: }
 3713: 
 3714: # -------------------------------------------------------- Get user privileges
 3715: 
 3716: sub rolesinit {
 3717:     my ($domain,$username,$authhost)=@_;
 3718:     my %userroles;
 3719:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3720:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
 3721:     my %allroles=();
 3722:     my %allgroups=();   
 3723:     my $now=time;
 3724:     %userroles = ('user.login.time' => $now);
 3725:     my $group_privs;
 3726: 
 3727:     if ($rolesdump ne '') {
 3728:         foreach my $entry (split(/&/,$rolesdump)) {
 3729: 	  if ($entry!~/^rolesdef_/) {
 3730:             my ($area,$role)=split(/=/,$entry);
 3731: 	    $area=~s/\_\w\w$//;
 3732:             my ($trole,$tend,$tstart,$group_privs);
 3733: 	    if ($role=~/^cr/) { 
 3734: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3735: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3736: 		    ($tend,$tstart)=split('_',$trest);
 3737: 		} else {
 3738: 		    $trole=$role;
 3739: 		}
 3740:             } elsif ($role =~ m|^gr/|) {
 3741:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3742:                 ($trole,$group_privs) = split(/\//,$trole);
 3743:                 $group_privs = &unescape($group_privs);
 3744: 	    } else {
 3745: 		($trole,$tend,$tstart)=split(/_/,$role);
 3746: 	    }
 3747: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3748: 					 $username);
 3749: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3750:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3751:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3752:             if (($area ne '') && ($trole ne '')) {
 3753: 		my $spec=$trole.'.'.$area;
 3754: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3755: 		if ($trole =~ /^cr\//) {
 3756:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3757:                 } elsif ($trole eq 'gr') {
 3758:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3759: 		} else {
 3760:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3761: 		}
 3762:             }
 3763:           }
 3764:         }
 3765:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3766:         $userroles{'user.adv'}    = $adv;
 3767: 	$userroles{'user.author'} = $author;
 3768:         $env{'user.adv'}=$adv;
 3769:     }
 3770:     return \%userroles;  
 3771: }
 3772: 
 3773: sub set_arearole {
 3774:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3775: # log the associated role with the area
 3776:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3777:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3778: }
 3779: 
 3780: sub custom_roleprivs {
 3781:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3782:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3783:     my $homsvr=homeserver($rauthor,$rdomain);
 3784:     if (&hostname($homsvr) ne '') {
 3785:         my ($rdummy,$roledef)=
 3786:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3787:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3788:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3789:             if (defined($syspriv)) {
 3790:                 $$allroles{'cm./'}.=':'.$syspriv;
 3791:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3792:             }
 3793:             if ($tdomain ne '') {
 3794:                 if (defined($dompriv)) {
 3795:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3796:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3797:                 }
 3798:                 if (($trest ne '') && (defined($coursepriv))) {
 3799:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3800:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3801:                 }
 3802:             }
 3803:         }
 3804:     }
 3805: }
 3806: 
 3807: sub group_roleprivs {
 3808:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3809:     my $access = 1;
 3810:     my $now = time;
 3811:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3812:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3813:     if ($access) {
 3814:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3815:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3816:     }
 3817: }
 3818: 
 3819: sub standard_roleprivs {
 3820:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3821:     if (defined($pr{$trole.':s'})) {
 3822:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3823:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3824:     }
 3825:     if ($tdomain ne '') {
 3826:         if (defined($pr{$trole.':d'})) {
 3827:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3828:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3829:         }
 3830:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3831:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3832:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3833:         }
 3834:     }
 3835: }
 3836: 
 3837: sub set_userprivs {
 3838:     my ($userroles,$allroles,$allgroups) = @_; 
 3839:     my $author=0;
 3840:     my $adv=0;
 3841:     my %grouproles = ();
 3842:     if (keys(%{$allgroups}) > 0) {
 3843:         foreach my $role (keys %{$allroles}) {
 3844:             my ($trole,$area,$sec,$extendedarea);
 3845:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3846:                 $trole = $1;
 3847:                 $area = $2;
 3848:                 $sec = $3;
 3849:                 $extendedarea = $area.$sec;
 3850:                 if (exists($$allgroups{$area})) {
 3851:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3852:                         my $spec = $trole.'.'.$extendedarea;
 3853:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3854:                                                 $$allgroups{$area}{$group};
 3855:                     }
 3856:                 }
 3857:             }
 3858:         }
 3859:     }
 3860:     foreach my $group (keys(%grouproles)) {
 3861:         $$allroles{$group} = $grouproles{$group};
 3862:     }
 3863:     foreach my $role (keys(%{$allroles})) {
 3864:         my %thesepriv;
 3865:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3866:         foreach my $item (split(/:/,$$allroles{$role})) {
 3867:             if ($item ne '') {
 3868:                 my ($privilege,$restrictions)=split(/&/,$item);
 3869:                 if ($restrictions eq '') {
 3870:                     $thesepriv{$privilege}='F';
 3871:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3872:                     $thesepriv{$privilege}.=$restrictions;
 3873:                 }
 3874:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3875:             }
 3876:         }
 3877:         my $thesestr='';
 3878:         foreach my $priv (keys(%thesepriv)) {
 3879: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3880: 	}
 3881:         $userroles->{'user.priv.'.$role} = $thesestr;
 3882:     }
 3883:     return ($author,$adv);
 3884: }
 3885: 
 3886: sub role_status {
 3887:     my ($rolekey,$then,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 3888:     my @pwhere = ();
 3889:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 3890:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 3891:         unless (!defined($$role) || $$role eq '') {
 3892:             $$where=join('.',@pwhere);
 3893:             $$trolecode=$$role.'.'.$$where;
 3894:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 3895:             $$tstatus='is';
 3896:             if ($$tstart && $$tstart>$then) {
 3897:                 $$tstatus='future';
 3898:                 if ($$tstart<$now) { $$tstatus='will'; }
 3899:             }
 3900:             if ($$tend) {
 3901:                 if ($$tend<$then) {
 3902:                     $$tstatus='expired';
 3903:                 } elsif ($$tend<$now) {
 3904:                     $$tstatus='will_not';
 3905:                 }
 3906:             }
 3907:         }
 3908:     }
 3909: }
 3910: 
 3911: sub check_adhoc_privs {
 3912:     my ($cdom,$cnum,$then,$now,$checkrole) = @_;
 3913:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 3914:     if ($env{$cckey}) {
 3915:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 3916:         &role_status($cckey,$then,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 3917:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 3918:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
 3919:         }
 3920:     } else {
 3921:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
 3922:     }
 3923: }
 3924: 
 3925: sub set_adhoc_privileges {
 3926: # role can be cc or ca
 3927:     my ($dcdom,$pickedcourse,$role) = @_;
 3928:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 3929:     my $spec = $role.'.'.$area;
 3930:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 3931:                                   $env{'user.name'});
 3932:     my %ccrole = ();
 3933:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 3934:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 3935:     &appenv(\%userroles,[$role,'cm']);
 3936:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 3937:     &appenv( {'request.role'        => $spec,
 3938:               'request.role.domain' => $dcdom,
 3939:               'request.course.sec'  => ''
 3940:              }
 3941:            );
 3942:     my $tadv=0;
 3943:     if (&allowed('adv') eq 'F') { $tadv=1; }
 3944:     &appenv({'request.role.adv'    => $tadv});
 3945: }
 3946: 
 3947: # --------------------------------------------------------------- get interface
 3948: 
 3949: sub get {
 3950:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3951:    my $items='';
 3952:    foreach my $item (@$storearr) {
 3953:        $items.=&escape($item).'&';
 3954:    }
 3955:    $items=~s/\&$//;
 3956:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3957:    if (!$uname) { $uname=$env{'user.name'}; }
 3958:    my $uhome=&homeserver($uname,$udomain);
 3959: 
 3960:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3961:    my @pairs=split(/\&/,$rep);
 3962:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3963:      return @pairs;
 3964:    }
 3965:    my %returnhash=();
 3966:    my $i=0;
 3967:    foreach my $item (@$storearr) {
 3968:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3969:       $i++;
 3970:    }
 3971:    return %returnhash;
 3972: }
 3973: 
 3974: # --------------------------------------------------------------- del interface
 3975: 
 3976: sub del {
 3977:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3978:    my $items='';
 3979:    foreach my $item (@$storearr) {
 3980:        $items.=&escape($item).'&';
 3981:    }
 3982: 
 3983:    $items=~s/\&$//;
 3984:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3985:    if (!$uname) { $uname=$env{'user.name'}; }
 3986:    my $uhome=&homeserver($uname,$udomain);
 3987:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3988: }
 3989: 
 3990: # -------------------------------------------------------------- dump interface
 3991: 
 3992: sub dump {
 3993:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3994:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3995:     if (!$uname) { $uname=$env{'user.name'}; }
 3996:     my $uhome=&homeserver($uname,$udomain);
 3997:     if ($regexp) {
 3998: 	$regexp=&escape($regexp);
 3999:     } else {
 4000: 	$regexp='.';
 4001:     }
 4002:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4003:     my @pairs=split(/\&/,$rep);
 4004:     my %returnhash=();
 4005:     foreach my $item (@pairs) {
 4006: 	my ($key,$value)=split(/=/,$item,2);
 4007: 	$key = &unescape($key);
 4008: 	next if ($key =~ /^error: 2 /);
 4009: 	$returnhash{$key}=&thaw_unescape($value);
 4010:     }
 4011:     return %returnhash;
 4012: }
 4013: 
 4014: # --------------------------------------------------------- dumpstore interface
 4015: 
 4016: sub dumpstore {
 4017:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4018:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4019:    if (!$uname) { $uname=$env{'user.name'}; }
 4020:    my $uhome=&homeserver($uname,$udomain);
 4021:    if ($regexp) {
 4022:        $regexp=&escape($regexp);
 4023:    } else {
 4024:        $regexp='.';
 4025:    }
 4026:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4027:    my @pairs=split(/\&/,$rep);
 4028:    my %returnhash=();
 4029:    foreach my $item (@pairs) {
 4030:        my ($key,$value)=split(/=/,$item,2);
 4031:        next if ($key =~ /^error: 2 /);
 4032:        $returnhash{$key}=&thaw_unescape($value);
 4033:    }
 4034:    return %returnhash;
 4035: }
 4036: 
 4037: # -------------------------------------------------------------- keys interface
 4038: 
 4039: sub getkeys {
 4040:    my ($namespace,$udomain,$uname)=@_;
 4041:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4042:    if (!$uname) { $uname=$env{'user.name'}; }
 4043:    my $uhome=&homeserver($uname,$udomain);
 4044:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 4045:    my @keyarray=();
 4046:    foreach my $key (split(/\&/,$rep)) {
 4047:       next if ($key =~ /^error: 2 /);
 4048:       push(@keyarray,&unescape($key));
 4049:    }
 4050:    return @keyarray;
 4051: }
 4052: 
 4053: # --------------------------------------------------------------- currentdump
 4054: sub currentdump {
 4055:    my ($courseid,$sdom,$sname)=@_;
 4056:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 4057:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 4058:    $sname    = $env{'user.name'}         if (! defined($sname));
 4059:    my $uhome = &homeserver($sname,$sdom);
 4060:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 4061:    return if ($rep =~ /^(error:|no_such_host)/);
 4062:    #
 4063:    my %returnhash=();
 4064:    #
 4065:    if ($rep eq "unknown_cmd") { 
 4066:        # an old lond will not know currentdump
 4067:        # Do a dump and make it look like a currentdump
 4068:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 4069:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 4070:        my %hash = @tmp;
 4071:        @tmp=();
 4072:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 4073:    } else {
 4074:        my @pairs=split(/\&/,$rep);
 4075:        foreach my $pair (@pairs) {
 4076:            my ($key,$value)=split(/=/,$pair,2);
 4077:            my ($symb,$param) = split(/:/,$key);
 4078:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 4079:                                                         &thaw_unescape($value);
 4080:        }
 4081:    }
 4082:    return %returnhash;
 4083: }
 4084: 
 4085: sub convert_dump_to_currentdump{
 4086:     my %hash = %{shift()};
 4087:     my %returnhash;
 4088:     # Code ripped from lond, essentially.  The only difference
 4089:     # here is the unescaping done by lonnet::dump().  Conceivably
 4090:     # we might run in to problems with parameter names =~ /^v\./
 4091:     while (my ($key,$value) = each(%hash)) {
 4092:         my ($v,$symb,$param) = split(/:/,$key);
 4093: 	$symb  = &unescape($symb);
 4094: 	$param = &unescape($param);
 4095:         next if ($v eq 'version' || $symb eq 'keys');
 4096:         next if (exists($returnhash{$symb}) &&
 4097:                  exists($returnhash{$symb}->{$param}) &&
 4098:                  $returnhash{$symb}->{'v.'.$param} > $v);
 4099:         $returnhash{$symb}->{$param}=$value;
 4100:         $returnhash{$symb}->{'v.'.$param}=$v;
 4101:     }
 4102:     #
 4103:     # Remove all of the keys in the hashes which keep track of
 4104:     # the version of the parameter.
 4105:     while (my ($symb,$param_hash) = each(%returnhash)) {
 4106:         # use a foreach because we are going to delete from the hash.
 4107:         foreach my $key (keys(%$param_hash)) {
 4108:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 4109:         }
 4110:     }
 4111:     return \%returnhash;
 4112: }
 4113: 
 4114: # ------------------------------------------------------ critical inc interface
 4115: 
 4116: sub cinc {
 4117:     return &inc(@_,'critical');
 4118: }
 4119: 
 4120: # --------------------------------------------------------------- inc interface
 4121: 
 4122: sub inc {
 4123:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 4124:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4125:     if (!$uname) { $uname=$env{'user.name'}; }
 4126:     my $uhome=&homeserver($uname,$udomain);
 4127:     my $items='';
 4128:     if (! ref($store)) {
 4129:         # got a single value, so use that instead
 4130:         $items = &escape($store).'=&';
 4131:     } elsif (ref($store) eq 'SCALAR') {
 4132:         $items = &escape($$store).'=&';        
 4133:     } elsif (ref($store) eq 'ARRAY') {
 4134:         $items = join('=&',map {&escape($_);} @{$store});
 4135:     } elsif (ref($store) eq 'HASH') {
 4136:         while (my($key,$value) = each(%{$store})) {
 4137:             $items.= &escape($key).'='.&escape($value).'&';
 4138:         }
 4139:     }
 4140:     $items=~s/\&$//;
 4141:     if ($critical) {
 4142: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 4143:     } else {
 4144: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 4145:     }
 4146: }
 4147: 
 4148: # --------------------------------------------------------------- put interface
 4149: 
 4150: sub put {
 4151:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4152:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4153:    if (!$uname) { $uname=$env{'user.name'}; }
 4154:    my $uhome=&homeserver($uname,$udomain);
 4155:    my $items='';
 4156:    foreach my $item (keys(%$storehash)) {
 4157:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4158:    }
 4159:    $items=~s/\&$//;
 4160:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4161: }
 4162: 
 4163: # ------------------------------------------------------------ newput interface
 4164: 
 4165: sub newput {
 4166:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4167:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4168:    if (!$uname) { $uname=$env{'user.name'}; }
 4169:    my $uhome=&homeserver($uname,$udomain);
 4170:    my $items='';
 4171:    foreach my $key (keys(%$storehash)) {
 4172:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4173:    }
 4174:    $items=~s/\&$//;
 4175:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 4176: }
 4177: 
 4178: # ---------------------------------------------------------  putstore interface
 4179: 
 4180: sub putstore {
 4181:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4182:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4183:    if (!$uname) { $uname=$env{'user.name'}; }
 4184:    my $uhome=&homeserver($uname,$udomain);
 4185:    my $items='';
 4186:    foreach my $key (keys(%$storehash)) {
 4187:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 4188:    }
 4189:    $items=~s/\&$//;
 4190:    my $esc_symb=&escape($symb);
 4191:    my $esc_v=&escape($version);
 4192:    my $reply =
 4193:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 4194: 	      $uhome);
 4195:    if ($reply eq 'unknown_cmd') {
 4196:        # gfall back to way things use to be done
 4197:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 4198: 			    $uname);
 4199:    }
 4200:    return $reply;
 4201: }
 4202: 
 4203: sub old_putstore {
 4204:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4205:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4206:     if (!$uname) { $uname=$env{'user.name'}; }
 4207:     my $uhome=&homeserver($uname,$udomain);
 4208:     my %newstorehash;
 4209:     foreach my $item (keys(%$storehash)) {
 4210: 	my $key = $version.':'.&escape($symb).':'.$item;
 4211: 	$newstorehash{$key} = $storehash->{$item};
 4212:     }
 4213:     my $items='';
 4214:     my %allitems = ();
 4215:     foreach my $item (keys(%newstorehash)) {
 4216: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 4217: 	    my $key = $1.':keys:'.$2;
 4218: 	    $allitems{$key} .= $3.':';
 4219: 	}
 4220: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 4221:     }
 4222:     foreach my $item (keys(%allitems)) {
 4223: 	$allitems{$item} =~ s/\:$//;
 4224: 	$items.= $item.'='.$allitems{$item}.'&';
 4225:     }
 4226:     $items=~s/\&$//;
 4227:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4228: }
 4229: 
 4230: # ------------------------------------------------------ critical put interface
 4231: 
 4232: sub cput {
 4233:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4234:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4235:    if (!$uname) { $uname=$env{'user.name'}; }
 4236:    my $uhome=&homeserver($uname,$udomain);
 4237:    my $items='';
 4238:    foreach my $item (keys(%$storehash)) {
 4239:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4240:    }
 4241:    $items=~s/\&$//;
 4242:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 4243: }
 4244: 
 4245: # -------------------------------------------------------------- eget interface
 4246: 
 4247: sub eget {
 4248:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4249:    my $items='';
 4250:    foreach my $item (@$storearr) {
 4251:        $items.=&escape($item).'&';
 4252:    }
 4253:    $items=~s/\&$//;
 4254:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4255:    if (!$uname) { $uname=$env{'user.name'}; }
 4256:    my $uhome=&homeserver($uname,$udomain);
 4257:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 4258:    my @pairs=split(/\&/,$rep);
 4259:    my %returnhash=();
 4260:    my $i=0;
 4261:    foreach my $item (@$storearr) {
 4262:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4263:       $i++;
 4264:    }
 4265:    return %returnhash;
 4266: }
 4267: 
 4268: # ------------------------------------------------------------ tmpput interface
 4269: sub tmpput {
 4270:     my ($storehash,$server,$context)=@_;
 4271:     my $items='';
 4272:     foreach my $item (keys(%$storehash)) {
 4273: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4274:     }
 4275:     $items=~s/\&$//;
 4276:     if (defined($context)) {
 4277:         $items .= ':'.&escape($context);
 4278:     }
 4279:     return &reply("tmpput:$items",$server);
 4280: }
 4281: 
 4282: # ------------------------------------------------------------ tmpget interface
 4283: sub tmpget {
 4284:     my ($token,$server)=@_;
 4285:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4286:     my $rep=&reply("tmpget:$token",$server);
 4287:     my %returnhash;
 4288:     foreach my $item (split(/\&/,$rep)) {
 4289: 	my ($key,$value)=split(/=/,$item);
 4290:         next if ($key =~ /^error: 2 /);
 4291: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 4292:     }
 4293:     return %returnhash;
 4294: }
 4295: 
 4296: # ------------------------------------------------------------ tmpget interface
 4297: sub tmpdel {
 4298:     my ($token,$server)=@_;
 4299:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4300:     return &reply("tmpdel:$token",$server);
 4301: }
 4302: 
 4303: # -------------------------------------------------- portfolio access checking
 4304: 
 4305: sub portfolio_access {
 4306:     my ($requrl) = @_;
 4307:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4308:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4309:     if ($result) {
 4310:         my %setters;
 4311:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4312:             my ($startblock,$endblock) =
 4313:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4314:             if ($startblock && $endblock) {
 4315:                 return 'B';
 4316:             }
 4317:         } else {
 4318:             my ($startblock,$endblock) =
 4319:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4320:             if ($startblock && $endblock) {
 4321:                 return 'B';
 4322:             }
 4323:         }
 4324:     }
 4325:     if ($result eq 'ok') {
 4326:        return 'F';
 4327:     } elsif ($result =~ /^[^:]+:guest_/) {
 4328:        return 'A';
 4329:     }
 4330:     return '';
 4331: }
 4332: 
 4333: sub get_portfolio_access {
 4334:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4335: 
 4336:     if (!ref($access_hash)) {
 4337: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4338: 	my %access_controls = &get_access_controls($current_perms,$group,
 4339: 						   $file_name);
 4340: 	$access_hash = $access_controls{$file_name};
 4341:     }
 4342: 
 4343:     my ($public,$guest,@domains,@users,@courses,@groups);
 4344:     my $now = time;
 4345:     if (ref($access_hash) eq 'HASH') {
 4346:         foreach my $key (keys(%{$access_hash})) {
 4347:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4348:             if ($start > $now) {
 4349:                 next;
 4350:             }
 4351:             if ($end && $end<$now) {
 4352:                 next;
 4353:             }
 4354:             if ($scope eq 'public') {
 4355:                 $public = $key;
 4356:                 last;
 4357:             } elsif ($scope eq 'guest') {
 4358:                 $guest = $key;
 4359:             } elsif ($scope eq 'domains') {
 4360:                 push(@domains,$key);
 4361:             } elsif ($scope eq 'users') {
 4362:                 push(@users,$key);
 4363:             } elsif ($scope eq 'course') {
 4364:                 push(@courses,$key);
 4365:             } elsif ($scope eq 'group') {
 4366:                 push(@groups,$key);
 4367:             }
 4368:         }
 4369:         if ($public) {
 4370:             return 'ok';
 4371:         }
 4372:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4373:             if ($guest) {
 4374:                 return $guest;
 4375:             }
 4376:         } else {
 4377:             if (@domains > 0) {
 4378:                 foreach my $domkey (@domains) {
 4379:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4380:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4381:                             return 'ok';
 4382:                         }
 4383:                     }
 4384:                 }
 4385:             }
 4386:             if (@users > 0) {
 4387:                 foreach my $userkey (@users) {
 4388:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4389:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4390:                             if (ref($item) eq 'HASH') {
 4391:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4392:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4393:                                     return 'ok';
 4394:                                 }
 4395:                             }
 4396:                         }
 4397:                     } 
 4398:                 }
 4399:             }
 4400:             my %roleshash;
 4401:             my @courses_and_groups = @courses;
 4402:             push(@courses_and_groups,@groups); 
 4403:             if (@courses_and_groups > 0) {
 4404:                 my (%allgroups,%allroles); 
 4405:                 my ($start,$end,$role,$sec,$group);
 4406:                 foreach my $envkey (%env) {
 4407:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4408:                         my $cid = $2.'_'.$3; 
 4409:                         if ($1 eq 'gr') {
 4410:                             $group = $4;
 4411:                             $allgroups{$cid}{$group} = $env{$envkey};
 4412:                         } else {
 4413:                             if ($4 eq '') {
 4414:                                 $sec = 'none';
 4415:                             } else {
 4416:                                 $sec = $4;
 4417:                             }
 4418:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4419:                         }
 4420:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4421:                         my $cid = $2.'_'.$3;
 4422:                         if ($4 eq '') {
 4423:                             $sec = 'none';
 4424:                         } else {
 4425:                             $sec = $4;
 4426:                         }
 4427:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4428:                     }
 4429:                 }
 4430:                 if (keys(%allroles) == 0) {
 4431:                     return;
 4432:                 }
 4433:                 foreach my $key (@courses_and_groups) {
 4434:                     my %content = %{$$access_hash{$key}};
 4435:                     my $cnum = $content{'number'};
 4436:                     my $cdom = $content{'domain'};
 4437:                     my $cid = $cdom.'_'.$cnum;
 4438:                     if (!exists($allroles{$cid})) {
 4439:                         next;
 4440:                     }    
 4441:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4442:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4443:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4444:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4445:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4446:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4447:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4448:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4449:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4450:                                         if (grep/^all$/,@sections) {
 4451:                                             return 'ok';
 4452:                                         } else {
 4453:                                             if (grep/^$sec$/,@sections) {
 4454:                                                 return 'ok';
 4455:                                             }
 4456:                                         }
 4457:                                     }
 4458:                                 }
 4459:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4460:                                     if (grep/^none$/,@groups) {
 4461:                                         return 'ok';
 4462:                                     }
 4463:                                 } else {
 4464:                                     if (grep/^all$/,@groups) {
 4465:                                         return 'ok';
 4466:                                     } 
 4467:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4468:                                         if (grep/^$group$/,@groups) {
 4469:                                             return 'ok';
 4470:                                         }
 4471:                                     }
 4472:                                 } 
 4473:                             }
 4474:                         }
 4475:                     }
 4476:                 }
 4477:             }
 4478:             if ($guest) {
 4479:                 return $guest;
 4480:             }
 4481:         }
 4482:     }
 4483:     return;
 4484: }
 4485: 
 4486: sub course_group_datechecker {
 4487:     my ($dates,$now,$status) = @_;
 4488:     my ($start,$end) = split(/\./,$dates);
 4489:     if (!$start && !$end) {
 4490:         return 'ok';
 4491:     }
 4492:     if (grep/^active$/,@{$status}) {
 4493:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4494:             return 'ok';
 4495:         }
 4496:     }
 4497:     if (grep/^previous$/,@{$status}) {
 4498:         if ($end > $now ) {
 4499:             return 'ok';
 4500:         }
 4501:     }
 4502:     if (grep/^future$/,@{$status}) {
 4503:         if ($start > $now) {
 4504:             return 'ok';
 4505:         }
 4506:     }
 4507:     return; 
 4508: }
 4509: 
 4510: sub parse_portfolio_url {
 4511:     my ($url) = @_;
 4512: 
 4513:     my ($type,$udom,$unum,$group,$file_name);
 4514:     
 4515:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4516: 	$type = 1;
 4517:         $udom = $1;
 4518:         $unum = $2;
 4519:         $file_name = $3;
 4520:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4521: 	$type = 2;
 4522:         $udom = $1;
 4523:         $unum = $2;
 4524:         $group = $3;
 4525:         $file_name = $3.'/'.$4;
 4526:     }
 4527:     if (wantarray) {
 4528: 	return ($type,$udom,$unum,$file_name,$group);
 4529:     }
 4530:     return $type;
 4531: }
 4532: 
 4533: sub is_portfolio_url {
 4534:     my ($url) = @_;
 4535:     return scalar(&parse_portfolio_url($url));
 4536: }
 4537: 
 4538: sub is_portfolio_file {
 4539:     my ($file) = @_;
 4540:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4541:         return 1;
 4542:     }
 4543:     return;
 4544: }
 4545: 
 4546: sub usertools_access {
 4547:     my ($uname,$udom,$tool,$action,$context) = @_;
 4548:     my ($access,%tools);
 4549:     if ($context eq '') {
 4550:         $context = 'tools';
 4551:     }
 4552:     if ($context eq 'requestcourses') {
 4553:         %tools = (
 4554:                       official   => 1,
 4555:                       unofficial => 1,
 4556:                  );
 4557:     } else {
 4558:         %tools = (
 4559:                       aboutme   => 1,
 4560:                       blog      => 1,
 4561:                       portfolio => 1,
 4562:                  );
 4563:     }
 4564:     return if (!defined($tools{$tool}));
 4565: 
 4566:     if ((!defined($udom)) || (!defined($uname))) {
 4567:         $udom = $env{'user.domain'};
 4568:         $uname = $env{'user.name'};
 4569:     }
 4570: 
 4571:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4572:         if ($action ne 'reload') {
 4573:             if ($context eq 'requestcourses') {
 4574:                 return $env{'environment.canrequest.'.$tool};
 4575:             } else {
 4576:                 return $env{'environment.availabletools.'.$tool};
 4577:             }
 4578:         }
 4579:     }
 4580: 
 4581:     my ($toolstatus,$inststatus);
 4582: 
 4583:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 4584:          ($action ne 'reload')) {
 4585:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 4586:         $inststatus = $env{'environment.inststatus'};
 4587:     } else {
 4588:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool);
 4589:         $toolstatus = $userenv{$context.'.'.$tool};
 4590:         $inststatus = $userenv{'inststatus'};
 4591:     }
 4592: 
 4593:     if ($toolstatus ne '') {
 4594:         if ($toolstatus) {
 4595:             $access = 1;
 4596:         } else {
 4597:             $access = 0;
 4598:         }
 4599:         return $access;
 4600:     }
 4601: 
 4602:     my $is_adv = &is_advanced_user($udom,$uname);
 4603:     my %domdef = &get_domain_defaults($udom);
 4604:     if (ref($domdef{$tool}) eq 'HASH') {
 4605:         if ($is_adv) {
 4606:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 4607:                 if ($domdef{$tool}{'_LC_adv'}) { 
 4608:                     $access = 1;
 4609:                 } else {
 4610:                     $access = 0;
 4611:                 }
 4612:                 return $access;
 4613:             }
 4614:         }
 4615:         if ($inststatus ne '') {
 4616:             my ($hasaccess,$hasnoaccess);
 4617:             foreach my $affiliation (split(/:/,$inststatus)) {
 4618:                 if ($domdef{$tool}{$affiliation} ne '') { 
 4619:                     if ($domdef{$tool}{$affiliation}) {
 4620:                         $hasaccess = 1;
 4621:                     } else {
 4622:                         $hasnoaccess = 1;
 4623:                     }
 4624:                 }
 4625:             }
 4626:             if ($hasaccess || $hasnoaccess) {
 4627:                 if ($hasaccess) {
 4628:                     $access = 1;
 4629:                 } elsif ($hasnoaccess) {
 4630:                     $access = 0; 
 4631:                 }
 4632:                 return $access;
 4633:             }
 4634:         } else {
 4635:             if ($domdef{$tool}{'default'} ne '') {
 4636:                 if ($domdef{$tool}{'default'}) {
 4637:                     $access = 1;
 4638:                 } elsif ($domdef{$tool}{'default'} == 0) {
 4639:                     $access = 0;
 4640:                 }
 4641:                 return $access;
 4642:             }
 4643:         }
 4644:     } else {
 4645:         if ($context eq 'tools') {
 4646:             $access = 1;
 4647:         } else {
 4648:             $access = 0;
 4649:         }
 4650:         return $access;
 4651:     }
 4652: }
 4653: 
 4654: sub is_advanced_user {
 4655:     my ($udom,$uname) = @_;
 4656:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 4657:     my %allroles;
 4658:     my $is_adv;
 4659:     foreach my $role (keys(%roleshash)) {
 4660:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 4661:         my $area = '/'.$tdomain.'/'.$trest;
 4662:         if ($sec ne '') {
 4663:             $area .= '/'.$sec;
 4664:         }
 4665:         if (($area ne '') && ($trole ne '')) {
 4666:             my $spec=$trole.'.'.$area;
 4667:             if ($trole =~ /^cr\//) {
 4668:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4669:             } elsif ($trole ne 'gr') {
 4670:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4671:             }
 4672:         }
 4673:     }
 4674:     foreach my $role (keys(%allroles)) {
 4675:         last if ($is_adv);
 4676:         foreach my $item (split(/:/,$allroles{$role})) {
 4677:             if ($item ne '') {
 4678:                 my ($privilege,$restrictions)=split(/&/,$item);
 4679:                 if ($privilege eq 'adv') {
 4680:                     $is_adv = 1;
 4681:                     last;
 4682:                 }
 4683:             }
 4684:         }
 4685:     }
 4686:     return $is_adv;
 4687: }
 4688: 
 4689: # ---------------------------------------------- Custom access rule evaluation
 4690: 
 4691: sub customaccess {
 4692:     my ($priv,$uri)=@_;
 4693:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4694:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4695:     $udom = &LONCAPA::clean_domain($udom);
 4696:     $ucrs = &LONCAPA::clean_username($ucrs);
 4697:     my $access=0;
 4698:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4699: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4700: 	if ($type eq 'user') {
 4701: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4702: 		my ($tdom,$tuname)=split(m{/},$scope);
 4703: 		if ($tdom) {
 4704: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4705: 		}
 4706: 		if ($tuname) {
 4707: 		    if ($tuname ne $env{'user.name'}) { next; }
 4708: 		}
 4709: 		$access=($effect eq 'allow');
 4710: 		last;
 4711: 	    }
 4712: 	} else {
 4713: 	    if ($role) {
 4714: 		if ($role ne $urole) { next; }
 4715: 	    }
 4716: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4717: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4718: 		if ($tdom) {
 4719: 		    if ($tdom ne $udom) { next; }
 4720: 		}
 4721: 		if ($tcrs) {
 4722: 		    if ($tcrs ne $ucrs) { next; }
 4723: 		}
 4724: 		if ($tsec) {
 4725: 		    if ($tsec ne $usec) { next; }
 4726: 		}
 4727: 		$access=($effect eq 'allow');
 4728: 		last;
 4729: 	    }
 4730: 	    if ($realm eq '' && $role eq '') {
 4731: 		$access=($effect eq 'allow');
 4732: 	    }
 4733: 	}
 4734:     }
 4735:     return $access;
 4736: }
 4737: 
 4738: # ------------------------------------------------- Check for a user privilege
 4739: 
 4740: sub allowed {
 4741:     my ($priv,$uri,$symb,$role)=@_;
 4742:     my $ver_orguri=$uri;
 4743:     $uri=&deversion($uri);
 4744:     my $orguri=$uri;
 4745:     $uri=&declutter($uri);
 4746: 
 4747:     if ($priv eq 'evb') {
 4748: # Evade communication block restrictions for specified role in a course
 4749:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4750:             return $1;
 4751:         } else {
 4752:             return;
 4753:         }
 4754:     }
 4755: 
 4756:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4757: # Free bre access to adm and meta resources
 4758:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4759: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4760: 	&& ($priv eq 'bre')) {
 4761: 	return 'F';
 4762:     }
 4763: 
 4764: # Free bre access to user's own portfolio contents
 4765:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4766:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4767: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4768:         my %setters;
 4769:         my ($startblock,$endblock) = 
 4770:             &Apache::loncommon::blockcheck(\%setters,'port');
 4771:         if ($startblock && $endblock) {
 4772:             return 'B';
 4773:         } else {
 4774:             return 'F';
 4775:         }
 4776:     }
 4777: 
 4778: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4779:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4780:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4781:         if (exists($env{'request.course.id'})) {
 4782:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4783:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4784:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4785:                 my $courseprivid=$env{'request.course.id'};
 4786:                 $courseprivid=~s/\_/\//;
 4787:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4788:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4789:                     return $1; 
 4790:                 } else {
 4791:                     if ($env{'request.course.sec'}) {
 4792:                         $courseprivid.='/'.$env{'request.course.sec'};
 4793:                     }
 4794:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4795:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4796:                         return $2;
 4797:                     }
 4798:                 }
 4799:             }
 4800:         }
 4801:     }
 4802: 
 4803: # Free bre to public access
 4804: 
 4805:     if ($priv eq 'bre') {
 4806:         my $copyright=&metadata($uri,'copyright');
 4807: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4808:            return 'F'; 
 4809:         }
 4810:         if ($copyright eq 'priv') {
 4811:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4812: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4813: 		return '';
 4814:             }
 4815:         }
 4816:         if ($copyright eq 'domain') {
 4817:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4818: 	    unless (($env{'user.domain'} eq $1) ||
 4819:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4820: 		return '';
 4821:             }
 4822:         }
 4823:         if ($env{'request.role'}=~ /li\.\//) {
 4824:             # Library role, so allow browsing of resources in this domain.
 4825:             return 'F';
 4826:         }
 4827:         if ($copyright eq 'custom') {
 4828: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4829:         }
 4830:     }
 4831:     # Domain coordinator is trying to create a course
 4832:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4833:         # uri is the requested domain in this case.
 4834:         # comparison to 'request.role.domain' shows if the user has selected
 4835:         # a role of dc for the domain in question.
 4836:         return 'F' if ($uri eq $env{'request.role.domain'});
 4837:     }
 4838: 
 4839:     my $thisallowed='';
 4840:     my $statecond=0;
 4841:     my $courseprivid='';
 4842: 
 4843: # Course
 4844: 
 4845:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4846:        $thisallowed.=$1;
 4847:     }
 4848: 
 4849: # Domain
 4850: 
 4851:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4852:        =~/\Q$priv\E\&([^\:]*)/) {
 4853:        $thisallowed.=$1;
 4854:     }
 4855: 
 4856: # Course: uri itself is a course
 4857:     my $courseuri=$uri;
 4858:     $courseuri=~s/\_(\d)/\/$1/;
 4859:     $courseuri=~s/^([^\/])/\/$1/;
 4860: 
 4861:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 4862:        =~/\Q$priv\E\&([^\:]*)/) {
 4863:        $thisallowed.=$1;
 4864:     }
 4865: 
 4866: # URI is an uploaded document for this course, default permissions don't matter
 4867: # not allowing 'edit' access (editupload) to uploaded course docs
 4868:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 4869: 	$thisallowed='';
 4870:         my ($match)=&is_on_map($uri);
 4871:         if ($match) {
 4872:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 4873:                   =~/\Q$priv\E\&([^\:]*)/) {
 4874:                 $thisallowed.=$1;
 4875:             }
 4876:         } else {
 4877:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 4878:             if ($refuri) {
 4879:                 if ($refuri =~ m|^/adm/|) {
 4880:                     $thisallowed='F';
 4881:                 } else {
 4882:                     $refuri=&declutter($refuri);
 4883:                     my ($match) = &is_on_map($refuri);
 4884:                     if ($match) {
 4885:                         $thisallowed='F';
 4886:                     }
 4887:                 }
 4888:             }
 4889:         }
 4890:     }
 4891: 
 4892:     if ($priv eq 'bre'
 4893: 	&& $thisallowed ne 'F' 
 4894: 	&& $thisallowed ne '2'
 4895: 	&& &is_portfolio_url($uri)) {
 4896: 	$thisallowed = &portfolio_access($uri);
 4897:     }
 4898:     
 4899: # Full access at system, domain or course-wide level? Exit.
 4900:     if ($thisallowed=~/F/) {
 4901: 	return 'F';
 4902:     }
 4903: 
 4904: # If this is generating or modifying users, exit with special codes
 4905: 
 4906:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4907: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4908: 	    my ($audom,$auname)=split('/',$uri);
 4909: # no author name given, so this just checks on the general right to make a co-author in this domain
 4910: 	    unless ($auname) { return $thisallowed; }
 4911: # an author name is given, so we are about to actually make a co-author for a certain account
 4912: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4913: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 4914: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 4915: 	}
 4916: 	return $thisallowed;
 4917:     }
 4918: #
 4919: # Gathered so far: system, domain and course wide privileges
 4920: #
 4921: # Course: See if uri or referer is an individual resource that is part of 
 4922: # the course
 4923: 
 4924:     if ($env{'request.course.id'}) {
 4925: 
 4926:        $courseprivid=$env{'request.course.id'};
 4927:        if ($env{'request.course.sec'}) {
 4928:           $courseprivid.='/'.$env{'request.course.sec'};
 4929:        }
 4930:        $courseprivid=~s/\_/\//;
 4931:        my $checkreferer=1;
 4932:        my ($match,$cond)=&is_on_map($uri);
 4933:        if ($match) {
 4934:            $statecond=$cond;
 4935:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4936:                =~/\Q$priv\E\&([^\:]*)/) {
 4937:                $thisallowed.=$1;
 4938:                $checkreferer=0;
 4939:            }
 4940:        }
 4941:        
 4942:        if ($checkreferer) {
 4943: 	  my $refuri=$env{'httpref.'.$orguri};
 4944:             unless ($refuri) {
 4945:                 foreach my $key (keys(%env)) {
 4946: 		    if ($key=~/^httpref\..*\*/) {
 4947: 			my $pattern=$key;
 4948:                         $pattern=~s/^httpref\.\/res\///;
 4949:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4950:                         $pattern=~s/\//\\\//g;
 4951:                         if ($orguri=~/$pattern/) {
 4952: 			    $refuri=$env{$key};
 4953:                         }
 4954:                     }
 4955:                 }
 4956:             }
 4957: 
 4958:          if ($refuri) { 
 4959: 	  $refuri=&declutter($refuri);
 4960:           my ($match,$cond)=&is_on_map($refuri);
 4961:             if ($match) {
 4962:               my $refstatecond=$cond;
 4963:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4964:                   =~/\Q$priv\E\&([^\:]*)/) {
 4965:                   $thisallowed.=$1;
 4966:                   $uri=$refuri;
 4967:                   $statecond=$refstatecond;
 4968:               }
 4969:           }
 4970:         }
 4971:        }
 4972:    }
 4973: 
 4974: #
 4975: # Gathered now: all privileges that could apply, and condition number
 4976: # 
 4977: #
 4978: # Full or no access?
 4979: #
 4980: 
 4981:     if ($thisallowed=~/F/) {
 4982: 	return 'F';
 4983:     }
 4984: 
 4985:     unless ($thisallowed) {
 4986:         return '';
 4987:     }
 4988: 
 4989: # Restrictions exist, deal with them
 4990: #
 4991: #   C:according to course preferences
 4992: #   R:according to resource settings
 4993: #   L:unless locked
 4994: #   X:according to user session state
 4995: #
 4996: 
 4997: # Possibly locked functionality, check all courses
 4998: # Locks might take effect only after 10 minutes cache expiration for other
 4999: # courses, and 2 minutes for current course
 5000: 
 5001:     my $envkey;
 5002:     if ($thisallowed=~/L/) {
 5003:         foreach $envkey (keys %env) {
 5004:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 5005:                my $courseid=$2;
 5006:                my $roleid=$1.'.'.$2;
 5007:                $courseid=~s/^\///;
 5008:                my $expiretime=600;
 5009:                if ($env{'request.role'} eq $roleid) {
 5010: 		  $expiretime=120;
 5011:                }
 5012: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 5013:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 5014:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 5015: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 5016:                }
 5017:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5018:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 5019: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 5020:                        &log($env{'user.domain'},$env{'user.name'},
 5021:                             $env{'user.home'},
 5022:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 5023:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5024:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5025: 		       return '';
 5026:                    }
 5027:                }
 5028:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5029:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 5030: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 5031:                        &log($env{'user.domain'},$env{'user.name'},
 5032:                             $env{'user.home'},
 5033:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 5034:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5035:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5036: 		       return '';
 5037:                    }
 5038:                }
 5039: 	   }
 5040:        }
 5041:     }
 5042:    
 5043: #
 5044: # Rest of the restrictions depend on selected course
 5045: #
 5046: 
 5047:     unless ($env{'request.course.id'}) {
 5048: 	if ($thisallowed eq 'A') {
 5049: 	    return 'A';
 5050:         } elsif ($thisallowed eq 'B') {
 5051:             return 'B';
 5052: 	} else {
 5053: 	    return '1';
 5054: 	}
 5055:     }
 5056: 
 5057: #
 5058: # Now user is definitely in a course
 5059: #
 5060: 
 5061: 
 5062: # Course preferences
 5063: 
 5064:    if ($thisallowed=~/C/) {
 5065:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5066:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 5067:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 5068: 	   =~/\Q$rolecode\E/) {
 5069: 	   if ($priv ne 'pch') { 
 5070: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5071: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 5072: 			$env{'request.course.id'});
 5073: 	   }
 5074:            return '';
 5075:        }
 5076: 
 5077:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 5078: 	   =~/\Q$unamedom\E/) {
 5079: 	   if ($priv ne 'pch') { 
 5080: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 5081: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 5082: 			$env{'request.course.id'});
 5083: 	   }
 5084:            return '';
 5085:        }
 5086:    }
 5087: 
 5088: # Resource preferences
 5089: 
 5090:    if ($thisallowed=~/R/) {
 5091:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5092:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 5093: 	   if ($priv ne 'pch') { 
 5094: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5095: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 5096: 	   }
 5097: 	   return '';
 5098:        }
 5099:    }
 5100: 
 5101: # Restricted by state or randomout?
 5102: 
 5103:    if ($thisallowed=~/X/) {
 5104:       if ($env{'acc.randomout'}) {
 5105: 	 if (!$symb) { $symb=&symbread($uri,1); }
 5106:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 5107:             return ''; 
 5108:          }
 5109:       }
 5110:       if (&condval($statecond)) {
 5111: 	 return '2';
 5112:       } else {
 5113:          return '';
 5114:       }
 5115:    }
 5116: 
 5117:     if ($thisallowed eq 'A') {
 5118: 	return 'A';
 5119:     } elsif ($thisallowed eq 'B') {
 5120:         return 'B';
 5121:     }
 5122:    return 'F';
 5123: }
 5124: 
 5125: sub split_uri_for_cond {
 5126:     my $uri=&deversion(&declutter(shift));
 5127:     my @uriparts=split(/\//,$uri);
 5128:     my $filename=pop(@uriparts);
 5129:     my $pathname=join('/',@uriparts);
 5130:     return ($pathname,$filename);
 5131: }
 5132: # --------------------------------------------------- Is a resource on the map?
 5133: 
 5134: sub is_on_map {
 5135:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 5136:     #Trying to find the conditional for the file
 5137:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 5138: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 5139:     if ($match) {
 5140: 	return (1,$1);
 5141:     } else {
 5142: 	return (0,0);
 5143:     }
 5144: }
 5145: 
 5146: # --------------------------------------------------------- Get symb from alias
 5147: 
 5148: sub get_symb_from_alias {
 5149:     my $symb=shift;
 5150:     my ($map,$resid,$url)=&decode_symb($symb);
 5151: # Already is a symb
 5152:     if ($url) { return $symb; }
 5153: # Must be an alias
 5154:     my $aliassymb='';
 5155:     my %bighash;
 5156:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5157:                             &GDBM_READER(),0640)) {
 5158:         my $rid=$bighash{'mapalias_'.$symb};
 5159: 	if ($rid) {
 5160: 	    my ($mapid,$resid)=split(/\./,$rid);
 5161: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 5162: 				    $resid,$bighash{'src_'.$rid});
 5163: 	}
 5164:         untie %bighash;
 5165:     }
 5166:     return $aliassymb;
 5167: }
 5168: 
 5169: # ----------------------------------------------------------------- Define Role
 5170: 
 5171: sub definerole {
 5172:   if (allowed('mcr','/')) {
 5173:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 5174:     foreach my $role (split(':',$sysrole)) {
 5175: 	my ($crole,$cqual)=split(/\&/,$role);
 5176:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 5177:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 5178: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5179:                return "refused:s:$crole&$cqual"; 
 5180:             }
 5181:         }
 5182:     }
 5183:     foreach my $role (split(':',$domrole)) {
 5184: 	my ($crole,$cqual)=split(/\&/,$role);
 5185:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 5186:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 5187: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 5188:                return "refused:d:$crole&$cqual"; 
 5189:             }
 5190:         }
 5191:     }
 5192:     foreach my $role (split(':',$courole)) {
 5193: 	my ($crole,$cqual)=split(/\&/,$role);
 5194:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 5195:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 5196: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5197:                return "refused:c:$crole&$cqual"; 
 5198:             }
 5199:         }
 5200:     }
 5201:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5202:                 "$env{'user.domain'}:$env{'user.name'}:".
 5203: 	        "rolesdef_$rolename=".
 5204:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 5205:     return reply($command,$env{'user.home'});
 5206:   } else {
 5207:     return 'refused';
 5208:   }
 5209: }
 5210: 
 5211: # ---------------- Make a metadata query against the network of library servers
 5212: 
 5213: sub metadata_query {
 5214:     my ($query,$custom,$customshow,$server_array)=@_;
 5215:     my %rhash;
 5216:     my %libserv = &all_library();
 5217:     my @server_list = (defined($server_array) ? @$server_array
 5218:                                               : keys(%libserv) );
 5219:     for my $server (@server_list) {
 5220: 	unless ($custom or $customshow) {
 5221: 	    my $reply=&reply("querysend:".&escape($query),$server);
 5222: 	    $rhash{$server}=$reply;
 5223: 	}
 5224: 	else {
 5225: 	    my $reply=&reply("querysend:".&escape($query).':'.
 5226: 			     &escape($custom).':'.&escape($customshow),
 5227: 			     $server);
 5228: 	    $rhash{$server}=$reply;
 5229: 	}
 5230:     }
 5231:     return \%rhash;
 5232: }
 5233: 
 5234: # ----------------------------------------- Send log queries and wait for reply
 5235: 
 5236: sub log_query {
 5237:     my ($uname,$udom,$query,%filters)=@_;
 5238:     my $uhome=&homeserver($uname,$udom);
 5239:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 5240:     my $uhost=&hostname($uhome);
 5241:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 5242:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 5243:                        $uhome);
 5244:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 5245:     return get_query_reply($queryid);
 5246: }
 5247: 
 5248: # -------------------------- Update MySQL table for portfolio file
 5249: 
 5250: sub update_portfolio_table {
 5251:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 5252:     if ($group ne '') {
 5253:         $file_name =~s /^\Q$group\E//;
 5254:     }
 5255:     my $homeserver = &homeserver($uname,$udom);
 5256:     my $queryid=
 5257:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 5258:                ':'.&escape($file_name).':'.$action,$homeserver);
 5259:     my $reply = &get_query_reply($queryid);
 5260:     return $reply;
 5261: }
 5262: 
 5263: # -------------------------- Update MySQL allusers table
 5264: 
 5265: sub update_allusers_table {
 5266:     my ($uname,$udom,$names) = @_;
 5267:     my $homeserver = &homeserver($uname,$udom);
 5268:     my $queryid=
 5269:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 5270:                'lastname='.&escape($names->{'lastname'}).'%%'.
 5271:                'firstname='.&escape($names->{'firstname'}).'%%'.
 5272:                'middlename='.&escape($names->{'middlename'}).'%%'.
 5273:                'generation='.&escape($names->{'generation'}).'%%'.
 5274:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 5275:                'id='.&escape($names->{'id'}),$homeserver);
 5276:     my $reply = &get_query_reply($queryid);
 5277:     return $reply;
 5278: }
 5279: 
 5280: # ------- Request retrieval of institutional classlists for course(s)
 5281: 
 5282: sub fetch_enrollment_query {
 5283:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 5284:     my $homeserver;
 5285:     my $maxtries = 1;
 5286:     if ($context eq 'automated') {
 5287:         $homeserver = $perlvar{'lonHostID'};
 5288:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 5289:     } else {
 5290:         $homeserver = &homeserver($cnum,$dom);
 5291:     }
 5292:     my $host=&hostname($homeserver);
 5293:     my $cmd = '';
 5294:     foreach my $affiliate (keys %{$affiliatesref}) {
 5295:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5296:     }
 5297:     $cmd =~ s/%%$//;
 5298:     $cmd = &escape($cmd);
 5299:     my $query = 'fetchenrollment';
 5300:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 5301:     unless ($queryid=~/^\Q$host\E\_/) { 
 5302:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 5303:         return 'error: '.$queryid;
 5304:     }
 5305:     my $reply = &get_query_reply($queryid);
 5306:     my $tries = 1;
 5307:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5308:         $reply = &get_query_reply($queryid);
 5309:         $tries ++;
 5310:     }
 5311:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5312:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5313:     } else {
 5314:         my @responses = split(/:/,$reply);
 5315:         if ($homeserver eq $perlvar{'lonHostID'}) {
 5316:             foreach my $line (@responses) {
 5317:                 my ($key,$value) = split(/=/,$line,2);
 5318:                 $$replyref{$key} = $value;
 5319:             }
 5320:         } else {
 5321:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 5322:             foreach my $line (@responses) {
 5323:                 my ($key,$value) = split(/=/,$line);
 5324:                 $$replyref{$key} = $value;
 5325:                 if ($value > 0) {
 5326:                     foreach my $item (@{$$affiliatesref{$key}}) {
 5327:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 5328:                         my $destname = $pathname.'/'.$filename;
 5329:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 5330:                         if ($xml_classlist =~ /^error/) {
 5331:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 5332:                         } else {
 5333:                             if ( open(FILE,">$destname") ) {
 5334:                                 print FILE &unescape($xml_classlist);
 5335:                                 close(FILE);
 5336:                             } else {
 5337:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 5338:                             }
 5339:                         }
 5340:                     }
 5341:                 }
 5342:             }
 5343:         }
 5344:         return 'ok';
 5345:     }
 5346:     return 'error';
 5347: }
 5348: 
 5349: sub get_query_reply {
 5350:     my $queryid=shift;
 5351:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 5352:     my $reply='';
 5353:     for (1..100) {
 5354: 	sleep 2;
 5355:         if (-e $replyfile.'.end') {
 5356: 	    if (open(my $fh,$replyfile)) {
 5357: 		$reply = join('',<$fh>);
 5358: 		close($fh);
 5359: 	   } else { return 'error: reply_file_error'; }
 5360:            return &unescape($reply);
 5361: 	}
 5362:     }
 5363:     return 'timeout:'.$queryid;
 5364: }
 5365: 
 5366: sub courselog_query {
 5367: #
 5368: # possible filters:
 5369: # url: url or symb
 5370: # username
 5371: # domain
 5372: # action: view, submit, grade
 5373: # start: timestamp
 5374: # end: timestamp
 5375: #
 5376:     my (%filters)=@_;
 5377:     unless ($env{'request.course.id'}) { return 'no_course'; }
 5378:     if ($filters{'url'}) {
 5379: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 5380:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 5381:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 5382:     }
 5383:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5384:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5385:     return &log_query($cname,$cdom,'courselog',%filters);
 5386: }
 5387: 
 5388: sub userlog_query {
 5389: #
 5390: # possible filters:
 5391: # action: log check role
 5392: # start: timestamp
 5393: # end: timestamp
 5394: #
 5395:     my ($uname,$udom,%filters)=@_;
 5396:     return &log_query($uname,$udom,'userlog',%filters);
 5397: }
 5398: 
 5399: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 5400: 
 5401: sub auto_run {
 5402:     my ($cnum,$cdom) = @_;
 5403:     my $response = 0;
 5404:     my $settings;
 5405:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 5406:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5407:         $settings = $domconfig{'autoenroll'};
 5408:         if ($settings->{'run'} eq '1') {
 5409:             $response = 1;
 5410:         }
 5411:     } else {
 5412:         my $homeserver;
 5413:         if (&is_course($cdom,$cnum)) {
 5414:             $homeserver = &homeserver($cnum,$cdom);
 5415:         } else {
 5416:             $homeserver = &domain($cdom,'primary');
 5417:         }
 5418:         if ($homeserver ne 'no_host') {
 5419:             $response = &reply('autorun:'.$cdom,$homeserver);
 5420:         }
 5421:     }
 5422:     return $response;
 5423: }
 5424: 
 5425: sub auto_get_sections {
 5426:     my ($cnum,$cdom,$inst_coursecode) = @_;
 5427:     my $homeserver = &homeserver($cnum,$cdom);
 5428:     my @secs = ();
 5429:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 5430:     unless ($response eq 'refused') {
 5431:         @secs = split(/:/,$response);
 5432:     }
 5433:     return @secs;
 5434: }
 5435: 
 5436: sub auto_new_course {
 5437:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 5438:     my $homeserver = &homeserver($cnum,$cdom);
 5439:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 5440:     return $response;
 5441: }
 5442: 
 5443: sub auto_validate_courseID {
 5444:     my ($cnum,$cdom,$inst_course_id) = @_;
 5445:     my $homeserver = &homeserver($cnum,$cdom);
 5446:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5447:     return $response;
 5448: }
 5449: 
 5450: sub auto_create_password {
 5451:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5452:     my ($homeserver,$response);
 5453:     my $create_passwd = 0;
 5454:     my $authchk = '';
 5455:     if ($udom =~ /^$match_domain$/) {
 5456:         $homeserver = &domain($udom,'primary');
 5457:     }
 5458:     if ($homeserver eq '') {
 5459:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5460:             $homeserver = &homeserver($cnum,$cdom);
 5461:         }
 5462:     }
 5463:     if ($homeserver eq '') {
 5464:         $authchk = 'nodomain';
 5465:     } else {
 5466:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5467:         if ($response eq 'refused') {
 5468:             $authchk = 'refused';
 5469:         } else {
 5470:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5471:         }
 5472:     }
 5473:     return ($authparam,$create_passwd,$authchk);
 5474: }
 5475: 
 5476: sub auto_photo_permission {
 5477:     my ($cnum,$cdom,$students) = @_;
 5478:     my $homeserver = &homeserver($cnum,$cdom);
 5479:     my ($outcome,$perm_reqd,$conditions) = 
 5480: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5481:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5482: 	return (undef,undef);
 5483:     }
 5484:     return ($outcome,$perm_reqd,$conditions);
 5485: }
 5486: 
 5487: sub auto_checkphotos {
 5488:     my ($uname,$udom,$pid) = @_;
 5489:     my $homeserver = &homeserver($uname,$udom);
 5490:     my ($result,$resulttype);
 5491:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5492: 				   &escape($uname).':'.&escape($pid),
 5493: 				   $homeserver));
 5494:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5495: 	return (undef,undef);
 5496:     }
 5497:     if ($outcome) {
 5498:         ($result,$resulttype) = split(/:/,$outcome);
 5499:     } 
 5500:     return ($result,$resulttype);
 5501: }
 5502: 
 5503: sub auto_photochoice {
 5504:     my ($cnum,$cdom) = @_;
 5505:     my $homeserver = &homeserver($cnum,$cdom);
 5506:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5507: 						       &escape($cdom),
 5508: 						       $homeserver)));
 5509:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5510: 	return (undef,undef);
 5511:     }
 5512:     return ($update,$comment);
 5513: }
 5514: 
 5515: sub auto_photoupdate {
 5516:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5517:     my $homeserver = &homeserver($cnum,$dom);
 5518:     my $host=&hostname($homeserver);
 5519:     my $cmd = '';
 5520:     my $maxtries = 1;
 5521:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5522:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5523:     }
 5524:     $cmd =~ s/%%$//;
 5525:     $cmd = &escape($cmd);
 5526:     my $query = 'institutionalphotos';
 5527:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5528:     unless ($queryid=~/^\Q$host\E\_/) {
 5529:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5530:         return 'error: '.$queryid;
 5531:     }
 5532:     my $reply = &get_query_reply($queryid);
 5533:     my $tries = 1;
 5534:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5535:         $reply = &get_query_reply($queryid);
 5536:         $tries ++;
 5537:     }
 5538:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5539:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5540:     } else {
 5541:         my @responses = split(/:/,$reply);
 5542:         my $outcome = shift(@responses); 
 5543:         foreach my $item (@responses) {
 5544:             my ($key,$value) = split(/=/,$item);
 5545:             $$photo{$key} = $value;
 5546:         }
 5547:         return $outcome;
 5548:     }
 5549:     return 'error';
 5550: }
 5551: 
 5552: sub auto_instcode_format {
 5553:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5554: 	$cat_order) = @_;
 5555:     my $courses = '';
 5556:     my @homeservers;
 5557:     if ($caller eq 'global') {
 5558: 	my %servers = &get_servers($codedom,'library');
 5559: 	foreach my $tryserver (keys(%servers)) {
 5560: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5561: 		push(@homeservers,$tryserver);
 5562: 	    }
 5563:         }
 5564:     } else {
 5565:         push(@homeservers,&homeserver($caller,$codedom));
 5566:     }
 5567:     foreach my $code (keys(%{$instcodes})) {
 5568:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5569:     }
 5570:     chop($courses);
 5571:     my $ok_response = 0;
 5572:     my $response;
 5573:     while (@homeservers > 0 && $ok_response == 0) {
 5574:         my $server = shift(@homeservers); 
 5575:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5576:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5577:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5578: 		split(/:/,$response);
 5579:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5580:             push(@{$codetitles},&str2array($codetitles_str));
 5581:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5582:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5583:             $ok_response = 1;
 5584:         }
 5585:     }
 5586:     if ($ok_response) {
 5587:         return 'ok';
 5588:     } else {
 5589:         return $response;
 5590:     }
 5591: }
 5592: 
 5593: sub auto_instcode_defaults {
 5594:     my ($domain,$returnhash,$code_order) = @_;
 5595:     my @homeservers;
 5596: 
 5597:     my %servers = &get_servers($domain,'library');
 5598:     foreach my $tryserver (keys(%servers)) {
 5599: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5600: 	    push(@homeservers,$tryserver);
 5601: 	}
 5602:     }
 5603: 
 5604:     my $response;
 5605:     foreach my $server (@homeservers) {
 5606:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5607:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5608: 	
 5609: 	foreach my $pair (split(/\&/,$response)) {
 5610: 	    my ($name,$value)=split(/\=/,$pair);
 5611: 	    if ($name eq 'code_order') {
 5612: 		@{$code_order} = split(/\&/,&unescape($value));
 5613: 	    } else {
 5614: 		$returnhash->{&unescape($name)}=&unescape($value);
 5615: 	    }
 5616: 	}
 5617: 	return 'ok';
 5618:     }
 5619: 
 5620:     return $response;
 5621: } 
 5622: 
 5623: sub auto_validate_class_sec {
 5624:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5625:     my $homeserver = &homeserver($cnum,$cdom);
 5626:     my $ownerlist;
 5627:     if (ref($owners) eq 'ARRAY') {
 5628:         $ownerlist = join(',',@{$owners});
 5629:     } else {
 5630:         $ownerlist = $owners;
 5631:     }
 5632:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 5633:                         &escape($ownerlist).':'.$cdom,$homeserver);
 5634:     return $response;
 5635: }
 5636: 
 5637: # ------------------------------------------------------- Course Group routines
 5638: 
 5639: sub get_coursegroups {
 5640:     my ($cdom,$cnum,$group,$namespace) = @_;
 5641:     return(&dump($namespace,$cdom,$cnum,$group));
 5642: }
 5643: 
 5644: sub modify_coursegroup {
 5645:     my ($cdom,$cnum,$groupsettings) = @_;
 5646:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 5647: }
 5648: 
 5649: sub toggle_coursegroup_status {
 5650:     my ($cdom,$cnum,$group,$action) = @_;
 5651:     my ($from_namespace,$to_namespace);
 5652:     if ($action eq 'delete') {
 5653:         $from_namespace = 'coursegroups';
 5654:         $to_namespace = 'deleted_groups';
 5655:     } else {
 5656:         $from_namespace = 'deleted_groups';
 5657:         $to_namespace = 'coursegroups';
 5658:     }
 5659:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 5660:     if (my $tmp = &error(%curr_group)) {
 5661:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 5662:         return ('read error',$tmp);
 5663:     } else {
 5664:         my %savedsettings = %curr_group; 
 5665:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 5666:         my $deloutcome;
 5667:         if ($result eq 'ok') {
 5668:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 5669:         } else {
 5670:             return ('write error',$result);
 5671:         }
 5672:         if ($deloutcome eq 'ok') {
 5673:             return 'ok';
 5674:         } else {
 5675:             return ('delete error',$deloutcome);
 5676:         }
 5677:     }
 5678: }
 5679: 
 5680: sub modify_group_roles {
 5681:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 5682:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 5683:     my $role = 'gr/'.&escape($userprivs);
 5684:     my ($uname,$udom) = split(/:/,$user);
 5685:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 5686:     if ($result eq 'ok') {
 5687:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 5688:     }
 5689:     return $result;
 5690: }
 5691: 
 5692: sub modify_coursegroup_membership {
 5693:     my ($cdom,$cnum,$membership) = @_;
 5694:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 5695:     return $result;
 5696: }
 5697: 
 5698: sub get_active_groups {
 5699:     my ($udom,$uname,$cdom,$cnum) = @_;
 5700:     my $now = time;
 5701:     my %groups = ();
 5702:     foreach my $key (keys(%env)) {
 5703:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 5704:             my ($start,$end) = split(/\./,$env{$key});
 5705:             if (($end!=0) && ($end<$now)) { next; }
 5706:             if (($start!=0) && ($start>$now)) { next; }
 5707:             if ($1 eq $cdom && $2 eq $cnum) {
 5708:                 $groups{$3} = $env{$key} ;
 5709:             }
 5710:         }
 5711:     }
 5712:     return %groups;
 5713: }
 5714: 
 5715: sub get_group_membership {
 5716:     my ($cdom,$cnum,$group) = @_;
 5717:     return(&dump('groupmembership',$cdom,$cnum,$group));
 5718: }
 5719: 
 5720: sub get_users_groups {
 5721:     my ($udom,$uname,$courseid) = @_;
 5722:     my @usersgroups;
 5723:     my $cachetime=1800;
 5724: 
 5725:     my $hashid="$udom:$uname:$courseid";
 5726:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 5727:     if (defined($cached)) {
 5728:         @usersgroups = split(/:/,$grouplist);
 5729:     } else {  
 5730:         $grouplist = '';
 5731:         my $courseurl = &courseid_to_courseurl($courseid);
 5732:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 5733:         my $access_end = $env{'course.'.$courseid.
 5734:                               '.default_enrollment_end_date'};
 5735:         my $now = time;
 5736:         foreach my $key (keys(%roleshash)) {
 5737:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 5738:                 my $group = $1;
 5739:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 5740:                     my $start = $2;
 5741:                     my $end = $1;
 5742:                     if ($start == -1) { next; } # deleted from group
 5743:                     if (($start!=0) && ($start>$now)) { next; }
 5744:                     if (($end!=0) && ($end<$now)) {
 5745:                         if ($access_end && $access_end < $now) {
 5746:                             if ($access_end - $end < 86400) {
 5747:                                 push(@usersgroups,$group);
 5748:                             }
 5749:                         }
 5750:                         next;
 5751:                     }
 5752:                     push(@usersgroups,$group);
 5753:                 }
 5754:             }
 5755:         }
 5756:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 5757:         $grouplist = join(':',@usersgroups);
 5758:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 5759:     }
 5760:     return @usersgroups;
 5761: }
 5762: 
 5763: sub devalidate_getgroups_cache {
 5764:     my ($udom,$uname,$cdom,$cnum)=@_;
 5765:     my $courseid = $cdom.'_'.$cnum;
 5766: 
 5767:     my $hashid="$udom:$uname:$courseid";
 5768:     &devalidate_cache_new('getgroups',$hashid);
 5769: }
 5770: 
 5771: # ------------------------------------------------------------------ Plain Text
 5772: 
 5773: sub plaintext {
 5774:     my ($short,$type,$cid,$forcedefault) = @_;
 5775:     if ($short =~ /^cr/) {
 5776: 	return (split('/',$short))[-1];
 5777:     }
 5778:     if (!defined($cid)) {
 5779:         $cid = $env{'request.course.id'};
 5780:     }
 5781:     if (defined($cid) && ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '')) {
 5782:         unless ($forcedefault) {
 5783:             my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 5784:             &Apache::lonlocal::mt_escape(\$roletext);
 5785:             return &Apache::lonlocal::mt($roletext);
 5786:         }
 5787:     }
 5788:     my %rolenames = (
 5789:                       Course => 'std',
 5790:                       Group => 'alt1',
 5791:                     );
 5792:     if (defined($type) && 
 5793:          defined($rolenames{$type}) && 
 5794:          defined($prp{$short}{$rolenames{$type}})) {
 5795:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 5796:     } else {
 5797:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 5798:     }
 5799: }
 5800: 
 5801: # ----------------------------------------------------------------- Assign Role
 5802: 
 5803: sub assignrole {
 5804:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 5805:         $context)=@_;
 5806:     my $mrole;
 5807:     if ($role =~ /^cr\//) {
 5808:         my $cwosec=$url;
 5809:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5810: 	unless (&allowed('ccr',$cwosec)) {
 5811:            &logthis('Refused custom assignrole: '.
 5812:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5813: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 5814:            return 'refused'; 
 5815:         }
 5816:         $mrole='cr';
 5817:     } elsif ($role =~ /^gr\//) {
 5818:         my $cwogrp=$url;
 5819:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 5820:         unless (&allowed('mdg',$cwogrp)) {
 5821:             &logthis('Refused group assignrole: '.
 5822:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5823:                     $env{'user.name'}.' at '.$env{'user.domain'});
 5824:             return 'refused';
 5825:         }
 5826:         $mrole='gr';
 5827:     } else {
 5828:         my $cwosec=$url;
 5829:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5830:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 5831:             my $refused;
 5832:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 5833:                 if (!(&allowed('c'.$role,$url))) {
 5834:                     $refused = 1;
 5835:                 }
 5836:             } else {
 5837:                 $refused = 1;
 5838:             }
 5839:             if ($refused) {
 5840:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5841:                     $refused = '';
 5842:                 } else {
 5843:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 5844:                              ' '.$role.' '.$end.' '.$start.' by '.
 5845: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 5846:                     return 'refused';
 5847:                 }
 5848:             }
 5849:         }
 5850:         $mrole=$role;
 5851:     }
 5852:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5853:                 "$udom:$uname:$url".'_'."$mrole=$role";
 5854:     if ($end) { $command.='_'.$end; }
 5855:     if ($start) {
 5856: 	if ($end) { 
 5857:            $command.='_'.$start; 
 5858:         } else {
 5859:            $command.='_0_'.$start;
 5860:         }
 5861:     }
 5862:     my $origstart = $start;
 5863:     my $origend = $end;
 5864:     my $delflag;
 5865: # actually delete
 5866:     if ($deleteflag) {
 5867: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 5868: # modify command to delete the role
 5869:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 5870:                 "$udom:$uname:$url".'_'."$mrole";
 5871: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 5872: # set start and finish to negative values for userrolelog
 5873:            $start=-1;
 5874:            $end=-1;
 5875:            $delflag = 1;
 5876:         }
 5877:     }
 5878: # send command
 5879:     my $answer=&reply($command,&homeserver($uname,$udom));
 5880: # log new user role if status is ok
 5881:     if ($answer eq 'ok') {
 5882: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 5883: # for course roles, perform group memberships changes triggered by role change.
 5884:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 5885:         unless ($role =~ /^gr/) {
 5886:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 5887:                                              $origstart,$selfenroll,$context);
 5888:         }
 5889:     }
 5890:     return $answer;
 5891: }
 5892: 
 5893: # -------------------------------------------------- Modify user authentication
 5894: # Overrides without validation
 5895: 
 5896: sub modifyuserauth {
 5897:     my ($udom,$uname,$umode,$upass)=@_;
 5898:     my $uhome=&homeserver($uname,$udom);
 5899:     unless (&allowed('mau',$udom)) { return 'refused'; }
 5900:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 5901:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5902:              ' in domain '.$env{'request.role.domain'});  
 5903:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 5904: 		     &escape($upass),$uhome);
 5905:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 5906:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 5907:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5908:     &log($udom,,$uname,$uhome,
 5909:         'Authentication changed by '.$env{'user.domain'}.', '.
 5910:                                      $env{'user.name'}.', '.$umode.
 5911:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5912:     unless ($reply eq 'ok') {
 5913:         &logthis('Authentication mode error: '.$reply);
 5914: 	return 'error: '.$reply;
 5915:     }   
 5916:     return 'ok';
 5917: }
 5918: 
 5919: # --------------------------------------------------------------- Modify a user
 5920: 
 5921: sub modifyuser {
 5922:     my ($udom,    $uname, $uid,
 5923:         $umode,   $upass, $first,
 5924:         $middle,  $last,  $gene,
 5925:         $forceid, $desiredhome, $email, $inststatus)=@_;
 5926:     $udom= &LONCAPA::clean_domain($udom);
 5927:     $uname=&LONCAPA::clean_username($uname);
 5928:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 5929:              $umode.', '.$first.', '.$middle.', '.
 5930: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 5931:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 5932:                                      ' desiredhome not specified'). 
 5933:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5934:              ' in domain '.$env{'request.role.domain'});
 5935:     my $uhome=&homeserver($uname,$udom,'true');
 5936: # ----------------------------------------------------------------- Create User
 5937:     if (($uhome eq 'no_host') && 
 5938: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 5939:         my $unhome='';
 5940:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 5941:             $unhome = $desiredhome;
 5942: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 5943: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 5944:         } else { # load balancing routine for determining $unhome
 5945:             my $loadm=10000000;
 5946: 	    my %servers = &get_servers($udom,'library');
 5947: 	    foreach my $tryserver (keys(%servers)) {
 5948: 		my $answer=reply('load',$tryserver);
 5949: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 5950: 		    $loadm=$answer;
 5951: 		    $unhome=$tryserver;
 5952: 		}
 5953: 	    }
 5954:         }
 5955:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 5956: 	    return 'error: unable to find a home server for '.$uname.
 5957:                    ' in domain '.$udom;
 5958:         }
 5959:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 5960:                          &escape($upass),$unhome);
 5961: 	unless ($reply eq 'ok') {
 5962:             return 'error: '.$reply;
 5963:         }   
 5964:         $uhome=&homeserver($uname,$udom,'true');
 5965:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 5966: 	    return 'error: unable verify users home machine.';
 5967:         }
 5968:     }   # End of creation of new user
 5969: # ---------------------------------------------------------------------- Add ID
 5970:     if ($uid) {
 5971:        $uid=~tr/A-Z/a-z/;
 5972:        my %uidhash=&idrget($udom,$uname);
 5973:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 5974:          && (!$forceid)) {
 5975: 	  unless ($uid eq $uidhash{$uname}) {
 5976: 	      return 'error: user id "'.$uid.'" does not match '.
 5977:                   'current user id "'.$uidhash{$uname}.'".';
 5978:           }
 5979:        } else {
 5980: 	  &idput($udom,($uname => $uid));
 5981:        }
 5982:     }
 5983: # -------------------------------------------------------------- Add names, etc
 5984:     my @tmp=&get('environment',
 5985: 		   ['firstname','middlename','lastname','generation','id',
 5986:                     'permanentemail','inststatus'],
 5987: 		   $udom,$uname);
 5988:     my %names;
 5989:     if ($tmp[0] =~ m/^error:.*/) { 
 5990:         %names=(); 
 5991:     } else {
 5992:         %names = @tmp;
 5993:     }
 5994: #
 5995: # Make sure to not trash student environment if instructor does not bother
 5996: # to supply name and email information
 5997: #
 5998:     if ($first)  { $names{'firstname'}  = $first; }
 5999:     if (defined($middle)) { $names{'middlename'} = $middle; }
 6000:     if ($last)   { $names{'lastname'}   = $last; }
 6001:     if (defined($gene))   { $names{'generation'} = $gene; }
 6002:     if ($email) {
 6003:        $email=~s/[^\w\@\.\-\,]//gs;
 6004:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 6005:     }
 6006:     if ($uid) { $names{'id'}  = $uid; }
 6007:     if (defined($inststatus)) {
 6008:         $names{'inststatus'} = '';
 6009:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 6010:         if (ref($usertypes) eq 'HASH') {
 6011:             my @okstatuses; 
 6012:             foreach my $item (split(/:/,$inststatus)) {
 6013:                 if (defined($usertypes->{$item})) {
 6014:                     push(@okstatuses,$item);  
 6015:                 }
 6016:             }
 6017:             if (@okstatuses) {
 6018:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 6019:             }
 6020:         }
 6021:     }
 6022:     my $reply = &put('environment', \%names, $udom,$uname);
 6023:     if ($reply ne 'ok') { return 'error: '.$reply; }
 6024:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 6025:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 6026:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 6027:                  $umode.', '.$first.', '.$middle.', '.
 6028: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
 6029:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 6030:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 6031:     } else {
 6032:         $logmsg .= ' during self creation';
 6033:     }
 6034:     &logthis($logmsg);
 6035:     return 'ok';
 6036: }
 6037: 
 6038: # -------------------------------------------------------------- Modify student
 6039: 
 6040: sub modifystudent {
 6041:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 6042:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 6043:         $selfenroll,$context,$inststatus)=@_;
 6044:     if (!$cid) {
 6045: 	unless ($cid=$env{'request.course.id'}) {
 6046: 	    return 'not_in_class';
 6047: 	}
 6048:     }
 6049: # --------------------------------------------------------------- Make the user
 6050:     my $reply=&modifyuser
 6051: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 6052:          $desiredhome,$email,$inststatus);
 6053:     unless ($reply eq 'ok') { return $reply; }
 6054:     # This will cause &modify_student_enrollment to get the uid from the
 6055:     # students environment
 6056:     $uid = undef if (!$forceid);
 6057:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 6058: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 6059:     return $reply;
 6060: }
 6061: 
 6062: sub modify_student_enrollment {
 6063:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 6064:     my ($cdom,$cnum,$chome);
 6065:     if (!$cid) {
 6066: 	unless ($cid=$env{'request.course.id'}) {
 6067: 	    return 'not_in_class';
 6068: 	}
 6069: 	$cdom=$env{'course.'.$cid.'.domain'};
 6070: 	$cnum=$env{'course.'.$cid.'.num'};
 6071:     } else {
 6072: 	($cdom,$cnum)=split(/_/,$cid);
 6073:     }
 6074:     $chome=$env{'course.'.$cid.'.home'};
 6075:     if (!$chome) {
 6076: 	$chome=&homeserver($cnum,$cdom);
 6077:     }
 6078:     if (!$chome) { return 'unknown_course'; }
 6079:     # Make sure the user exists
 6080:     my $uhome=&homeserver($uname,$udom);
 6081:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6082: 	return 'error: no such user';
 6083:     }
 6084:     # Get student data if we were not given enough information
 6085:     if (!defined($first)  || $first  eq '' || 
 6086:         !defined($last)   || $last   eq '' || 
 6087:         !defined($uid)    || $uid    eq '' || 
 6088:         !defined($middle) || $middle eq '' || 
 6089:         !defined($gene)   || $gene   eq '') {
 6090:         # They did not supply us with enough data to enroll the student, so
 6091:         # we need to pick up more information.
 6092:         my %tmp = &get('environment',
 6093:                        ['firstname','middlename','lastname', 'generation','id']
 6094:                        ,$udom,$uname);
 6095: 
 6096:         #foreach my $key (keys(%tmp)) {
 6097:         #    &logthis("key $key = ".$tmp{$key});
 6098:         #}
 6099:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 6100:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 6101:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 6102:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 6103:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 6104:     }
 6105:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 6106:     my $reply=cput('classlist',
 6107: 		   {"$uname:$udom" => 
 6108: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 6109: 		   $cdom,$cnum);
 6110:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 6111: 	return 'error: '.$reply;
 6112:     } else {
 6113: 	&devalidate_getsection_cache($udom,$uname,$cid);
 6114:     }
 6115:     # Add student role to user
 6116:     my $uurl='/'.$cid;
 6117:     $uurl=~s/\_/\//g;
 6118:     if ($usec) {
 6119: 	$uurl.='/'.$usec;
 6120:     }
 6121:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 6122: }
 6123: 
 6124: sub format_name {
 6125:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 6126:     my $name;
 6127:     if ($first ne 'lastname') {
 6128: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 6129:     } else {
 6130: 	if ($lastname=~/\S/) {
 6131: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 6132: 	    $name=~s/\s+,/,/;
 6133: 	} else {
 6134: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 6135: 	}
 6136:     }
 6137:     $name=~s/^\s+//;
 6138:     $name=~s/\s+$//;
 6139:     $name=~s/\s+/ /g;
 6140:     return $name;
 6141: }
 6142: 
 6143: # ------------------------------------------------- Write to course preferences
 6144: 
 6145: sub writecoursepref {
 6146:     my ($courseid,%prefs)=@_;
 6147:     $courseid=~s/^\///;
 6148:     $courseid=~s/\_/\//g;
 6149:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6150:     my $chome=homeserver($cnum,$cdomain);
 6151:     if (($chome eq '') || ($chome eq 'no_host')) { 
 6152: 	return 'error: no such course';
 6153:     }
 6154:     my $cstring='';
 6155:     foreach my $pref (keys(%prefs)) {
 6156: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 6157:     }
 6158:     $cstring=~s/\&$//;
 6159:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 6160: }
 6161: 
 6162: # ---------------------------------------------------------- Make/modify course
 6163: 
 6164: sub createcourse {
 6165:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 6166:         $course_owner,$crstype)=@_;
 6167:     $url=&declutter($url);
 6168:     my $cid='';
 6169:     unless (&allowed('ccc',$udom)) {
 6170:         return 'refused';
 6171:     }
 6172: # ------------------------------------------------------------------- Create ID
 6173:    my $uname=int(1+rand(9)).
 6174:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6175:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6176:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6177: # ----------------------------------------------- Make sure that does not exist
 6178:    my $uhome=&homeserver($uname,$udom,'true');
 6179:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6180:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6181:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6182:        $uhome=&homeserver($uname,$udom,'true');       
 6183:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6184:            return 'error: unable to generate unique course-ID';
 6185:        } 
 6186:    }
 6187: # ------------------------------------------------ Check supplied server name
 6188:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 6189:     if (! &is_library($course_server)) {
 6190:         return 'error:bad server name '.$course_server;
 6191:     }
 6192: # ------------------------------------------------------------- Make the course
 6193:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 6194:                       $course_server);
 6195:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 6196:     $uhome=&homeserver($uname,$udom,'true');
 6197:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6198: 	return 'error: no such course';
 6199:     }
 6200: # ----------------------------------------------------------------- Course made
 6201: # log existence
 6202:     my $newcourse = {
 6203:                     $udom.'_'.$uname => {
 6204:                                      description => $description,
 6205:                                      inst_code   => $inst_code,
 6206:                                      owner       => $course_owner,
 6207:                                      type        => $crstype,
 6208:                                                 },
 6209:                     };
 6210:     &courseidput($udom,$newcourse,$uhome,'notime');
 6211: # set toplevel url
 6212:     my $topurl=$url;
 6213:     unless ($nonstandard) {
 6214: # ------------------------------------------ For standard courses, make top url
 6215:         my $mapurl=&clutter($url);
 6216:         if ($mapurl eq '/res/') { $mapurl=''; }
 6217:         $env{'form.initmap'}=(<<ENDINITMAP);
 6218: <map>
 6219: <resource id="1" type="start"></resource>
 6220: <resource id="2" src="$mapurl"></resource>
 6221: <resource id="3" type="finish"></resource>
 6222: <link index="1" from="1" to="2"></link>
 6223: <link index="2" from="2" to="3"></link>
 6224: </map>
 6225: ENDINITMAP
 6226:         $topurl=&declutter(
 6227:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 6228:                           );
 6229:     }
 6230: # ----------------------------------------------------------- Write preferences
 6231:     &writecoursepref($udom.'_'.$uname,
 6232:                      ('description' => $description,
 6233:                       'url'         => $topurl));
 6234:     return '/'.$udom.'/'.$uname;
 6235: }
 6236: 
 6237: sub is_course {
 6238:     my ($cdom,$cnum) = @_;
 6239:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 6240: 				undef,'.');
 6241:     if (exists($courses{$cdom.'_'.$cnum})) {
 6242:         return 1;
 6243:     }
 6244:     return 0;
 6245: }
 6246: 
 6247: # ---------------------------------------------------------- Assign Custom Role
 6248: 
 6249: sub assigncustomrole {
 6250:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 6251:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 6252:                        $end,$start,$deleteflag,$selfenroll,$context);
 6253: }
 6254: 
 6255: # ----------------------------------------------------------------- Revoke Role
 6256: 
 6257: sub revokerole {
 6258:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 6259:     my $now=time;
 6260:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 6261: }
 6262: 
 6263: # ---------------------------------------------------------- Revoke Custom Role
 6264: 
 6265: sub revokecustomrole {
 6266:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 6267:     my $now=time;
 6268:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 6269:            $deleteflag,$selfenroll,$context);
 6270: }
 6271: 
 6272: # ------------------------------------------------------------ Disk usage
 6273: sub diskusage {
 6274:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 6275:     $directorypath =~ s/\/$//;
 6276:     my $listing=&reply('du2:'.&escape($directorypath).':'
 6277:                        .&escape($getpropath).':'.&escape($uname).':'
 6278:                        .&escape($udom),homeserver($uname,$udom));
 6279:     if ($listing eq 'unknown_cmd') {
 6280:         if ($getpropath) {
 6281:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 6282:         }
 6283:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 6284:     }
 6285:     return $listing;
 6286: }
 6287: 
 6288: sub is_locked {
 6289:     my ($file_name, $domain, $user) = @_;
 6290:     my @check;
 6291:     my $is_locked;
 6292:     push @check, $file_name;
 6293:     my %locked = &get('file_permissions',\@check,
 6294: 		      $env{'user.domain'},$env{'user.name'});
 6295:     my ($tmp)=keys(%locked);
 6296:     if ($tmp=~/^error:/) { undef(%locked); }
 6297:     
 6298:     if (ref($locked{$file_name}) eq 'ARRAY') {
 6299:         $is_locked = 'false';
 6300:         foreach my $entry (@{$locked{$file_name}}) {
 6301:            if (ref($entry) eq 'ARRAY') { 
 6302:                $is_locked = 'true';
 6303:                last;
 6304:            }
 6305:        }
 6306:     } else {
 6307:         $is_locked = 'false';
 6308:     }
 6309: }
 6310: 
 6311: sub declutter_portfile {
 6312:     my ($file) = @_;
 6313:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 6314:     return $file;
 6315: }
 6316: 
 6317: # ------------------------------------------------------------- Mark as Read Only
 6318: 
 6319: sub mark_as_readonly {
 6320:     my ($domain,$user,$files,$what) = @_;
 6321:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6322:     my ($tmp)=keys(%current_permissions);
 6323:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6324:     foreach my $file (@{$files}) {
 6325: 	$file = &declutter_portfile($file);
 6326:         push(@{$current_permissions{$file}},$what);
 6327:     }
 6328:     &put('file_permissions',\%current_permissions,$domain,$user);
 6329:     return;
 6330: }
 6331: 
 6332: # ------------------------------------------------------------Save Selected Files
 6333: 
 6334: sub save_selected_files {
 6335:     my ($user, $path, @files) = @_;
 6336:     my $filename = $user."savedfiles";
 6337:     my @other_files = &files_not_in_path($user, $path);
 6338:     open (OUT, '>'.$tmpdir.$filename);
 6339:     foreach my $file (@files) {
 6340:         print (OUT $env{'form.currentpath'}.$file."\n");
 6341:     }
 6342:     foreach my $file (@other_files) {
 6343:         print (OUT $file."\n");
 6344:     }
 6345:     close (OUT);
 6346:     return 'ok';
 6347: }
 6348: 
 6349: sub clear_selected_files {
 6350:     my ($user) = @_;
 6351:     my $filename = $user."savedfiles";
 6352:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6353:     print (OUT undef);
 6354:     close (OUT);
 6355:     return ("ok");    
 6356: }
 6357: 
 6358: sub files_in_path {
 6359:     my ($user, $path) = @_;
 6360:     my $filename = $user."savedfiles";
 6361:     my %return_files;
 6362:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6363:     while (my $line_in = <IN>) {
 6364:         chomp ($line_in);
 6365:         my @paths_and_file = split (m!/!, $line_in);
 6366:         my $file_part = pop (@paths_and_file);
 6367:         my $path_part = join ('/', @paths_and_file);
 6368:         $path_part.='/';
 6369:         my $path_and_file = $path_part.$file_part;
 6370:         if ($path_part eq $path) {
 6371:             $return_files{$file_part}= 'selected';
 6372:         }
 6373:     }
 6374:     close (IN);
 6375:     return (\%return_files);
 6376: }
 6377: 
 6378: # called in portfolio select mode, to show files selected NOT in current directory
 6379: sub files_not_in_path {
 6380:     my ($user, $path) = @_;
 6381:     my $filename = $user."savedfiles";
 6382:     my @return_files;
 6383:     my $path_part;
 6384:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6385:     while (my $line = <IN>) {
 6386:         #ok, I know it's clunky, but I want it to work
 6387:         my @paths_and_file = split(m|/|, $line);
 6388:         my $file_part = pop(@paths_and_file);
 6389:         chomp($file_part);
 6390:         my $path_part = join('/', @paths_and_file);
 6391:         $path_part .= '/';
 6392:         my $path_and_file = $path_part.$file_part;
 6393:         if ($path_part ne $path) {
 6394:             push(@return_files, ($path_and_file));
 6395:         }
 6396:     }
 6397:     close(OUT);
 6398:     return (@return_files);
 6399: }
 6400: 
 6401: #----------------------------------------------Get portfolio file permissions
 6402: 
 6403: sub get_portfile_permissions {
 6404:     my ($domain,$user) = @_;
 6405:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6406:     my ($tmp)=keys(%current_permissions);
 6407:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6408:     return \%current_permissions;
 6409: }
 6410: 
 6411: #---------------------------------------------Get portfolio file access controls
 6412: 
 6413: sub get_access_controls {
 6414:     my ($current_permissions,$group,$file) = @_;
 6415:     my %access;
 6416:     my $real_file = $file;
 6417:     $file =~ s/\.meta$//;
 6418:     if (defined($file)) {
 6419:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 6420:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 6421:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 6422:             }
 6423:         }
 6424:     } else {
 6425:         foreach my $key (keys(%{$current_permissions})) {
 6426:             if ($key =~ /\0accesscontrol$/) {
 6427:                 if (defined($group)) {
 6428:                     if ($key !~ m-^\Q$group\E/-) {
 6429:                         next;
 6430:                     }
 6431:                 }
 6432:                 my ($fullpath) = split(/\0/,$key);
 6433:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 6434:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 6435:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 6436:                     }
 6437:                 }
 6438:             }
 6439:         }
 6440:     }
 6441:     return %access;
 6442: }
 6443: 
 6444: sub modify_access_controls {
 6445:     my ($file_name,$changes,$domain,$user)=@_;
 6446:     my ($outcome,$deloutcome);
 6447:     my %store_permissions;
 6448:     my %new_values;
 6449:     my %new_control;
 6450:     my %translation;
 6451:     my @deletions = ();
 6452:     my $now = time;
 6453:     if (exists($$changes{'activate'})) {
 6454:         if (ref($$changes{'activate'}) eq 'HASH') {
 6455:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 6456:             my $numnew = scalar(@newitems);
 6457:             for (my $i=0; $i<$numnew; $i++) {
 6458:                 my $newkey = $newitems[$i];
 6459:                 my $newid = &Apache::loncommon::get_cgi_id();
 6460:                 if ($newkey =~ /^\d+:/) { 
 6461:                     $newkey =~ s/^(\d+)/$newid/;
 6462:                     $translation{$1} = $newid;
 6463:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 6464:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 6465:                     $translation{$1} = $newid;
 6466:                 }
 6467:                 $new_values{$file_name."\0".$newkey} = 
 6468:                                           $$changes{'activate'}{$newitems[$i]};
 6469:                 $new_control{$newkey} = $now;
 6470:             }
 6471:         }
 6472:     }
 6473:     my %todelete;
 6474:     my %changed_items;
 6475:     foreach my $action ('delete','update') {
 6476:         if (exists($$changes{$action})) {
 6477:             if (ref($$changes{$action}) eq 'HASH') {
 6478:                 foreach my $key (keys(%{$$changes{$action}})) {
 6479:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 6480:                     if ($action eq 'delete') { 
 6481:                         $todelete{$itemnum} = 1;
 6482:                     } else {
 6483:                         $changed_items{$itemnum} = $key;
 6484:                     }
 6485:                 }
 6486:             }
 6487:         }
 6488:     }
 6489:     # get lock on access controls for file.
 6490:     my $lockhash = {
 6491:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 6492:                                                        ':'.$env{'user.domain'},
 6493:                    }; 
 6494:     my $tries = 0;
 6495:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6496:    
 6497:     while (($gotlock ne 'ok') && $tries <3) {
 6498:         $tries ++;
 6499:         sleep 1;
 6500:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6501:     }
 6502:     if ($gotlock eq 'ok') {
 6503:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 6504:         my ($tmp)=keys(%curr_permissions);
 6505:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 6506:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 6507:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 6508:             if (ref($curr_controls) eq 'HASH') {
 6509:                 foreach my $control_item (keys(%{$curr_controls})) {
 6510:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 6511:                     if (defined($todelete{$itemnum})) {
 6512:                         push(@deletions,$file_name."\0".$control_item);
 6513:                     } else {
 6514:                         if (defined($changed_items{$itemnum})) {
 6515:                             $new_control{$changed_items{$itemnum}} = $now;
 6516:                             push(@deletions,$file_name."\0".$control_item);
 6517:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 6518:                         } else {
 6519:                             $new_control{$control_item} = $$curr_controls{$control_item};
 6520:                         }
 6521:                     }
 6522:                 }
 6523:             }
 6524:         }
 6525:         my ($group);
 6526:         if (&is_course($domain,$user)) {
 6527:             ($group,my $file) = split(/\//,$file_name,2);
 6528:         }
 6529:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 6530:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 6531:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 6532:         #  remove lock
 6533:         my @del_lock = ($file_name."\0".'locked_access_records');
 6534:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 6535:         my $sqlresult =
 6536:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 6537:                                     $group);
 6538:     } else {
 6539:         $outcome = "error: could not obtain lockfile\n";  
 6540:     }
 6541:     return ($outcome,$deloutcome,\%new_values,\%translation);
 6542: }
 6543: 
 6544: sub make_public_indefinitely {
 6545:     my ($requrl) = @_;
 6546:     my $now = time;
 6547:     my $action = 'activate';
 6548:     my $aclnum = 0;
 6549:     if (&is_portfolio_url($requrl)) {
 6550:         my (undef,$udom,$unum,$file_name,$group) =
 6551:             &parse_portfolio_url($requrl);
 6552:         my $current_perms = &get_portfile_permissions($udom,$unum);
 6553:         my %access_controls = &get_access_controls($current_perms,
 6554:                                                    $group,$file_name);
 6555:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 6556:             my ($num,$scope,$end,$start) = 
 6557:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6558:             if ($scope eq 'public') {
 6559:                 if ($start <= $now && $end == 0) {
 6560:                     $action = 'none';
 6561:                 } else {
 6562:                     $action = 'update';
 6563:                     $aclnum = $num;
 6564:                 }
 6565:                 last;
 6566:             }
 6567:         }
 6568:         if ($action eq 'none') {
 6569:              return 'ok';
 6570:         } else {
 6571:             my %changes;
 6572:             my $newend = 0;
 6573:             my $newstart = $now;
 6574:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 6575:             $changes{$action}{$newkey} = {
 6576:                 type => 'public',
 6577:                 time => {
 6578:                     start => $newstart,
 6579:                     end   => $newend,
 6580:                 },
 6581:             };
 6582:             my ($outcome,$deloutcome,$new_values,$translation) =
 6583:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 6584:             return $outcome;
 6585:         }
 6586:     } else {
 6587:         return 'invalid';
 6588:     }
 6589: }
 6590: 
 6591: #------------------------------------------------------Get Marked as Read Only
 6592: 
 6593: sub get_marked_as_readonly {
 6594:     my ($domain,$user,$what,$group) = @_;
 6595:     my $current_permissions = &get_portfile_permissions($domain,$user);
 6596:     my @readonly_files;
 6597:     my $cmp1=$what;
 6598:     if (ref($what)) { $cmp1=join('',@{$what}) };
 6599:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6600:         if (defined($group)) {
 6601:             if ($file_name !~ m-^\Q$group\E/-) {
 6602:                 next;
 6603:             }
 6604:         }
 6605:         if (ref($value) eq "ARRAY"){
 6606:             foreach my $stored_what (@{$value}) {
 6607:                 my $cmp2=$stored_what;
 6608:                 if (ref($stored_what) eq 'ARRAY') {
 6609:                     $cmp2=join('',@{$stored_what});
 6610:                 }
 6611:                 if ($cmp1 eq $cmp2) {
 6612:                     push(@readonly_files, $file_name);
 6613:                     last;
 6614:                 } elsif (!defined($what)) {
 6615:                     push(@readonly_files, $file_name);
 6616:                     last;
 6617:                 }
 6618:             }
 6619:         }
 6620:     }
 6621:     return @readonly_files;
 6622: }
 6623: #-----------------------------------------------------------Get Marked as Read Only Hash
 6624: 
 6625: sub get_marked_as_readonly_hash {
 6626:     my ($current_permissions,$group,$what) = @_;
 6627:     my %readonly_files;
 6628:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6629:         if (defined($group)) {
 6630:             if ($file_name !~ m-^\Q$group\E/-) {
 6631:                 next;
 6632:             }
 6633:         }
 6634:         if (ref($value) eq "ARRAY"){
 6635:             foreach my $stored_what (@{$value}) {
 6636:                 if (ref($stored_what) eq 'ARRAY') {
 6637:                     foreach my $lock_descriptor(@{$stored_what}) {
 6638:                         if ($lock_descriptor eq 'graded') {
 6639:                             $readonly_files{$file_name} = 'graded';
 6640:                         } elsif ($lock_descriptor eq 'handback') {
 6641:                             $readonly_files{$file_name} = 'handback';
 6642:                         } else {
 6643:                             if (!exists($readonly_files{$file_name})) {
 6644:                                 $readonly_files{$file_name} = 'locked';
 6645:                             }
 6646:                         }
 6647:                     }
 6648:                 } 
 6649:             }
 6650:         } 
 6651:     }
 6652:     return %readonly_files;
 6653: }
 6654: # ------------------------------------------------------------ Unmark as Read Only
 6655: 
 6656: sub unmark_as_readonly {
 6657:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 6658:     # for portfolio submissions, $what contains [$symb,$crsid] 
 6659:     my ($domain,$user,$what,$file_name,$group) = @_;
 6660:     $file_name = &declutter_portfile($file_name);
 6661:     my $symb_crs = $what;
 6662:     if (ref($what)) { $symb_crs=join('',@$what); }
 6663:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 6664:     my ($tmp)=keys(%current_permissions);
 6665:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6666:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 6667:     foreach my $file (@readonly_files) {
 6668: 	my $clean_file = &declutter_portfile($file);
 6669: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 6670: 	my $current_locks = $current_permissions{$file};
 6671:         my @new_locks;
 6672:         my @del_keys;
 6673:         if (ref($current_locks) eq "ARRAY"){
 6674:             foreach my $locker (@{$current_locks}) {
 6675:                 my $compare=$locker;
 6676:                 if (ref($locker) eq 'ARRAY') {
 6677:                     $compare=join('',@{$locker});
 6678:                     if ($compare ne $symb_crs) {
 6679:                         push(@new_locks, $locker);
 6680:                     }
 6681:                 }
 6682:             }
 6683:             if (scalar(@new_locks) > 0) {
 6684:                 $current_permissions{$file} = \@new_locks;
 6685:             } else {
 6686:                 push(@del_keys, $file);
 6687:                 &del('file_permissions',\@del_keys, $domain, $user);
 6688:                 delete($current_permissions{$file});
 6689:             }
 6690:         }
 6691:     }
 6692:     &put('file_permissions',\%current_permissions,$domain,$user);
 6693:     return;
 6694: }
 6695: 
 6696: # ------------------------------------------------------------ Directory lister
 6697: 
 6698: sub dirlist {
 6699:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 6700:     $uri=~s/^\///;
 6701:     $uri=~s/\/$//;
 6702:     my ($udom, $uname);
 6703:     if ($getuserdir) {
 6704:         $udom = $userdomain;
 6705:         $uname = $username;
 6706:     } else {
 6707:         (undef,$udom,$uname)=split(/\//,$uri);
 6708:         if(defined($userdomain)) {
 6709:             $udom = $userdomain;
 6710:         }
 6711:         if(defined($username)) {
 6712:             $uname = $username;
 6713:         }
 6714:     }
 6715:     my ($dirRoot,$listing,@listing_results);
 6716: 
 6717:     $dirRoot = $perlvar{'lonDocRoot'};
 6718:     if (defined($getpropath)) {
 6719:         $dirRoot = &propath($udom,$uname);
 6720:         $dirRoot =~ s/\/$//;
 6721:     } elsif (defined($getuserdir)) {
 6722:         my $subdir=$uname.'__';
 6723:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 6724:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 6725:                    ."/$udom/$subdir/$uname";
 6726:     } elsif (defined($alternateRoot)) {
 6727:         $dirRoot = $alternateRoot;
 6728:     }
 6729: 
 6730:     if($udom) {
 6731:         if($uname) {
 6732:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 6733:                               .$getuserdir.':'.&escape($dirRoot)
 6734:                               .':'.&escape($uname).':'.&escape($udom),
 6735:                               &homeserver($uname,$udom));
 6736:             if ($listing eq 'unknown_cmd') {
 6737:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 6738:                                   &homeserver($uname,$udom));
 6739:             } else {
 6740:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6741:             }
 6742:             if ($listing eq 'unknown_cmd') {
 6743:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 6744: 				  &homeserver($uname,$udom));
 6745:                 @listing_results = split(/:/,$listing);
 6746:             } else {
 6747:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6748:             }
 6749:             return @listing_results;
 6750:         } elsif(!$alternateRoot) {
 6751:             my %allusers;
 6752: 	    my %servers = &get_servers($udom,'library');
 6753:  	    foreach my $tryserver (keys(%servers)) {
 6754:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 6755:                                   &escape($udom),$tryserver);
 6756:                 if ($listing eq 'unknown_cmd') {
 6757: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 6758: 				      $udom, $tryserver);
 6759:                 } else {
 6760:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 6761:                 }
 6762: 		if ($listing eq 'unknown_cmd') {
 6763: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 6764: 				      $udom, $tryserver);
 6765: 		    @listing_results = split(/:/,$listing);
 6766: 		} else {
 6767: 		    @listing_results =
 6768: 			map { &unescape($_); } split(/:/,$listing);
 6769: 		}
 6770: 		if ($listing_results[0] ne 'no_such_dir' && 
 6771: 		    $listing_results[0] ne 'empty'       &&
 6772: 		    $listing_results[0] ne 'con_lost') {
 6773: 		    foreach my $line (@listing_results) {
 6774: 			my ($entry) = split(/&/,$line,2);
 6775: 			$allusers{$entry} = 1;
 6776: 		    }
 6777: 		}
 6778:             }
 6779:             my $alluserstr='';
 6780:             foreach my $user (sort(keys(%allusers))) {
 6781:                 $alluserstr.=$user.'&user:';
 6782:             }
 6783:             $alluserstr=~s/:$//;
 6784:             return split(/:/,$alluserstr);
 6785:         } else {
 6786:             return ('missing user name');
 6787:         }
 6788:     } elsif(!defined($getpropath)) {
 6789:         my @all_domains = sort(&all_domains());
 6790:         foreach my $domain (@all_domains) {
 6791:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 6792:         }
 6793:         return @all_domains;
 6794:     } else {
 6795:         return ('missing domain');
 6796:     }
 6797: }
 6798: 
 6799: # --------------------------------------------- GetFileTimestamp
 6800: # This function utilizes dirlist and returns the date stamp for
 6801: # when it was last modified.  It will also return an error of -1
 6802: # if an error occurs
 6803: 
 6804: sub GetFileTimestamp {
 6805:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 6806:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 6807:     $studentName   = &LONCAPA::clean_username($studentName);
 6808:     my ($fileStat) = 
 6809:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
 6810:                                  undef,$getuserdir);
 6811:     my @stats = split('&', $fileStat);
 6812:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6813:         # @stats contains first the filename, then the stat output
 6814:         return $stats[10]; # so this is 10 instead of 9.
 6815:     } else {
 6816:         return -1;
 6817:     }
 6818: }
 6819: 
 6820: sub stat_file {
 6821:     my ($uri) = @_;
 6822:     $uri = &clutter_with_no_wrapper($uri);
 6823: 
 6824:     my ($udom,$uname,$file);
 6825:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 6826: 	($udom,$uname,$file) =
 6827: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 6828: 	$file = 'userfiles/'.$file;
 6829:     }
 6830:     if ($uri =~ m-^/res/-) {
 6831: 	($udom,$uname) = 
 6832: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 6833: 	$file = $uri;
 6834:     }
 6835: 
 6836:     if (!$udom || !$uname || !$file) {
 6837: 	# unable to handle the uri
 6838: 	return ();
 6839:     }
 6840:     my $getpropath;
 6841:     if ($file =~ /^userfiles\//) {
 6842:         $getpropath = 1;
 6843:     }
 6844:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
 6845:     my @stats = split('&', $result);
 6846:     
 6847:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6848: 	shift(@stats); #filename is first
 6849: 	return @stats;
 6850:     }
 6851:     return ();
 6852: }
 6853: 
 6854: # -------------------------------------------------------- Value of a Condition
 6855: 
 6856: # gets the value of a specific preevaluated condition
 6857: #    stored in the string  $env{user.state.<cid>}
 6858: # or looks up a condition reference in the bighash and if if hasn't
 6859: # already been evaluated recurses into docondval to get the value of
 6860: # the condition, then memoizing it to 
 6861: #   $env{user.state.<cid>.<condition>}
 6862: sub directcondval {
 6863:     my $number=shift;
 6864:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 6865: 	&Apache::lonuserstate::evalstate();
 6866:     }
 6867:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 6868: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 6869:     } elsif ($number =~ /^_/) {
 6870: 	my $sub_condition;
 6871: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6872: 		&GDBM_READER(),0640)) {
 6873: 	    $sub_condition=$bighash{'conditions'.$number};
 6874: 	    untie(%bighash);
 6875: 	}
 6876: 	my $value = &docondval($sub_condition);
 6877: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 6878: 	return $value;
 6879:     }
 6880:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 6881:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 6882:     } else {
 6883:        return 2;
 6884:     }
 6885: }
 6886: 
 6887: # get the collection of conditions for this resource
 6888: sub condval {
 6889:     my $condidx=shift;
 6890:     my $allpathcond='';
 6891:     foreach my $cond (split(/\|/,$condidx)) {
 6892: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 6893: 	    $allpathcond.=
 6894: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 6895: 	}
 6896:     }
 6897:     $allpathcond=~s/\|$//;
 6898:     return &docondval($allpathcond);
 6899: }
 6900: 
 6901: #evaluates an expression of conditions
 6902: sub docondval {
 6903:     my ($allpathcond) = @_;
 6904:     my $result=0;
 6905:     if ($env{'request.course.id'}
 6906: 	&& defined($allpathcond)) {
 6907: 	my $operand='|';
 6908: 	my @stack;
 6909: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 6910: 	    if ($chunk eq '(') {
 6911: 		push @stack,($operand,$result);
 6912: 	    } elsif ($chunk eq ')') {
 6913: 		my $before=pop @stack;
 6914: 		if (pop @stack eq '&') {
 6915: 		    $result=$result>$before?$before:$result;
 6916: 		} else {
 6917: 		    $result=$result>$before?$result:$before;
 6918: 		}
 6919: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 6920: 		$operand=$chunk;
 6921: 	    } else {
 6922: 		my $new=directcondval($chunk);
 6923: 		if ($operand eq '&') {
 6924: 		    $result=$result>$new?$new:$result;
 6925: 		} else {
 6926: 		    $result=$result>$new?$result:$new;
 6927: 		}
 6928: 	    }
 6929: 	}
 6930:     }
 6931:     return $result;
 6932: }
 6933: 
 6934: # ---------------------------------------------------- Devalidate courseresdata
 6935: 
 6936: sub devalidatecourseresdata {
 6937:     my ($coursenum,$coursedomain)=@_;
 6938:     my $hashid=$coursenum.':'.$coursedomain;
 6939:     &devalidate_cache_new('courseres',$hashid);
 6940: }
 6941: 
 6942: 
 6943: # --------------------------------------------------- Course Resourcedata Query
 6944: #
 6945: #  Parameters:
 6946: #      $coursenum    - Number of the course.
 6947: #      $coursedomain - Domain at which the course was created.
 6948: #  Returns:
 6949: #     A hash of the course parameters along (I think) with timestamps
 6950: #     and version info.
 6951: 
 6952: sub get_courseresdata {
 6953:     my ($coursenum,$coursedomain)=@_;
 6954:     my $coursehom=&homeserver($coursenum,$coursedomain);
 6955:     my $hashid=$coursenum.':'.$coursedomain;
 6956:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 6957:     my %dumpreply;
 6958:     unless (defined($cached)) {
 6959: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 6960: 	$result=\%dumpreply;
 6961: 	my ($tmp) = keys(%dumpreply);
 6962: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6963: 	    &do_cache_new('courseres',$hashid,$result,600);
 6964: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 6965: 	    return $tmp;
 6966: 	} elsif ($tmp =~ /^(error)/) {
 6967: 	    $result=undef;
 6968: 	    &do_cache_new('courseres',$hashid,$result,600);
 6969: 	}
 6970:     }
 6971:     return $result;
 6972: }
 6973: 
 6974: sub devalidateuserresdata {
 6975:     my ($uname,$udom)=@_;
 6976:     my $hashid="$udom:$uname";
 6977:     &devalidate_cache_new('userres',$hashid);
 6978: }
 6979: 
 6980: sub get_userresdata {
 6981:     my ($uname,$udom)=@_;
 6982:     #most student don\'t have any data set, check if there is some data
 6983:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 6984: 
 6985:     my $hashid="$udom:$uname";
 6986:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 6987:     if (!defined($cached)) {
 6988: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 6989: 	$result=\%resourcedata;
 6990: 	&do_cache_new('userres',$hashid,$result,600);
 6991:     }
 6992:     my ($tmp)=keys(%$result);
 6993:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 6994: 	return $result;
 6995:     }
 6996:     #error 2 occurs when the .db doesn't exist
 6997:     if ($tmp!~/error: 2 /) {
 6998: 	&logthis("<font color=\"blue\">WARNING:".
 6999: 		 " Trying to get resource data for ".
 7000: 		 $uname." at ".$udom.": ".
 7001: 		 $tmp."</font>");
 7002:     } elsif ($tmp=~/error: 2 /) {
 7003: 	#&EXT_cache_set($udom,$uname);
 7004: 	&do_cache_new('userres',$hashid,undef,600);
 7005: 	undef($tmp); # not really an error so don't send it back
 7006:     }
 7007:     return $tmp;
 7008: }
 7009: #----------------------------------------------- resdata - return resource data
 7010: #  Purpose:
 7011: #    Return resource data for either users or for a course.
 7012: #  Parameters:
 7013: #     $name      - Course/user name.
 7014: #     $domain    - Name of the domain the user/course is registered on.
 7015: #     $type      - Type of thing $name is (must be 'course' or 'user'
 7016: #     @which     - Array of names of resources desired.
 7017: #  Returns:
 7018: #     The value of the first reasource in @which that is found in the
 7019: #     resource hash.
 7020: #  Exceptional Conditions:
 7021: #     If the $type passed in is not valid (not the string 'course' or 
 7022: #     'user', an undefined  reference is returned.
 7023: #     If none of the resources are found, an undef is returned
 7024: sub resdata {
 7025:     my ($name,$domain,$type,@which)=@_;
 7026:     my $result;
 7027:     if ($type eq 'course') {
 7028: 	$result=&get_courseresdata($name,$domain);
 7029:     } elsif ($type eq 'user') {
 7030: 	$result=&get_userresdata($name,$domain);
 7031:     }
 7032:     if (!ref($result)) { return $result; }    
 7033:     foreach my $item (@which) {
 7034: 	if (defined($result->{$item->[0]})) {
 7035: 	    return [$result->{$item->[0]},$item->[1]];
 7036: 	}
 7037:     }
 7038:     return undef;
 7039: }
 7040: 
 7041: #
 7042: # EXT resource caching routines
 7043: #
 7044: 
 7045: sub clear_EXT_cache_status {
 7046:     &delenv('cache.EXT.');
 7047: }
 7048: 
 7049: sub EXT_cache_status {
 7050:     my ($target_domain,$target_user) = @_;
 7051:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7052:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 7053:         # We know already the user has no data
 7054:         return 1;
 7055:     } else {
 7056:         return 0;
 7057:     }
 7058: }
 7059: 
 7060: sub EXT_cache_set {
 7061:     my ($target_domain,$target_user) = @_;
 7062:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7063:     #&appenv({$cachename => time});
 7064: }
 7065: 
 7066: # --------------------------------------------------------- Value of a Variable
 7067: sub EXT {
 7068: 
 7069:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 7070:     unless ($varname) { return ''; }
 7071:     #get real user name/domain, courseid and symb
 7072:     my $courseid;
 7073:     my $publicuser;
 7074:     if ($symbparm) {
 7075: 	$symbparm=&get_symb_from_alias($symbparm);
 7076:     }
 7077:     if (!($uname && $udom)) {
 7078:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 7079:       if (!$symbparm) {	$symbparm=$cursymb; }
 7080:     } else {
 7081: 	$courseid=$env{'request.course.id'};
 7082:     }
 7083:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 7084:     my $rest;
 7085:     if (defined($therest[0])) {
 7086:        $rest=join('.',@therest);
 7087:     } else {
 7088:        $rest='';
 7089:     }
 7090: 
 7091:     my $qualifierrest=$qualifier;
 7092:     if ($rest) { $qualifierrest.='.'.$rest; }
 7093:     my $spacequalifierrest=$space;
 7094:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 7095:     if ($realm eq 'user') {
 7096: # --------------------------------------------------------------- user.resource
 7097: 	if ($space eq 'resource') {
 7098: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 7099: 		  || defined($Apache::lonhomework::parsing_a_task))
 7100: 		 &&
 7101: 		 ($symbparm eq &symbread()) ) {	
 7102: 		# if we are in the middle of processing the resource the
 7103: 		# get the value we are planning on committing
 7104:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 7105:                     return $Apache::lonhomework::results{$qualifierrest};
 7106:                 } else {
 7107:                     return $Apache::lonhomework::history{$qualifierrest};
 7108:                 }
 7109: 	    } else {
 7110: 		my %restored;
 7111: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 7112: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 7113: 		} else {
 7114: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 7115: 		}
 7116: 		return $restored{$qualifierrest};
 7117: 	    }
 7118: # ----------------------------------------------------------------- user.access
 7119:         } elsif ($space eq 'access') {
 7120: 	    # FIXME - not supporting calls for a specific user
 7121:             return &allowed($qualifier,$rest);
 7122: # ------------------------------------------ user.preferences, user.environment
 7123:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 7124: 	    if (($uname eq $env{'user.name'}) &&
 7125: 		($udom eq $env{'user.domain'})) {
 7126: 		return $env{join('.',('environment',$qualifierrest))};
 7127: 	    } else {
 7128: 		my %returnhash;
 7129: 		if (!$publicuser) {
 7130: 		    %returnhash=&userenvironment($udom,$uname,
 7131: 						 $qualifierrest);
 7132: 		}
 7133: 		return $returnhash{$qualifierrest};
 7134: 	    }
 7135: # ----------------------------------------------------------------- user.course
 7136:         } elsif ($space eq 'course') {
 7137: 	    # FIXME - not supporting calls for a specific user
 7138:             return $env{join('.',('request.course',$qualifier))};
 7139: # ------------------------------------------------------------------- user.role
 7140:         } elsif ($space eq 'role') {
 7141: 	    # FIXME - not supporting calls for a specific user
 7142:             my ($role,$where)=split(/\./,$env{'request.role'});
 7143:             if ($qualifier eq 'value') {
 7144: 		return $role;
 7145:             } elsif ($qualifier eq 'extent') {
 7146:                 return $where;
 7147:             }
 7148: # ----------------------------------------------------------------- user.domain
 7149:         } elsif ($space eq 'domain') {
 7150:             return $udom;
 7151: # ------------------------------------------------------------------- user.name
 7152:         } elsif ($space eq 'name') {
 7153:             return $uname;
 7154: # ---------------------------------------------------- Any other user namespace
 7155:         } else {
 7156: 	    my %reply;
 7157: 	    if (!$publicuser) {
 7158: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 7159: 	    }
 7160: 	    return $reply{$qualifierrest};
 7161:         }
 7162:     } elsif ($realm eq 'query') {
 7163: # ---------------------------------------------- pull stuff out of query string
 7164:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 7165: 						[$spacequalifierrest]);
 7166: 	return $env{'form.'.$spacequalifierrest}; 
 7167:    } elsif ($realm eq 'request') {
 7168: # ------------------------------------------------------------- request.browser
 7169:         if ($space eq 'browser') {
 7170: 	    if ($qualifier eq 'textremote') {
 7171: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 7172: 		    return 1;
 7173: 		} else {
 7174: 		    return 0;
 7175: 		}
 7176: 	    } else {
 7177: 		return $env{'browser.'.$qualifier};
 7178: 	    }
 7179: # ------------------------------------------------------------ request.filename
 7180:         } else {
 7181:             return $env{'request.'.$spacequalifierrest};
 7182:         }
 7183:     } elsif ($realm eq 'course') {
 7184: # ---------------------------------------------------------- course.description
 7185:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 7186:     } elsif ($realm eq 'resource') {
 7187: 
 7188: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 7189: 	    if (!$symbparm) { $symbparm=&symbread(); }
 7190: 	}
 7191: 
 7192: 	if ($space eq 'title') {
 7193: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 7194: 	    return &gettitle($symbparm);
 7195: 	}
 7196: 	
 7197: 	if ($space eq 'map') {
 7198: 	    my ($map) = &decode_symb($symbparm);
 7199: 	    return &symbread($map);
 7200: 	}
 7201: 	if ($space eq 'filename') {
 7202: 	    if ($symbparm) {
 7203: 		return &clutter((&decode_symb($symbparm))[2]);
 7204: 	    }
 7205: 	    return &hreflocation('',$env{'request.filename'});
 7206: 	}
 7207: 
 7208: 	my ($section, $group, @groups);
 7209: 	my ($courselevelm,$courselevel);
 7210: 	if ($symbparm && defined($courseid) && 
 7211: 	    $courseid eq $env{'request.course.id'}) {
 7212: 
 7213: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 7214: 
 7215: # ----------------------------------------------------- Cascading lookup scheme
 7216: 	    my $symbp=$symbparm;
 7217: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 7218: 
 7219: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 7220: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 7221: 
 7222: 	    if (($env{'user.name'} eq $uname) &&
 7223: 		($env{'user.domain'} eq $udom)) {
 7224: 		$section=$env{'request.course.sec'};
 7225:                 @groups = split(/:/,$env{'request.course.groups'});  
 7226:                 @groups=&sort_course_groups($courseid,@groups); 
 7227: 	    } else {
 7228: 		if (! defined($usection)) {
 7229: 		    $section=&getsection($udom,$uname,$courseid);
 7230: 		} else {
 7231: 		    $section = $usection;
 7232: 		}
 7233:                 @groups = &get_users_groups($udom,$uname,$courseid);
 7234: 	    }
 7235: 
 7236: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 7237: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 7238: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 7239: 
 7240: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 7241: 	    my $courselevelr=$courseid.'.'.$symbparm;
 7242: 	    $courselevelm=$courseid.'.'.$mapparm;
 7243: 
 7244: # ----------------------------------------------------------- first, check user
 7245: 
 7246: 	    my $userreply=&resdata($uname,$udom,'user',
 7247: 				       ([$courselevelr,'resource'],
 7248: 					[$courselevelm,'map'     ],
 7249: 					[$courselevel, 'course'  ]));
 7250: 	    if (defined($userreply)) { return &get_reply($userreply); }
 7251: 
 7252: # ------------------------------------------------ second, check some of course
 7253:             my $coursereply;
 7254:             if (@groups > 0) {
 7255:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 7256:                                        $mapparm,$spacequalifierrest);
 7257:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 7258:             }
 7259: 
 7260: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7261: 				  $env{'course.'.$courseid.'.domain'},
 7262: 				  'course',
 7263: 				  ([$seclevelr,   'resource'],
 7264: 				   [$seclevelm,   'map'     ],
 7265: 				   [$seclevel,    'course'  ],
 7266: 				   [$courselevelr,'resource']));
 7267: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7268: 
 7269: # ------------------------------------------------------ third, check map parms
 7270: 	    my %parmhash=();
 7271: 	    my $thisparm='';
 7272: 	    if (tie(%parmhash,'GDBM_File',
 7273: 		    $env{'request.course.fn'}.'_parms.db',
 7274: 		    &GDBM_READER(),0640)) {
 7275: 		$thisparm=$parmhash{$symbparm};
 7276: 		untie(%parmhash);
 7277: 	    }
 7278: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 7279: 	}
 7280: # ------------------------------------------ fourth, look in resource metadata
 7281: 
 7282: 	$spacequalifierrest=~s/\./\_/;
 7283: 	my $filename;
 7284: 	if (!$symbparm) { $symbparm=&symbread(); }
 7285: 	if ($symbparm) {
 7286: 	    $filename=(&decode_symb($symbparm))[2];
 7287: 	} else {
 7288: 	    $filename=$env{'request.filename'};
 7289: 	}
 7290: 	my $metadata=&metadata($filename,$spacequalifierrest);
 7291: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7292: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 7293: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7294: 
 7295: # ---------------------------------------------- fourth, look in rest of course
 7296: 	if ($symbparm && defined($courseid) && 
 7297: 	    $courseid eq $env{'request.course.id'}) {
 7298: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7299: 				     $env{'course.'.$courseid.'.domain'},
 7300: 				     'course',
 7301: 				     ([$courselevelm,'map'   ],
 7302: 				      [$courselevel, 'course']));
 7303: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7304: 	}
 7305: # ------------------------------------------------------------------ Cascade up
 7306: 	unless ($space eq '0') {
 7307: 	    my @parts=split(/_/,$space);
 7308: 	    my $id=pop(@parts);
 7309: 	    my $part=join('_',@parts);
 7310: 	    if ($part eq '') { $part='0'; }
 7311: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 7312: 				 $symbparm,$udom,$uname,$section,1);
 7313: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 7314: 	}
 7315: 	if ($recurse) { return undef; }
 7316: 	my $pack_def=&packages_tab_default($filename,$varname);
 7317: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 7318: # ---------------------------------------------------- Any other user namespace
 7319:     } elsif ($realm eq 'environment') {
 7320: # ----------------------------------------------------------------- environment
 7321: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 7322: 	    return $env{'environment.'.$spacequalifierrest};
 7323: 	} else {
 7324: 	    if ($uname eq 'anonymous' && $udom eq '') {
 7325: 		return '';
 7326: 	    }
 7327: 	    my %returnhash=&userenvironment($udom,$uname,
 7328: 					    $spacequalifierrest);
 7329: 	    return $returnhash{$spacequalifierrest};
 7330: 	}
 7331:     } elsif ($realm eq 'system') {
 7332: # ----------------------------------------------------------------- system.time
 7333: 	if ($space eq 'time') {
 7334: 	    return time;
 7335:         }
 7336:     } elsif ($realm eq 'server') {
 7337: # ----------------------------------------------------------------- system.time
 7338: 	if ($space eq 'name') {
 7339: 	    return $ENV{'SERVER_NAME'};
 7340:         }
 7341:     }
 7342:     return '';
 7343: }
 7344: 
 7345: sub get_reply {
 7346:     my ($reply_value) = @_;
 7347:     if (ref($reply_value) eq 'ARRAY') {
 7348:         if (wantarray) {
 7349: 	    return @$reply_value;
 7350:         }
 7351:         return $reply_value->[0];
 7352:     } else {
 7353:         return $reply_value;
 7354:     }
 7355: }
 7356: 
 7357: sub check_group_parms {
 7358:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 7359:     my @groupitems = ();
 7360:     my $resultitem;
 7361:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 7362:     foreach my $group (@{$groups}) {
 7363:         foreach my $level (@levels) {
 7364:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 7365:              push(@groupitems,[$item,$level->[1]]);
 7366:         }
 7367:     }
 7368:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 7369:                             $env{'course.'.$courseid.'.domain'},
 7370:                                      'course',@groupitems);
 7371:     return $coursereply;
 7372: }
 7373: 
 7374: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 7375:     my ($courseid,@groups) = @_;
 7376:     @groups = sort(@groups);
 7377:     return @groups;
 7378: }
 7379: 
 7380: sub packages_tab_default {
 7381:     my ($uri,$varname)=@_;
 7382:     my (undef,$part,$name)=split(/\./,$varname);
 7383: 
 7384:     my (@extension,@specifics,$do_default);
 7385:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 7386: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 7387: 	if ($pack_type eq 'default') {
 7388: 	    $do_default=1;
 7389: 	} elsif ($pack_type eq 'extension') {
 7390: 	    push(@extension,[$package,$pack_type,$pack_part]);
 7391: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 7392: 	    # only look at packages defaults for packages that this id is
 7393: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 7394: 	}
 7395:     }
 7396:     # first look for a package that matches the requested part id
 7397:     foreach my $package (@specifics) {
 7398: 	my (undef,$pack_type,$pack_part)=@{$package};
 7399: 	next if ($pack_part ne $part);
 7400: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7401: 	    return $packagetab{"$pack_type&$name&default"};
 7402: 	}
 7403:     }
 7404:     # look for any possible matching non extension_ package
 7405:     foreach my $package (@specifics) {
 7406: 	my (undef,$pack_type,$pack_part)=@{$package};
 7407: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7408: 	    return $packagetab{"$pack_type&$name&default"};
 7409: 	}
 7410: 	if ($pack_type eq 'part') { $pack_part='0'; }
 7411: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 7412: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 7413: 	}
 7414:     }
 7415:     # look for any posible extension_ match
 7416:     foreach my $package (@extension) {
 7417: 	my ($package,$pack_type)=@{$package};
 7418: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7419: 	    return $packagetab{"$pack_type&$name&default"};
 7420: 	}
 7421: 	if (defined($packagetab{$package."&$name&default"})) {
 7422: 	    return $packagetab{$package."&$name&default"};
 7423: 	}
 7424:     }
 7425:     # look for a global default setting
 7426:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 7427: 	return $packagetab{"default&$name&default"};
 7428:     }
 7429:     return undef;
 7430: }
 7431: 
 7432: sub add_prefix_and_part {
 7433:     my ($prefix,$part)=@_;
 7434:     my $keyroot;
 7435:     if (defined($prefix) && $prefix !~ /^__/) {
 7436: 	# prefix that has a part already
 7437: 	$keyroot=$prefix;
 7438:     } elsif (defined($prefix)) {
 7439: 	# prefix that is missing a part
 7440: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 7441:     } else {
 7442: 	# no prefix at all
 7443: 	if (defined($part)) { $keyroot='_'.$part; }
 7444:     }
 7445:     return $keyroot;
 7446: }
 7447: 
 7448: # ---------------------------------------------------------------- Get metadata
 7449: 
 7450: my %metaentry;
 7451: sub metadata {
 7452:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 7453:     $uri=&declutter($uri);
 7454:     # if it is a non metadata possible uri return quickly
 7455:     if (($uri eq '') || 
 7456: 	(($uri =~ m|^/*adm/|) && 
 7457: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 7458:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 7459: 	return undef;
 7460:     }
 7461:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 7462: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 7463: 	return undef;
 7464:     }
 7465:     my $filename=$uri;
 7466:     $uri=~s/\.meta$//;
 7467: #
 7468: # Is the metadata already cached?
 7469: # Look at timestamp of caching
 7470: # Everything is cached by the main uri, libraries are never directly cached
 7471: #
 7472:     if (!defined($liburi)) {
 7473: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 7474: 	if (defined($cached)) { return $result->{':'.$what}; }
 7475:     }
 7476:     {
 7477: #
 7478: # Is this a recursive call for a library?
 7479: #
 7480: #	if (! exists($metacache{$uri})) {
 7481: #	    $metacache{$uri}={};
 7482: #	}
 7483: 	my $cachetime = 60*60;
 7484:         if ($liburi) {
 7485: 	    $liburi=&declutter($liburi);
 7486:             $filename=$liburi;
 7487:         } else {
 7488: 	    &devalidate_cache_new('meta',$uri);
 7489: 	    undef(%metaentry);
 7490: 	}
 7491:         my %metathesekeys=();
 7492:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 7493: 	my $metastring;
 7494: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 7495: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 7496: 	    $metastring = 
 7497: 		&Apache::lonnet::ssi_body($which,
 7498: 					  ('grade_target' => 'meta'));
 7499: 	    $cachetime = 1; # only want this cached in the child not long term
 7500: 	} elsif ($uri !~ m -^(editupload)/-) {
 7501: 	    my $file=&filelocation('',&clutter($filename));
 7502: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 7503: 	    $metastring=&getfile($file);
 7504: 	}
 7505:         my $parser=HTML::LCParser->new(\$metastring);
 7506:         my $token;
 7507:         undef %metathesekeys;
 7508:         while ($token=$parser->get_token) {
 7509: 	    if ($token->[0] eq 'S') {
 7510: 		if (defined($token->[2]->{'package'})) {
 7511: #
 7512: # This is a package - get package info
 7513: #
 7514: 		    my $package=$token->[2]->{'package'};
 7515: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7516: 		    if (defined($token->[2]->{'id'})) { 
 7517: 			$keyroot.='_'.$token->[2]->{'id'}; 
 7518: 		    }
 7519: 		    if ($metaentry{':packages'}) {
 7520: 			$metaentry{':packages'}.=','.$package.$keyroot;
 7521: 		    } else {
 7522: 			$metaentry{':packages'}=$package.$keyroot;
 7523: 		    }
 7524: 		    foreach my $pack_entry (keys(%packagetab)) {
 7525: 			my $part=$keyroot;
 7526: 			$part=~s/^\_//;
 7527: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 7528: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 7529: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 7530: 			    # ignore package.tab specified default values
 7531:                             # here &package_tab_default() will fetch those
 7532: 			    if ($subp eq 'default') { next; }
 7533: 			    my $value=$packagetab{$pack_entry};
 7534: 			    my $unikey;
 7535: 			    if ($pack =~ /_0$/) {
 7536: 				$unikey='parameter_0_'.$name;
 7537: 				$part=0;
 7538: 			    } else {
 7539: 				$unikey='parameter'.$keyroot.'_'.$name;
 7540: 			    }
 7541: 			    if ($subp eq 'display') {
 7542: 				$value.=' [Part: '.$part.']';
 7543: 			    }
 7544: 			    $metaentry{':'.$unikey.'.part'}=$part;
 7545: 			    $metathesekeys{$unikey}=1;
 7546: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7547: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 7548: 			    }
 7549: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 7550: 				$metaentry{':'.$unikey}=
 7551: 				    $metaentry{':'.$unikey.'.default'};
 7552: 			    }
 7553: 			}
 7554: 		    }
 7555: 		} else {
 7556: #
 7557: # This is not a package - some other kind of start tag
 7558: #
 7559: 		    my $entry=$token->[1];
 7560: 		    my $unikey;
 7561: 		    if ($entry eq 'import') {
 7562: 			$unikey='';
 7563: 		    } else {
 7564: 			$unikey=$entry;
 7565: 		    }
 7566: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7567: 
 7568: 		    if (defined($token->[2]->{'id'})) { 
 7569: 			$unikey.='_'.$token->[2]->{'id'}; 
 7570: 		    }
 7571: 
 7572: 		    if ($entry eq 'import') {
 7573: #
 7574: # Importing a library here
 7575: #
 7576: 			if ($depthcount<20) {
 7577: 			    my $location=$parser->get_text('/import');
 7578: 			    my $dir=$filename;
 7579: 			    $dir=~s|[^/]*$||;
 7580: 			    $location=&filelocation($dir,$location);
 7581: 			    my $metadata = 
 7582: 				&metadata($uri,'keys', $location,$unikey,
 7583: 					  $depthcount+1);
 7584: 			    foreach my $meta (split(',',$metadata)) {
 7585: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 7586: 				$metathesekeys{$meta}=1;
 7587: 			    }
 7588: 			}
 7589: 		    } else { 
 7590: 			
 7591: 			if (defined($token->[2]->{'name'})) { 
 7592: 			    $unikey.='_'.$token->[2]->{'name'}; 
 7593: 			}
 7594: 			$metathesekeys{$unikey}=1;
 7595: 			foreach my $param (@{$token->[3]}) {
 7596: 			    $metaentry{':'.$unikey.'.'.$param} =
 7597: 				$token->[2]->{$param};
 7598: 			}
 7599: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 7600: 			my $default=$metaentry{':'.$unikey.'.default'};
 7601: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 7602: 		 # only ws inside the tag, and not in default, so use default
 7603: 		 # as value
 7604: 			    $metaentry{':'.$unikey}=$default;
 7605: 			} elsif ( $internaltext =~ /\S/ ) {
 7606: 		  # something interesting inside the tag
 7607: 			    $metaentry{':'.$unikey}=$internaltext;
 7608: 			} else {
 7609: 		  # no interesting values, don't set a default
 7610: 			}
 7611: # end of not-a-package not-a-library import
 7612: 		    }
 7613: # end of not-a-package start tag
 7614: 		}
 7615: # the next is the end of "start tag"
 7616: 	    }
 7617: 	}
 7618: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 7619: 	$extension = lc($extension);
 7620: 	if ($extension eq 'htm') { $extension='html'; }
 7621: 
 7622: 	foreach my $key (keys(%packagetab)) {
 7623: 	    #no specific packages #how's our extension
 7624: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 7625: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 7626: 					 \%metathesekeys);
 7627: 	}
 7628: 
 7629: 	if (!exists($metaentry{':packages'})
 7630: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 7631: 	    foreach my $key (keys(%packagetab)) {
 7632: 		#no specific packages well let's get default then
 7633: 		if ($key!~/^default&/) { next; }
 7634: 		&metadata_create_package_def($uri,$key,'default',
 7635: 					     \%metathesekeys);
 7636: 	    }
 7637: 	}
 7638: # are there custom rights to evaluate
 7639: 	if ($metaentry{':copyright'} eq 'custom') {
 7640: 
 7641:     #
 7642:     # Importing a rights file here
 7643:     #
 7644: 	    unless ($depthcount) {
 7645: 		my $location=$metaentry{':customdistributionfile'};
 7646: 		my $dir=$filename;
 7647: 		$dir=~s|[^/]*$||;
 7648: 		$location=&filelocation($dir,$location);
 7649: 		my $rights_metadata =
 7650: 		    &metadata($uri,'keys',$location,'_rights',
 7651: 			      $depthcount+1);
 7652: 		foreach my $rights (split(',',$rights_metadata)) {
 7653: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 7654: 		    $metathesekeys{$rights}=1;
 7655: 		}
 7656: 	    }
 7657: 	}
 7658: 	# uniqifiy package listing
 7659: 	my %seen;
 7660: 	my @uniq_packages =
 7661: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 7662: 	$metaentry{':packages'} = join(',',@uniq_packages);
 7663: 
 7664: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 7665: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 7666: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 7667: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 7668: # this is the end of "was not already recently cached
 7669:     }
 7670:     return $metaentry{':'.$what};
 7671: }
 7672: 
 7673: sub metadata_create_package_def {
 7674:     my ($uri,$key,$package,$metathesekeys)=@_;
 7675:     my ($pack,$name,$subp)=split(/\&/,$key);
 7676:     if ($subp eq 'default') { next; }
 7677:     
 7678:     if (defined($metaentry{':packages'})) {
 7679: 	$metaentry{':packages'}.=','.$package;
 7680:     } else {
 7681: 	$metaentry{':packages'}=$package;
 7682:     }
 7683:     my $value=$packagetab{$key};
 7684:     my $unikey;
 7685:     $unikey='parameter_0_'.$name;
 7686:     $metaentry{':'.$unikey.'.part'}=0;
 7687:     $$metathesekeys{$unikey}=1;
 7688:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7689: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 7690:     }
 7691:     if (defined($metaentry{':'.$unikey.'.default'})) {
 7692: 	$metaentry{':'.$unikey}=
 7693: 	    $metaentry{':'.$unikey.'.default'};
 7694:     }
 7695: }
 7696: 
 7697: sub metadata_generate_part0 {
 7698:     my ($metadata,$metacache,$uri) = @_;
 7699:     my %allnames;
 7700:     foreach my $metakey (keys(%$metadata)) {
 7701: 	if ($metakey=~/^parameter\_(.*)/) {
 7702: 	  my $part=$$metacache{':'.$metakey.'.part'};
 7703: 	  my $name=$$metacache{':'.$metakey.'.name'};
 7704: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 7705: 	    $allnames{$name}=$part;
 7706: 	  }
 7707: 	}
 7708:     }
 7709:     foreach my $name (keys(%allnames)) {
 7710:       $$metadata{"parameter_0_$name"}=1;
 7711:       my $key=":parameter_0_$name";
 7712:       $$metacache{"$key.part"}='0';
 7713:       $$metacache{"$key.name"}=$name;
 7714:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 7715: 					   $allnames{$name}.'_'.$name.
 7716: 					   '.type'};
 7717:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 7718: 			     '.display'};
 7719:       my $expr='[Part: '.$allnames{$name}.']';
 7720:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 7721:       $$metacache{"$key.display"}=$olddis;
 7722:     }
 7723: }
 7724: 
 7725: # ------------------------------------------------------ Devalidate title cache
 7726: 
 7727: sub devalidate_title_cache {
 7728:     my ($url)=@_;
 7729:     if (!$env{'request.course.id'}) { return; }
 7730:     my $symb=&symbread($url);
 7731:     if (!$symb) { return; }
 7732:     my $key=$env{'request.course.id'}."\0".$symb;
 7733:     &devalidate_cache_new('title',$key);
 7734: }
 7735: 
 7736: # ------------------------------------------------- Get the title of a resource
 7737: 
 7738: sub gettitle {
 7739:     my $urlsymb=shift;
 7740:     my $symb=&symbread($urlsymb);
 7741:     if ($symb) {
 7742: 	my $key=$env{'request.course.id'}."\0".$symb;
 7743: 	my ($result,$cached)=&is_cached_new('title',$key);
 7744: 	if (defined($cached)) { 
 7745: 	    return $result;
 7746: 	}
 7747: 	my ($map,$resid,$url)=&decode_symb($symb);
 7748: 	my $title='';
 7749: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 7750: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 7751: 	} else {
 7752: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7753: 		    &GDBM_READER(),0640)) {
 7754: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 7755: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 7756: 		untie(%bighash);
 7757: 	    }
 7758: 	}
 7759: 	$title=~s/\&colon\;/\:/gs;
 7760: 	if ($title) {
 7761: 	    return &do_cache_new('title',$key,$title,600);
 7762: 	}
 7763: 	$urlsymb=$url;
 7764:     }
 7765:     my $title=&metadata($urlsymb,'title');
 7766:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 7767:     return $title;
 7768: }
 7769: 
 7770: sub get_slot {
 7771:     my ($which,$cnum,$cdom)=@_;
 7772:     if (!$cnum || !$cdom) {
 7773: 	(undef,my $courseid)=&whichuser();
 7774: 	$cdom=$env{'course.'.$courseid.'.domain'};
 7775: 	$cnum=$env{'course.'.$courseid.'.num'};
 7776:     }
 7777:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 7778:     my %slotinfo;
 7779:     if (exists($remembered{$key})) {
 7780: 	$slotinfo{$which} = $remembered{$key};
 7781:     } else {
 7782: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 7783: 	&Apache::lonhomework::showhash(%slotinfo);
 7784: 	my ($tmp)=keys(%slotinfo);
 7785: 	if ($tmp=~/^error:/) { return (); }
 7786: 	$remembered{$key} = $slotinfo{$which};
 7787:     }
 7788:     if (ref($slotinfo{$which}) eq 'HASH') {
 7789: 	return %{$slotinfo{$which}};
 7790:     }
 7791:     return $slotinfo{$which};
 7792: }
 7793: # ------------------------------------------------- Update symbolic store links
 7794: 
 7795: sub symblist {
 7796:     my ($mapname,%newhash)=@_;
 7797:     $mapname=&deversion(&declutter($mapname));
 7798:     my %hash;
 7799:     if (($env{'request.course.fn'}) && (%newhash)) {
 7800:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7801:                       &GDBM_WRCREAT(),0640)) {
 7802: 	    foreach my $url (keys %newhash) {
 7803: 		next if ($url eq 'last_known'
 7804: 			 && $env{'form.no_update_last_known'});
 7805: 		$hash{declutter($url)}=&encode_symb($mapname,
 7806: 						    $newhash{$url}->[1],
 7807: 						    $newhash{$url}->[0]);
 7808:             }
 7809:             if (untie(%hash)) {
 7810: 		return 'ok';
 7811:             }
 7812:         }
 7813:     }
 7814:     return 'error';
 7815: }
 7816: 
 7817: # --------------------------------------------------------------- Verify a symb
 7818: 
 7819: sub symbverify {
 7820:     my ($symb,$thisurl)=@_;
 7821:     my $thisfn=$thisurl;
 7822:     $thisfn=&declutter($thisfn);
 7823: # direct jump to resource in page or to a sequence - will construct own symbs
 7824:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 7825: # check URL part
 7826:     my ($map,$resid,$url)=&decode_symb($symb);
 7827: 
 7828:     unless ($url eq $thisfn) { return 0; }
 7829: 
 7830:     $symb=&symbclean($symb);
 7831:     $thisurl=&deversion($thisurl);
 7832:     $thisfn=&deversion($thisfn);
 7833: 
 7834:     my %bighash;
 7835:     my $okay=0;
 7836: 
 7837:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7838:                             &GDBM_READER(),0640)) {
 7839:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 7840:         unless ($ids) { 
 7841:            $ids=$bighash{'ids_/'.$thisurl};
 7842:         }
 7843:         if ($ids) {
 7844: # ------------------------------------------------------------------- Has ID(s)
 7845: 	    foreach my $id (split(/\,/,$ids)) {
 7846: 	       my ($mapid,$resid)=split(/\./,$id);
 7847:                if (
 7848:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 7849:    eq $symb) { 
 7850: 		   if (($env{'request.role.adv'}) ||
 7851: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 7852: 		       $okay=1; 
 7853: 		   }
 7854: 	       }
 7855: 	   }
 7856:         }
 7857: 	untie(%bighash);
 7858:     }
 7859:     return $okay;
 7860: }
 7861: 
 7862: # --------------------------------------------------------------- Clean-up symb
 7863: 
 7864: sub symbclean {
 7865:     my $symb=shift;
 7866:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7867: # remove version from map
 7868:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 7869: 
 7870: # remove version from URL
 7871:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 7872: 
 7873: # remove wrapper
 7874: 
 7875:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 7876:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 7877:     return $symb;
 7878: }
 7879: 
 7880: # ---------------------------------------------- Split symb to find map and url
 7881: 
 7882: sub encode_symb {
 7883:     my ($map,$resid,$url)=@_;
 7884:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 7885: }
 7886: 
 7887: sub decode_symb {
 7888:     my $symb=shift;
 7889:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7890:     my ($map,$resid,$url)=split(/___/,$symb);
 7891:     return (&fixversion($map),$resid,&fixversion($url));
 7892: }
 7893: 
 7894: sub fixversion {
 7895:     my $fn=shift;
 7896:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 7897:     my %bighash;
 7898:     my $uri=&clutter($fn);
 7899:     my $key=$env{'request.course.id'}.'_'.$uri;
 7900: # is this cached?
 7901:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 7902:     if (defined($cached)) { return $result; }
 7903: # unfortunately not cached, or expired
 7904:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7905: 	    &GDBM_READER(),0640)) {
 7906:  	if ($bighash{'version_'.$uri}) {
 7907:  	    my $version=$bighash{'version_'.$uri};
 7908:  	    unless (($version eq 'mostrecent') || 
 7909: 		    ($version==&getversion($uri))) {
 7910:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 7911:  	    }
 7912:  	}
 7913:  	untie %bighash;
 7914:     }
 7915:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 7916: }
 7917: 
 7918: sub deversion {
 7919:     my $url=shift;
 7920:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 7921:     return $url;
 7922: }
 7923: 
 7924: # ------------------------------------------------------ Return symb list entry
 7925: 
 7926: sub symbread {
 7927:     my ($thisfn,$donotrecurse)=@_;
 7928:     my $cache_str='request.symbread.cached.'.$thisfn;
 7929:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 7930: # no filename provided? try from environment
 7931:     unless ($thisfn) {
 7932:         if ($env{'request.symb'}) {
 7933: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 7934: 	}
 7935: 	$thisfn=$env{'request.filename'};
 7936:     }
 7937:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7938: # is that filename actually a symb? Verify, clean, and return
 7939:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 7940: 	if (&symbverify($thisfn,$1)) {
 7941: 	    return $env{$cache_str}=&symbclean($thisfn);
 7942: 	}
 7943:     }
 7944:     $thisfn=declutter($thisfn);
 7945:     my %hash;
 7946:     my %bighash;
 7947:     my $syval='';
 7948:     if (($env{'request.course.fn'}) && ($thisfn)) {
 7949:         my $targetfn = $thisfn;
 7950:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 7951:             $targetfn = 'adm/wrapper/'.$thisfn;
 7952:         }
 7953: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 7954: 	    $targetfn=$1;
 7955: 	}
 7956:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7957:                       &GDBM_READER(),0640)) {
 7958: 	    $syval=$hash{$targetfn};
 7959:             untie(%hash);
 7960:         }
 7961: # ---------------------------------------------------------- There was an entry
 7962:         if ($syval) {
 7963: 	    #unless ($syval=~/\_\d+$/) {
 7964: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 7965: 		    #&appenv({'request.ambiguous' => $thisfn});
 7966: 		    #return $env{$cache_str}='';
 7967: 		#}    
 7968: 		#$syval.=$1;
 7969: 	    #}
 7970:         } else {
 7971: # ------------------------------------------------------- Was not in symb table
 7972:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7973:                             &GDBM_READER(),0640)) {
 7974: # ---------------------------------------------- Get ID(s) for current resource
 7975:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 7976:               unless ($ids) { 
 7977:                  $ids=$bighash{'ids_/'.$thisfn};
 7978:               }
 7979:               unless ($ids) {
 7980: # alias?
 7981: 		  $ids=$bighash{'mapalias_'.$thisfn};
 7982:               }
 7983:               if ($ids) {
 7984: # ------------------------------------------------------------------- Has ID(s)
 7985:                  my @possibilities=split(/\,/,$ids);
 7986:                  if ($#possibilities==0) {
 7987: # ----------------------------------------------- There is only one possibility
 7988: 		     my ($mapid,$resid)=split(/\./,$ids);
 7989: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7990: 						    $resid,$thisfn);
 7991:                  } elsif (!$donotrecurse) {
 7992: # ------------------------------------------ There is more than one possibility
 7993:                      my $realpossible=0;
 7994:                      foreach my $id (@possibilities) {
 7995: 			 my $file=$bighash{'src_'.$id};
 7996:                          if (&allowed('bre',$file)) {
 7997:          		    my ($mapid,$resid)=split(/\./,$id);
 7998:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 7999: 				$realpossible++;
 8000:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 8001: 						    $resid,$thisfn);
 8002:                             }
 8003: 			 }
 8004:                      }
 8005: 		     if ($realpossible!=1) { $syval=''; }
 8006:                  } else {
 8007:                      $syval='';
 8008:                  }
 8009: 	      }
 8010:               untie(%bighash)
 8011:            }
 8012:         }
 8013:         if ($syval) {
 8014: 	    return $env{$cache_str}=$syval;
 8015:         }
 8016:     }
 8017:     &appenv({'request.ambiguous' => $thisfn});
 8018:     return $env{$cache_str}='';
 8019: }
 8020: 
 8021: # ---------------------------------------------------------- Return random seed
 8022: 
 8023: sub numval {
 8024:     my $txt=shift;
 8025:     $txt=~tr/A-J/0-9/;
 8026:     $txt=~tr/a-j/0-9/;
 8027:     $txt=~tr/K-T/0-9/;
 8028:     $txt=~tr/k-t/0-9/;
 8029:     $txt=~tr/U-Z/0-5/;
 8030:     $txt=~tr/u-z/0-5/;
 8031:     $txt=~s/\D//g;
 8032:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 8033:     return int($txt);
 8034: }
 8035: 
 8036: sub numval2 {
 8037:     my $txt=shift;
 8038:     $txt=~tr/A-J/0-9/;
 8039:     $txt=~tr/a-j/0-9/;
 8040:     $txt=~tr/K-T/0-9/;
 8041:     $txt=~tr/k-t/0-9/;
 8042:     $txt=~tr/U-Z/0-5/;
 8043:     $txt=~tr/u-z/0-5/;
 8044:     $txt=~s/\D//g;
 8045:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8046:     my $total;
 8047:     foreach my $val (@txts) { $total+=$val; }
 8048:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 8049:     return int($total);
 8050: }
 8051: 
 8052: sub numval3 {
 8053:     use integer;
 8054:     my $txt=shift;
 8055:     $txt=~tr/A-J/0-9/;
 8056:     $txt=~tr/a-j/0-9/;
 8057:     $txt=~tr/K-T/0-9/;
 8058:     $txt=~tr/k-t/0-9/;
 8059:     $txt=~tr/U-Z/0-5/;
 8060:     $txt=~tr/u-z/0-5/;
 8061:     $txt=~s/\D//g;
 8062:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8063:     my $total;
 8064:     foreach my $val (@txts) { $total+=$val; }
 8065:     if ($_64bit) { $total=(($total<<32)>>32); }
 8066:     return $total;
 8067: }
 8068: 
 8069: sub digest {
 8070:     my ($data)=@_;
 8071:     my $digest=&Digest::MD5::md5($data);
 8072:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 8073:     my ($e,$f);
 8074:     {
 8075:         use integer;
 8076:         $e=($a+$b);
 8077:         $f=($c+$d);
 8078:         if ($_64bit) {
 8079:             $e=(($e<<32)>>32);
 8080:             $f=(($f<<32)>>32);
 8081:         }
 8082:     }
 8083:     if (wantarray) {
 8084: 	return ($e,$f);
 8085:     } else {
 8086: 	my $g;
 8087: 	{
 8088: 	    use integer;
 8089: 	    $g=($e+$f);
 8090: 	    if ($_64bit) {
 8091: 		$g=(($g<<32)>>32);
 8092: 	    }
 8093: 	}
 8094: 	return $g;
 8095:     }
 8096: }
 8097: 
 8098: sub latest_rnd_algorithm_id {
 8099:     return '64bit5';
 8100: }
 8101: 
 8102: sub get_rand_alg {
 8103:     my ($courseid)=@_;
 8104:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 8105:     if ($courseid) {
 8106: 	return $env{"course.$courseid.rndseed"};
 8107:     }
 8108:     return &latest_rnd_algorithm_id();
 8109: }
 8110: 
 8111: sub validCODE {
 8112:     my ($CODE)=@_;
 8113:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 8114:     return 0;
 8115: }
 8116: 
 8117: sub getCODE {
 8118:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 8119:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 8120: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 8121: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 8122: 	return $Apache::lonhomework::history{'resource.CODE'};
 8123:     }
 8124:     return undef;
 8125: }
 8126: 
 8127: sub rndseed {
 8128:     my ($symb,$courseid,$domain,$username)=@_;
 8129:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 8130:     if (!defined($symb)) {
 8131: 	unless ($symb=$wsymb) { return time; }
 8132:     }
 8133:     if (!$courseid) { $courseid=$wcourseid; }
 8134:     if (!$domain) { $domain=$wdomain; }
 8135:     if (!$username) { $username=$wusername }
 8136:     my $which=&get_rand_alg();
 8137: 
 8138:     if (defined(&getCODE())) {
 8139: 	if ($which eq '64bit5') {
 8140: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 8141: 	} elsif ($which eq '64bit4') {
 8142: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 8143: 	} else {
 8144: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 8145: 	}
 8146:     } elsif ($which eq '64bit5') {
 8147: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 8148:     } elsif ($which eq '64bit4') {
 8149: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 8150:     } elsif ($which eq '64bit3') {
 8151: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 8152:     } elsif ($which eq '64bit2') {
 8153: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 8154:     } elsif ($which eq '64bit') {
 8155: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 8156:     }
 8157:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 8158: }
 8159: 
 8160: sub rndseed_32bit {
 8161:     my ($symb,$courseid,$domain,$username)=@_;
 8162:     {
 8163: 	use integer;
 8164: 	my $symbchck=unpack("%32C*",$symb) << 27;
 8165: 	my $symbseed=numval($symb) << 22;
 8166: 	my $namechck=unpack("%32C*",$username) << 17;
 8167: 	my $nameseed=numval($username) << 12;
 8168: 	my $domainseed=unpack("%32C*",$domain) << 7;
 8169: 	my $courseseed=unpack("%32C*",$courseid);
 8170: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 8171: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8172: 	#&logthis("rndseed :$num:$symb");
 8173: 	if ($_64bit) { $num=(($num<<32)>>32); }
 8174: 	return $num;
 8175:     }
 8176: }
 8177: 
 8178: sub rndseed_64bit {
 8179:     my ($symb,$courseid,$domain,$username)=@_;
 8180:     {
 8181: 	use integer;
 8182: 	my $symbchck=unpack("%32S*",$symb) << 21;
 8183: 	my $symbseed=numval($symb) << 10;
 8184: 	my $namechck=unpack("%32S*",$username);
 8185: 	
 8186: 	my $nameseed=numval($username) << 21;
 8187: 	my $domainseed=unpack("%32S*",$domain) << 10;
 8188: 	my $courseseed=unpack("%32S*",$courseid);
 8189: 	
 8190: 	my $num1=$symbchck+$symbseed+$namechck;
 8191: 	my $num2=$nameseed+$domainseed+$courseseed;
 8192: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8193: 	#&logthis("rndseed :$num:$symb");
 8194: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8195: 	return "$num1,$num2";
 8196:     }
 8197: }
 8198: 
 8199: sub rndseed_64bit2 {
 8200:     my ($symb,$courseid,$domain,$username)=@_;
 8201:     {
 8202: 	use integer;
 8203: 	# strings need to be an even # of cahracters long, it it is odd the
 8204:         # last characters gets thrown away
 8205: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8206: 	my $symbseed=numval($symb) << 10;
 8207: 	my $namechck=unpack("%32S*",$username.' ');
 8208: 	
 8209: 	my $nameseed=numval($username) << 21;
 8210: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8211: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8212: 	
 8213: 	my $num1=$symbchck+$symbseed+$namechck;
 8214: 	my $num2=$nameseed+$domainseed+$courseseed;
 8215: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8216: 	#&logthis("rndseed :$num:$symb");
 8217: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8218: 	return "$num1,$num2";
 8219:     }
 8220: }
 8221: 
 8222: sub rndseed_64bit3 {
 8223:     my ($symb,$courseid,$domain,$username)=@_;
 8224:     {
 8225: 	use integer;
 8226: 	# strings need to be an even # of cahracters long, it it is odd the
 8227:         # last characters gets thrown away
 8228: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8229: 	my $symbseed=numval2($symb) << 10;
 8230: 	my $namechck=unpack("%32S*",$username.' ');
 8231: 	
 8232: 	my $nameseed=numval2($username) << 21;
 8233: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8234: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8235: 	
 8236: 	my $num1=$symbchck+$symbseed+$namechck;
 8237: 	my $num2=$nameseed+$domainseed+$courseseed;
 8238: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8239: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8240: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8241: 	
 8242: 	return "$num1:$num2";
 8243:     }
 8244: }
 8245: 
 8246: sub rndseed_64bit4 {
 8247:     my ($symb,$courseid,$domain,$username)=@_;
 8248:     {
 8249: 	use integer;
 8250: 	# strings need to be an even # of cahracters long, it it is odd the
 8251:         # last characters gets thrown away
 8252: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8253: 	my $symbseed=numval3($symb) << 10;
 8254: 	my $namechck=unpack("%32S*",$username.' ');
 8255: 	
 8256: 	my $nameseed=numval3($username) << 21;
 8257: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8258: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8259: 	
 8260: 	my $num1=$symbchck+$symbseed+$namechck;
 8261: 	my $num2=$nameseed+$domainseed+$courseseed;
 8262: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8263: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8264: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8265: 	
 8266: 	return "$num1:$num2";
 8267:     }
 8268: }
 8269: 
 8270: sub rndseed_64bit5 {
 8271:     my ($symb,$courseid,$domain,$username)=@_;
 8272:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 8273:     return "$num1:$num2";
 8274: }
 8275: 
 8276: sub rndseed_CODE_64bit {
 8277:     my ($symb,$courseid,$domain,$username)=@_;
 8278:     {
 8279: 	use integer;
 8280: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8281: 	my $symbseed=numval2($symb);
 8282: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8283: 	my $CODEseed=numval(&getCODE());
 8284: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8285: 	my $num1=$symbseed+$CODEchck;
 8286: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8287: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8288: 	#&logthis("rndseed :$num1:$num2:$symb");
 8289: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8290: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8291: 	return "$num1:$num2";
 8292:     }
 8293: }
 8294: 
 8295: sub rndseed_CODE_64bit4 {
 8296:     my ($symb,$courseid,$domain,$username)=@_;
 8297:     {
 8298: 	use integer;
 8299: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8300: 	my $symbseed=numval3($symb);
 8301: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8302: 	my $CODEseed=numval3(&getCODE());
 8303: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8304: 	my $num1=$symbseed+$CODEchck;
 8305: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8306: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8307: 	#&logthis("rndseed :$num1:$num2:$symb");
 8308: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8309: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8310: 	return "$num1:$num2";
 8311:     }
 8312: }
 8313: 
 8314: sub rndseed_CODE_64bit5 {
 8315:     my ($symb,$courseid,$domain,$username)=@_;
 8316:     my $code = &getCODE();
 8317:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 8318:     return "$num1:$num2";
 8319: }
 8320: 
 8321: sub setup_random_from_rndseed {
 8322:     my ($rndseed)=@_;
 8323:     if ($rndseed =~/([,:])/) {
 8324: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 8325: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 8326:     } else {
 8327: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 8328:     }
 8329: }
 8330: 
 8331: sub latest_receipt_algorithm_id {
 8332:     return 'receipt3';
 8333: }
 8334: 
 8335: sub recunique {
 8336:     my $fucourseid=shift;
 8337:     my $unique;
 8338:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 8339: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8340: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 8341:     } else {
 8342: 	$unique=$perlvar{'lonReceipt'};
 8343:     }
 8344:     return unpack("%32C*",$unique);
 8345: }
 8346: 
 8347: sub recprefix {
 8348:     my $fucourseid=shift;
 8349:     my $prefix;
 8350:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 8351: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8352: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 8353:     } else {
 8354: 	$prefix=$perlvar{'lonHostID'};
 8355:     }
 8356:     return unpack("%32C*",$prefix);
 8357: }
 8358: 
 8359: sub ireceipt {
 8360:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 8361: 
 8362:     my $return =&recprefix($fucourseid).'-';
 8363: 
 8364:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 8365: 	$env{'request.state'} eq 'construct') {
 8366: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 8367: 	return $return;
 8368:     }
 8369: 
 8370:     my $cuname=unpack("%32C*",$funame);
 8371:     my $cudom=unpack("%32C*",$fudom);
 8372:     my $cucourseid=unpack("%32C*",$fucourseid);
 8373:     my $cusymb=unpack("%32C*",$fusymb);
 8374:     my $cunique=&recunique($fucourseid);
 8375:     my $cpart=unpack("%32S*",$part);
 8376:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 8377: 
 8378: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 8379: 			       
 8380: 	$return.= ($cunique%$cuname+
 8381: 		   $cunique%$cudom+
 8382: 		   $cusymb%$cuname+
 8383: 		   $cusymb%$cudom+
 8384: 		   $cucourseid%$cuname+
 8385: 		   $cucourseid%$cudom+
 8386: 		   $cpart%$cuname+
 8387: 		   $cpart%$cudom);
 8388:     } else {
 8389: 	$return.= ($cunique%$cuname+
 8390: 		   $cunique%$cudom+
 8391: 		   $cusymb%$cuname+
 8392: 		   $cusymb%$cudom+
 8393: 		   $cucourseid%$cuname+
 8394: 		   $cucourseid%$cudom);
 8395:     }
 8396:     return $return;
 8397: }
 8398: 
 8399: sub receipt {
 8400:     my ($part)=@_;
 8401:     my ($symb,$courseid,$domain,$name) = &whichuser();
 8402:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 8403: }
 8404: 
 8405: sub whichuser {
 8406:     my ($passedsymb)=@_;
 8407:     my ($symb,$courseid,$domain,$name,$publicuser);
 8408:     if (defined($env{'form.grade_symb'})) {
 8409: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 8410: 	my $allowed=&allowed('vgr',$tmp_courseid);
 8411: 	if (!$allowed &&
 8412: 	    exists($env{'request.course.sec'}) &&
 8413: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 8414: 	    $allowed=&allowed('vgr',$tmp_courseid.
 8415: 			      '/'.$env{'request.course.sec'});
 8416: 	}
 8417: 	if ($allowed) {
 8418: 	    ($symb)=&get_env_multiple('form.grade_symb');
 8419: 	    $courseid=$tmp_courseid;
 8420: 	    ($domain)=&get_env_multiple('form.grade_domain');
 8421: 	    ($name)=&get_env_multiple('form.grade_username');
 8422: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 8423: 	}
 8424:     }
 8425:     if (!$passedsymb) {
 8426: 	$symb=&symbread();
 8427:     } else {
 8428: 	$symb=$passedsymb;
 8429:     }
 8430:     $courseid=$env{'request.course.id'};
 8431:     $domain=$env{'user.domain'};
 8432:     $name=$env{'user.name'};
 8433:     if ($name eq 'public' && $domain eq 'public') {
 8434: 	if (!defined($env{'form.username'})) {
 8435: 	    $env{'form.username'}.=time.rand(10000000);
 8436: 	}
 8437: 	$name.=$env{'form.username'};
 8438:     }
 8439:     return ($symb,$courseid,$domain,$name,$publicuser);
 8440: 
 8441: }
 8442: 
 8443: # ------------------------------------------------------------ Serves up a file
 8444: # returns either the contents of the file or 
 8445: # -1 if the file doesn't exist
 8446: #
 8447: # if the target is a file that was uploaded via DOCS, 
 8448: # a check will be made to see if a current copy exists on the local server,
 8449: # if it does this will be served, otherwise a copy will be retrieved from
 8450: # the home server for the course and stored in /home/httpd/html/userfiles on
 8451: # the local server.   
 8452: 
 8453: sub getfile {
 8454:     my ($file) = @_;
 8455:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8456:     &repcopy($file);
 8457:     return &readfile($file);
 8458: }
 8459: 
 8460: sub repcopy_userfile {
 8461:     my ($file)=@_;
 8462:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8463:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 8464:     my ($cdom,$cnum,$filename) = 
 8465: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 8466:     my $uri="/uploaded/$cdom/$cnum/$filename";
 8467:     if (-e "$file") {
 8468: # we already have a local copy, check it out
 8469: 	my @fileinfo = stat($file);
 8470: 	my $rtncode;
 8471: 	my $info;
 8472: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 8473: 	if ($lwpresp ne 'ok') {
 8474: # there is no such file anymore, even though we had a local copy
 8475: 	    if ($rtncode eq '404') {
 8476: 		unlink($file);
 8477: 	    }
 8478: 	    return -1;
 8479: 	}
 8480: 	if ($info < $fileinfo[9]) {
 8481: # nice, the file we have is up-to-date, just say okay
 8482: 	    return 'ok';
 8483: 	} else {
 8484: # the file is outdated, get rid of it
 8485: 	    unlink($file);
 8486: 	}
 8487:     }
 8488: # one way or the other, at this point, we don't have the file
 8489: # construct the correct path for the file
 8490:     my @parts = ($cdom,$cnum); 
 8491:     if ($filename =~ m|^(.+)/[^/]+$|) {
 8492: 	push @parts, split(/\//,$1);
 8493:     }
 8494:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 8495:     foreach my $part (@parts) {
 8496: 	$path .= '/'.$part;
 8497: 	if (!-e $path) {
 8498: 	    mkdir($path,0770);
 8499: 	}
 8500:     }
 8501: # now the path exists for sure
 8502: # get a user agent
 8503:     my $ua=new LWP::UserAgent;
 8504:     my $transferfile=$file.'.in.transfer';
 8505: # FIXME: this should flock
 8506:     if (-e $transferfile) { return 'ok'; }
 8507:     my $request;
 8508:     $uri=~s/^\///;
 8509:     my $homeserver = &homeserver($cnum,$cdom);
 8510:     my $protocol = $protocol{$homeserver};
 8511:     $protocol = 'http' if ($protocol ne 'https');
 8512:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
 8513:     my $response=$ua->request($request,$transferfile);
 8514: # did it work?
 8515:     if ($response->is_error()) {
 8516: 	unlink($transferfile);
 8517: 	&logthis("Userfile repcopy failed for $uri");
 8518: 	return -1;
 8519:     }
 8520: # worked, rename the transfer file
 8521:     rename($transferfile,$file);
 8522:     return 'ok';
 8523: }
 8524: 
 8525: sub tokenwrapper {
 8526:     my $uri=shift;
 8527:     $uri=~s|^https?\://([^/]+)||;
 8528:     $uri=~s|^/||;
 8529:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 8530:     my $token=$1;
 8531:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 8532:     if ($udom && $uname && $file) {
 8533: 	$file=~s|(\?\.*)*$||;
 8534:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 8535:         my $homeserver = &homeserver($uname,$udom);
 8536:         my $protocol = $protocol{$homeserver};
 8537:         $protocol = 'http' if ($protocol ne 'https');
 8538:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
 8539:                (($uri=~/\?/)?'&':'?').'token='.$token.
 8540:                                '&tokenissued='.$perlvar{'lonHostID'};
 8541:     } else {
 8542:         return '/adm/notfound.html';
 8543:     }
 8544: }
 8545: 
 8546: # call with reqtype HEAD: get last modification time
 8547: # call with reqtype GET: get the file contents
 8548: # Do not call this with reqtype GET for large files! It loads everything into memory
 8549: #
 8550: sub getuploaded {
 8551:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 8552:     $uri=~s/^\///;
 8553:     my $homeserver = &homeserver($cnum,$cdom);
 8554:     my $protocol = $protocol{$homeserver};
 8555:     $protocol = 'http' if ($protocol ne 'https');
 8556:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
 8557:     my $ua=new LWP::UserAgent;
 8558:     my $request=new HTTP::Request($reqtype,$uri);
 8559:     my $response=$ua->request($request);
 8560:     $$rtncode = $response->code;
 8561:     if (! $response->is_success()) {
 8562: 	return 'failed';
 8563:     }      
 8564:     if ($reqtype eq 'HEAD') {
 8565: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 8566:     } elsif ($reqtype eq 'GET') {
 8567: 	$$info = $response->content;
 8568:     }
 8569:     return 'ok';
 8570: }
 8571: 
 8572: sub readfile {
 8573:     my $file = shift;
 8574:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 8575:     my $fh;
 8576:     open($fh,"<$file");
 8577:     my $a='';
 8578:     while (my $line = <$fh>) { $a .= $line; }
 8579:     return $a;
 8580: }
 8581: 
 8582: sub filelocation {
 8583:     my ($dir,$file) = @_;
 8584:     my $location;
 8585:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 8586: 
 8587:     if ($file =~ m-^/adm/-) {
 8588: 	$file=~s-^/adm/wrapper/-/-;
 8589: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8590:     }
 8591: 
 8592:     if ($file=~m:^/~:) { # is a contruction space reference
 8593:         $location = $file;
 8594:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 8595:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 8596: 	# is a correct contruction space reference
 8597:         $location = $file;
 8598:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
 8599:         $location = $file;
 8600:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 8601:         my ($udom,$uname,$filename)=
 8602:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 8603:         my $home=&homeserver($uname,$udom);
 8604:         my $is_me=0;
 8605:         my @ids=&current_machine_ids();
 8606:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 8607:         if ($is_me) {
 8608:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
 8609:         } else {
 8610:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 8611:   	      $udom.'/'.$uname.'/'.$filename;
 8612:         }
 8613:     } elsif ($file =~ m-^/adm/-) {
 8614: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 8615:     } else {
 8616:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8617:         $file=~s:^/res/:/:;
 8618:         if ( !( $file =~ m:^/:) ) {
 8619:             $location = $dir. '/'.$file;
 8620:         } else {
 8621:             $location = '/home/httpd/html/res'.$file;
 8622:         }
 8623:     }
 8624:     $location=~s://+:/:g; # remove duplicate /
 8625:     while ($location=~m{/\.\./}) {
 8626: 	if ($location =~ m{/[^/]+/\.\./}) {
 8627: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 8628: 	} else {
 8629: 	    $location=~ s{/\.\./}{/}g;
 8630: 	}
 8631:     } #remove dir/..
 8632:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 8633:     return $location;
 8634: }
 8635: 
 8636: sub hreflocation {
 8637:     my ($dir,$file)=@_;
 8638:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
 8639: 	$file=filelocation($dir,$file);
 8640:     } elsif ($file=~m-^/adm/-) {
 8641: 	$file=~s-^/adm/wrapper/-/-;
 8642: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8643:     }
 8644:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 8645: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 8646:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 8647: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 8648:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 8649: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 8650: 	    -/uploaded/$1/$2/-x;
 8651:     }
 8652:     if ($file=~ m{^/userfiles/}) {
 8653: 	$file =~ s{^/userfiles/}{/uploaded/};
 8654:     }
 8655:     return $file;
 8656: }
 8657: 
 8658: sub current_machine_domains {
 8659:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 8660: }
 8661: 
 8662: sub machine_domains {
 8663:     my ($hostname) = @_;
 8664:     my @domains;
 8665:     my %hostname = &all_hostnames();
 8666:     while( my($id, $name) = each(%hostname)) {
 8667: #	&logthis("-$id-$name-$hostname-");
 8668: 	if ($hostname eq $name) {
 8669: 	    push(@domains,&host_domain($id));
 8670: 	}
 8671:     }
 8672:     return @domains;
 8673: }
 8674: 
 8675: sub current_machine_ids {
 8676:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 8677: }
 8678: 
 8679: sub machine_ids {
 8680:     my ($hostname) = @_;
 8681:     $hostname ||= &hostname($perlvar{'lonHostID'});
 8682:     my @ids;
 8683:     my %name_to_host = &all_names();
 8684:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 8685: 	return @{ $name_to_host{$hostname} };
 8686:     }
 8687:     return;
 8688: }
 8689: 
 8690: sub additional_machine_domains {
 8691:     my @domains;
 8692:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 8693:     while( my $line = <$fh>) {
 8694:         $line =~ s/\s//g;
 8695:         push(@domains,$line);
 8696:     }
 8697:     return @domains;
 8698: }
 8699: 
 8700: sub default_login_domain {
 8701:     my $domain = $perlvar{'lonDefDomain'};
 8702:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 8703:     foreach my $posdom (&current_machine_domains(),
 8704:                         &additional_machine_domains()) {
 8705:         if (lc($posdom) eq lc($testdomain)) {
 8706:             $domain=$posdom;
 8707:             last;
 8708:         }
 8709:     }
 8710:     return $domain;
 8711: }
 8712: 
 8713: # ------------------------------------------------------------- Declutters URLs
 8714: 
 8715: sub declutter {
 8716:     my $thisfn=shift;
 8717:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8718:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8719:     $thisfn=~s/^\///;
 8720:     $thisfn=~s|^adm/wrapper/||;
 8721:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 8722:     $thisfn=~s/^res\///;
 8723:     $thisfn=~s/\?.+$//;
 8724:     return $thisfn;
 8725: }
 8726: 
 8727: # ------------------------------------------------------------- Clutter up URLs
 8728: 
 8729: sub clutter {
 8730:     my $thisfn='/'.&declutter(shift);
 8731:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 8732: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 8733:        $thisfn='/res'.$thisfn; 
 8734:     }
 8735:     if ($thisfn !~m|/adm|) {
 8736: 	if ($thisfn =~ m|/ext/|) {
 8737: 	    $thisfn='/adm/wrapper'.$thisfn;
 8738: 	} else {
 8739: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 8740: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 8741: 	    if ($embstyle eq 'ssi'
 8742: 		|| ($embstyle eq 'hdn')
 8743: 		|| ($embstyle eq 'rat')
 8744: 		|| ($embstyle eq 'prv')
 8745: 		|| ($embstyle eq 'ign')) {
 8746: 		#do nothing with these
 8747: 	    } elsif (($embstyle eq 'img') 
 8748: 		|| ($embstyle eq 'emb')
 8749: 		|| ($embstyle eq 'wrp')) {
 8750: 		$thisfn='/adm/wrapper'.$thisfn;
 8751: 	    } elsif ($embstyle eq 'unk'
 8752: 		     && $thisfn!~/\.(sequence|page)$/) {
 8753: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 8754: 	    } else {
 8755: #		&logthis("Got a blank emb style");
 8756: 	    }
 8757: 	}
 8758:     }
 8759:     return $thisfn;
 8760: }
 8761: 
 8762: sub clutter_with_no_wrapper {
 8763:     my $uri = &clutter(shift);
 8764:     if ($uri =~ m-^/adm/-) {
 8765: 	$uri =~ s-^/adm/wrapper/-/-;
 8766: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 8767:     }
 8768:     return $uri;
 8769: }
 8770: 
 8771: sub freeze_escape {
 8772:     my ($value)=@_;
 8773:     if (ref($value)) {
 8774: 	$value=&nfreeze($value);
 8775: 	return '__FROZEN__'.&escape($value);
 8776:     }
 8777:     return &escape($value);
 8778: }
 8779: 
 8780: 
 8781: sub thaw_unescape {
 8782:     my ($value)=@_;
 8783:     if ($value =~ /^__FROZEN__/) {
 8784: 	substr($value,0,10,undef);
 8785: 	$value=&unescape($value);
 8786: 	return &thaw($value);
 8787:     }
 8788:     return &unescape($value);
 8789: }
 8790: 
 8791: sub correct_line_ends {
 8792:     my ($result)=@_;
 8793:     $$result =~s/\r\n/\n/mg;
 8794:     $$result =~s/\r/\n/mg;
 8795: }
 8796: # ================================================================ Main Program
 8797: 
 8798: sub goodbye {
 8799:    &logthis("Starting Shut down");
 8800: #not converted to using infrastruture and probably shouldn't be
 8801:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 8802: #converted
 8803: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 8804:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 8805: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 8806: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 8807: #1.1 only
 8808: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 8809: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 8810: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 8811: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 8812:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 8813:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 8814:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 8815:    &flushcourselogs();
 8816:    &logthis("Shutting down");
 8817: }
 8818: 
 8819: sub get_dns {
 8820:     my ($url,$func,$ignore_cache) = @_;
 8821:     if (!$ignore_cache) {
 8822: 	my ($content,$cached)=
 8823: 	    &Apache::lonnet::is_cached_new('dns',$url);
 8824: 	if ($cached) {
 8825: 	    &$func($content);
 8826: 	    return;
 8827: 	}
 8828:     }
 8829: 
 8830:     my %alldns;
 8831:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8832:     foreach my $dns (<$config>) {
 8833: 	next if ($dns !~ /^\^(\S*)/x);
 8834:         my $line = $1;
 8835:         my ($host,$protocol) = split(/:/,$line);
 8836:         if ($protocol ne 'https') {
 8837:             $protocol = 'http';
 8838:         }
 8839: 	$alldns{$host} = $protocol;
 8840:     }
 8841:     while (%alldns) {
 8842: 	my ($dns) = keys(%alldns);
 8843: 	my $ua=new LWP::UserAgent;
 8844: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
 8845: 	my $response=$ua->request($request);
 8846:         delete($alldns{$dns});
 8847: 	next if ($response->is_error());
 8848: 	my @content = split("\n",$response->content);
 8849: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 8850: 	&$func(\@content);
 8851: 	return;
 8852:     }
 8853:     close($config);
 8854:     my $which = (split('/',$url))[3];
 8855:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 8856:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 8857:     my @content = <$config>;
 8858:     &$func(\@content);
 8859:     return;
 8860: }
 8861: # ------------------------------------------------------------ Read domain file
 8862: {
 8863:     my $loaded;
 8864:     my %domain;
 8865: 
 8866:     sub parse_domain_tab {
 8867: 	my ($lines) = @_;
 8868: 	foreach my $line (@$lines) {
 8869: 	    next if ($line =~ /^(\#|\s*$ )/x);
 8870: 
 8871: 	    chomp($line);
 8872: 	    my ($name,@elements) = split(/:/,$line,9);
 8873: 	    my %this_domain;
 8874: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 8875: 			       'lang_def', 'city', 'longi', 'lati',
 8876: 			       'primary') {
 8877: 		$this_domain{$field} = shift(@elements);
 8878: 	    }
 8879: 	    $domain{$name} = \%this_domain;
 8880: 	}
 8881:     }
 8882: 
 8883:     sub reset_domain_info {
 8884: 	undef($loaded);
 8885: 	undef(%domain);
 8886:     }
 8887: 
 8888:     sub load_domain_tab {
 8889: 	my ($ignore_cache) = @_;
 8890: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 8891: 	my $fh;
 8892: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 8893: 	    my @lines = <$fh>;
 8894: 	    &parse_domain_tab(\@lines);
 8895: 	}
 8896: 	close($fh);
 8897: 	$loaded = 1;
 8898:     }
 8899: 
 8900:     sub domain {
 8901: 	&load_domain_tab() if (!$loaded);
 8902: 
 8903: 	my ($name,$what) = @_;
 8904: 	return if ( !exists($domain{$name}) );
 8905: 
 8906: 	if (!$what) {
 8907: 	    return $domain{$name}{'description'};
 8908: 	}
 8909: 	return $domain{$name}{$what};
 8910:     }
 8911: 
 8912:     sub domain_info {
 8913:         &load_domain_tab() if (!$loaded);
 8914:         return %domain;
 8915:     }
 8916: 
 8917: }
 8918: 
 8919: 
 8920: # ------------------------------------------------------------- Read hosts file
 8921: {
 8922:     my %hostname;
 8923:     my %hostdom;
 8924:     my %libserv;
 8925:     my $loaded;
 8926:     my %name_to_host;
 8927: 
 8928:     sub parse_hosts_tab {
 8929: 	my ($file) = @_;
 8930: 	foreach my $configline (@$file) {
 8931: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 8932: 	    next if ($configline =~ /^\^/);
 8933: 	    chomp($configline);
 8934: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
 8935: 	    $name=~s/\s//g;
 8936: 	    if ($id && $domain && $role && $name) {
 8937: 		$hostname{$id}=$name;
 8938: 		push(@{$name_to_host{$name}}, $id);
 8939: 		$hostdom{$id}=$domain;
 8940: 		if ($role eq 'library') { $libserv{$id}=$name; }
 8941:                 if (defined($protocol)) {
 8942:                     if ($protocol eq 'https') {
 8943:                         $protocol{$id} = $protocol;
 8944:                     } else {
 8945:                         $protocol{$id} = 'http'; 
 8946:                     }
 8947:                 } else {
 8948:                     $protocol{$id} = 'http';
 8949:                 }
 8950: 	    }
 8951: 	}
 8952:     }
 8953:     
 8954:     sub reset_hosts_info {
 8955: 	&purge_remembered();
 8956: 	&reset_domain_info();
 8957: 	&reset_hosts_ip_info();
 8958: 	undef(%name_to_host);
 8959: 	undef(%hostname);
 8960: 	undef(%hostdom);
 8961: 	undef(%libserv);
 8962: 	undef($loaded);
 8963:     }
 8964: 
 8965:     sub load_hosts_tab {
 8966: 	my ($ignore_cache) = @_;
 8967: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 8968: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8969: 	my @config = <$config>;
 8970: 	&parse_hosts_tab(\@config);
 8971: 	close($config);
 8972: 	$loaded=1;
 8973:     }
 8974: 
 8975:     sub hostname {
 8976: 	&load_hosts_tab() if (!$loaded);
 8977: 
 8978: 	my ($lonid) = @_;
 8979: 	return $hostname{$lonid};
 8980:     }
 8981: 
 8982:     sub all_hostnames {
 8983: 	&load_hosts_tab() if (!$loaded);
 8984: 
 8985: 	return %hostname;
 8986:     }
 8987: 
 8988:     sub all_names {
 8989: 	&load_hosts_tab() if (!$loaded);
 8990: 
 8991: 	return %name_to_host;
 8992:     }
 8993: 
 8994:     sub all_host_domain {
 8995:         &load_hosts_tab() if (!$loaded);
 8996:         return %hostdom;
 8997:     }
 8998: 
 8999:     sub is_library {
 9000: 	&load_hosts_tab() if (!$loaded);
 9001: 
 9002: 	return exists($libserv{$_[0]});
 9003:     }
 9004: 
 9005:     sub all_library {
 9006: 	&load_hosts_tab() if (!$loaded);
 9007: 
 9008: 	return %libserv;
 9009:     }
 9010: 
 9011:     sub get_servers {
 9012: 	&load_hosts_tab() if (!$loaded);
 9013: 
 9014: 	my ($domain,$type) = @_;
 9015: 	my %possible_hosts = ($type eq 'library') ? %libserv
 9016: 	                                          : %hostname;
 9017: 	my %result;
 9018: 	if (ref($domain) eq 'ARRAY') {
 9019: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9020: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 9021: 		    $result{$host} = $hostname;
 9022: 		}
 9023: 	    }
 9024: 	} else {
 9025: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9026: 		if ($hostdom{$host} eq $domain) {
 9027: 		    $result{$host} = $hostname;
 9028: 		}
 9029: 	    }
 9030: 	}
 9031: 	return %result;
 9032:     }
 9033: 
 9034:     sub host_domain {
 9035: 	&load_hosts_tab() if (!$loaded);
 9036: 
 9037: 	my ($lonid) = @_;
 9038: 	return $hostdom{$lonid};
 9039:     }
 9040: 
 9041:     sub all_domains {
 9042: 	&load_hosts_tab() if (!$loaded);
 9043: 
 9044: 	my %seen;
 9045: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 9046: 	return @uniq;
 9047:     }
 9048: }
 9049: 
 9050: { 
 9051:     my %iphost;
 9052:     my %name_to_ip;
 9053:     my %lonid_to_ip;
 9054: 
 9055:     sub get_hosts_from_ip {
 9056: 	my ($ip) = @_;
 9057: 	my %iphosts = &get_iphost();
 9058: 	if (ref($iphosts{$ip})) {
 9059: 	    return @{$iphosts{$ip}};
 9060: 	}
 9061: 	return;
 9062:     }
 9063:     
 9064:     sub reset_hosts_ip_info {
 9065: 	undef(%iphost);
 9066: 	undef(%name_to_ip);
 9067: 	undef(%lonid_to_ip);
 9068:     }
 9069: 
 9070:     sub get_host_ip {
 9071: 	my ($lonid) = @_;
 9072: 	if (exists($lonid_to_ip{$lonid})) {
 9073: 	    return $lonid_to_ip{$lonid};
 9074: 	}
 9075: 	my $name=&hostname($lonid);
 9076:    	my $ip = gethostbyname($name);
 9077: 	return if (!$ip || length($ip) ne 4);
 9078: 	$ip=inet_ntoa($ip);
 9079: 	$name_to_ip{$name}   = $ip;
 9080: 	$lonid_to_ip{$lonid} = $ip;
 9081: 	return $ip;
 9082:     }
 9083:     
 9084:     sub get_iphost {
 9085: 	my ($ignore_cache) = @_;
 9086: 
 9087: 	if (!$ignore_cache) {
 9088: 	    if (%iphost) {
 9089: 		return %iphost;
 9090: 	    }
 9091: 	    my ($ip_info,$cached)=
 9092: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 9093: 	    if ($cached) {
 9094: 		%iphost      = %{$ip_info->[0]};
 9095: 		%name_to_ip  = %{$ip_info->[1]};
 9096: 		%lonid_to_ip = %{$ip_info->[2]};
 9097: 		return %iphost;
 9098: 	    }
 9099: 	}
 9100: 
 9101: 	# get yesterday's info for fallback
 9102: 	my %old_name_to_ip;
 9103: 	my ($ip_info,$cached)=
 9104: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 9105: 	if ($cached) {
 9106: 	    %old_name_to_ip = %{$ip_info->[1]};
 9107: 	}
 9108: 
 9109: 	my %name_to_host = &all_names();
 9110: 	foreach my $name (keys(%name_to_host)) {
 9111: 	    my $ip;
 9112: 	    if (!exists($name_to_ip{$name})) {
 9113: 		$ip = gethostbyname($name);
 9114: 		if (!$ip || length($ip) ne 4) {
 9115: 		    if (defined($old_name_to_ip{$name})) {
 9116: 			$ip = $old_name_to_ip{$name};
 9117: 			&logthis("Can't find $name defaulting to old $ip");
 9118: 		    } else {
 9119: 			&logthis("Name $name no IP found");
 9120: 			next;
 9121: 		    }
 9122: 		} else {
 9123: 		    $ip=inet_ntoa($ip);
 9124: 		}
 9125: 		$name_to_ip{$name} = $ip;
 9126: 	    } else {
 9127: 		$ip = $name_to_ip{$name};
 9128: 	    }
 9129: 	    foreach my $id (@{ $name_to_host{$name} }) {
 9130: 		$lonid_to_ip{$id} = $ip;
 9131: 	    }
 9132: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 9133: 	}
 9134: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 9135: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 9136: 				      48*60*60);
 9137: 
 9138: 	return %iphost;
 9139:     }
 9140: 
 9141:     #
 9142:     #  Given a DNS returns the loncapa host name for that DNS 
 9143:     # 
 9144:     sub host_from_dns {
 9145:         my ($dns) = @_;
 9146:         my @hosts;
 9147:         my $ip;
 9148: 
 9149:         if (exists($name_to_ip{$dns})) {
 9150:             $ip = $name_to_ip{$dns};
 9151:         }
 9152:         if (!$ip) {
 9153:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
 9154:             if (length($ip) == 4) { 
 9155: 	        $ip   = &IO::Socket::inet_ntoa($ip);
 9156:             }
 9157:         }
 9158:         if ($ip) {
 9159: 	    @hosts = get_hosts_from_ip($ip);
 9160: 	    return $hosts[0];
 9161:         }
 9162:         return undef;
 9163:     }
 9164: 
 9165: }
 9166: 
 9167: BEGIN {
 9168: 
 9169: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 9170:     unless ($readit) {
 9171: {
 9172:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 9173:     %perlvar = (%perlvar,%{$configvars});
 9174: }
 9175: 
 9176: 
 9177: # ------------------------------------------------------ Read spare server file
 9178: {
 9179:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 9180: 
 9181:     while (my $configline=<$config>) {
 9182:        chomp($configline);
 9183:        if ($configline) {
 9184: 	   my ($host,$type) = split(':',$configline,2);
 9185: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 9186: 	   push(@{ $spareid{$type} }, $host);
 9187:        }
 9188:     }
 9189:     close($config);
 9190: }
 9191: # ------------------------------------------------------------ Read permissions
 9192: {
 9193:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 9194: 
 9195:     while (my $configline=<$config>) {
 9196: 	chomp($configline);
 9197: 	if ($configline) {
 9198: 	    my ($role,$perm)=split(/ /,$configline);
 9199: 	    if ($perm ne '') { $pr{$role}=$perm; }
 9200: 	}
 9201:     }
 9202:     close($config);
 9203: }
 9204: 
 9205: # -------------------------------------------- Read plain texts for permissions
 9206: {
 9207:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 9208: 
 9209:     while (my $configline=<$config>) {
 9210: 	chomp($configline);
 9211: 	if ($configline) {
 9212: 	    my ($short,@plain)=split(/:/,$configline);
 9213:             %{$prp{$short}} = ();
 9214: 	    if (@plain > 0) {
 9215:                 $prp{$short}{'std'} = $plain[0];
 9216:                 for (my $i=1; $i<@plain; $i++) {
 9217:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 9218:                 }
 9219:             }
 9220: 	}
 9221:     }
 9222:     close($config);
 9223: }
 9224: 
 9225: # ---------------------------------------------------------- Read package table
 9226: {
 9227:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 9228: 
 9229:     while (my $configline=<$config>) {
 9230: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 9231: 	chomp($configline);
 9232: 	my ($short,$plain)=split(/:/,$configline);
 9233: 	my ($pack,$name)=split(/\&/,$short);
 9234: 	if ($plain ne '') {
 9235: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 9236: 	    $packagetab{$short}=$plain; 
 9237: 	}
 9238:     }
 9239:     close($config);
 9240: }
 9241: 
 9242: # ------------- set up temporary directory
 9243: {
 9244:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 9245: 
 9246: }
 9247: 
 9248: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 9249: 				'compress_threshold'=> 20_000,
 9250:  			        });
 9251: 
 9252: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 9253: $dumpcount=0;
 9254: $locknum=0;
 9255: 
 9256: &logtouch();
 9257: &logthis('<font color="yellow">INFO: Read configuration</font>');
 9258: $readit=1;
 9259:     {
 9260: 	use integer;
 9261: 	my $test=(2**32)+1;
 9262: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 9263: 	&logthis(" Detected 64bit platform ($_64bit)");
 9264:     }
 9265: }
 9266: }
 9267: 
 9268: 1;
 9269: __END__
 9270: 
 9271: =pod
 9272: 
 9273: =head1 NAME
 9274: 
 9275: Apache::lonnet - Subroutines to ask questions about things in the network.
 9276: 
 9277: =head1 SYNOPSIS
 9278: 
 9279: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 9280: 
 9281:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 9282: 
 9283: Common parameters:
 9284: 
 9285: =over 4
 9286: 
 9287: =item *
 9288: 
 9289: $uname : an internal username (if $cname expecting a course Id specifically)
 9290: 
 9291: =item *
 9292: 
 9293: $udom : a domain (if $cdom expecting a course's domain specifically)
 9294: 
 9295: =item *
 9296: 
 9297: $symb : a resource instance identifier
 9298: 
 9299: =item *
 9300: 
 9301: $namespace : the name of a .db file that contains the data needed or
 9302: being set.
 9303: 
 9304: =back
 9305: 
 9306: =head1 OVERVIEW
 9307: 
 9308: lonnet provides subroutines which interact with the
 9309: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 9310: about classes, users, and resources.
 9311: 
 9312: For many of these objects you can also use this to store data about
 9313: them or modify them in various ways.
 9314: 
 9315: =head2 Symbs
 9316: 
 9317: To identify a specific instance of a resource, LON-CAPA uses symbols
 9318: or "symbs"X<symb>. These identifiers are built from the URL of the
 9319: map, the resource number of the resource in the map, and the URL of
 9320: the resource itself. The latter is somewhat redundant, but might help
 9321: if maps change.
 9322: 
 9323: An example is
 9324: 
 9325:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 9326: 
 9327: The respective map entry is
 9328: 
 9329:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 9330:   title="Problem 2">
 9331:  </resource>
 9332: 
 9333: Symbs are used by the random number generator, as well as to store and
 9334: restore data specific to a certain instance of for example a problem.
 9335: 
 9336: =head2 Storing And Retrieving Data
 9337: 
 9338: X<store()>X<cstore()>X<restore()>Three of the most important functions
 9339: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 9340: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 9341: is is the non-critical message twin of cstore. These functions are for
 9342: handlers to store a perl hash to a user's permanent data space in an
 9343: easy manner, and to retrieve it again on another call. It is expected
 9344: that a handler would use this once at the beginning to retrieve data,
 9345: and then again once at the end to send only the new data back.
 9346: 
 9347: The data is stored in the user's data directory on the user's
 9348: homeserver under the ID of the course.
 9349: 
 9350: The hash that is returned by restore will have all of the previous
 9351: value for all of the elements of the hash.
 9352: 
 9353: Example:
 9354: 
 9355:  #creating a hash
 9356:  my %hash;
 9357:  $hash{'foo'}='bar';
 9358: 
 9359:  #storing it
 9360:  &Apache::lonnet::cstore(\%hash);
 9361: 
 9362:  #changing a value
 9363:  $hash{'foo'}='notbar';
 9364: 
 9365:  #adding a new value
 9366:  $hash{'bar'}='foo';
 9367:  &Apache::lonnet::cstore(\%hash);
 9368: 
 9369:  #retrieving the hash
 9370:  my %history=&Apache::lonnet::restore();
 9371: 
 9372:  #print the hash
 9373:  foreach my $key (sort(keys(%history))) {
 9374:    print("\%history{$key} = $history{$key}");
 9375:  }
 9376: 
 9377: Will print out:
 9378: 
 9379:  %history{1:foo} = bar
 9380:  %history{1:keys} = foo:timestamp
 9381:  %history{1:timestamp} = 990455579
 9382:  %history{2:bar} = foo
 9383:  %history{2:foo} = notbar
 9384:  %history{2:keys} = foo:bar:timestamp
 9385:  %history{2:timestamp} = 990455580
 9386:  %history{bar} = foo
 9387:  %history{foo} = notbar
 9388:  %history{timestamp} = 990455580
 9389:  %history{version} = 2
 9390: 
 9391: Note that the special hash entries C<keys>, C<version> and
 9392: C<timestamp> were added to the hash. C<version> will be equal to the
 9393: total number of versions of the data that have been stored. The
 9394: C<timestamp> attribute will be the UNIX time the hash was
 9395: stored. C<keys> is available in every historical section to list which
 9396: keys were added or changed at a specific historical revision of a
 9397: hash.
 9398: 
 9399: B<Warning>: do not store the hash that restore returns directly. This
 9400: will cause a mess since it will restore the historical keys as if the
 9401: were new keys. I.E. 1:foo will become 1:1:foo etc.
 9402: 
 9403: Calling convention:
 9404: 
 9405:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 9406:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 9407: 
 9408: For more detailed information, see lonnet specific documentation.
 9409: 
 9410: =head1 RETURN MESSAGES
 9411: 
 9412: =over 4
 9413: 
 9414: =item * B<con_lost>: unable to contact remote host
 9415: 
 9416: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 9417: when the connection is brought back up
 9418: 
 9419: =item * B<con_failed>: unable to contact remote host and unable to save message
 9420: for later delivery
 9421: 
 9422: =item * B<error:>: an error a occurred, a description of the error follows the :
 9423: 
 9424: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 9425: that was requested
 9426: 
 9427: =back
 9428: 
 9429: =head1 PUBLIC SUBROUTINES
 9430: 
 9431: =head2 Session Environment Functions
 9432: 
 9433: =over 4
 9434: 
 9435: =item * 
 9436: X<appenv()>
 9437: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
 9438: the user envirnoment file, and will be restored for each access this
 9439: user makes during this session, also modifies the %env for the current
 9440: process. Optional rolesarrayref - if defined contains a reference to an array
 9441: of roles which are exempt from the restriction on modifying user.role entries 
 9442: in the user's environment.db and in %env.    
 9443: 
 9444: =item *
 9445: X<delenv()>
 9446: B<delenv($delthis,$regexp)>: removes all items from the session
 9447: environment file that begin with $delthis. If the 
 9448: optional second arg - $regexp - is true, $delthis is treated as a 
 9449: regular expression, otherwise \Q$delthis\E is used. 
 9450: The values are also deleted from the current processes %env.
 9451: 
 9452: =item * get_env_multiple($name) 
 9453: 
 9454: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9455: values may be defined and end up as an array ref.
 9456: 
 9457: returns an array of values
 9458: 
 9459: =back
 9460: 
 9461: =head2 User Information
 9462: 
 9463: =over 4
 9464: 
 9465: =item *
 9466: X<queryauthenticate()>
 9467: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 9468: authentication scheme
 9469: 
 9470: =item *
 9471: X<authenticate()>
 9472: B<authenticate($uname,$upass,$udom)>: try to
 9473: authenticate user from domain's lib servers (first use the current
 9474: one). C<$upass> should be the users password.
 9475: 
 9476: =item *
 9477: X<homeserver()>
 9478: B<homeserver($uname,$udom)>: find the server which has
 9479: the user's directory and files (there must be only one), this caches
 9480: the answer, and also caches if there is a borken connection.
 9481: 
 9482: =item *
 9483: X<idget()>
 9484: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 9485: (IDs are a unique resource in a domain, there must be only 1 ID per
 9486: username, and only 1 username per ID in a specific domain) (returns
 9487: hash: id=>name,id=>name)
 9488: 
 9489: =item *
 9490: X<idrget()>
 9491: B<idrget($udom,@unames)>: find the IDs behind a list of
 9492: usernames (returns hash: name=>id,name=>id)
 9493: 
 9494: =item *
 9495: X<idput()>
 9496: B<idput($udom,%ids)>: store away a list of names and associated IDs
 9497: 
 9498: =item *
 9499: X<rolesinit()>
 9500: B<rolesinit($udom,$username,$authhost)>: get user privileges
 9501: 
 9502: =item *
 9503: X<getsection()>
 9504: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 9505: course $cname, return section name/number or '' for "not in course"
 9506: and '-1' for "no section"
 9507: 
 9508: =item *
 9509: X<userenvironment()>
 9510: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 9511: passed in @what from the requested user's environment, returns a hash
 9512: 
 9513: =item * 
 9514: X<userlog_query()>
 9515: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 9516: activity.log file. %filters defines filters applied when parsing the
 9517: log file. These can be start or end timestamps, or the type of action
 9518: - log to look for Login or Logout events, check for Checkin or
 9519: Checkout, role for role selection. The response is in the form
 9520: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 9521: escaped strings of the action recorded in the activity.log file.
 9522: 
 9523: =back
 9524: 
 9525: =head2 User Roles
 9526: 
 9527: =over 4
 9528: 
 9529: =item *
 9530: 
 9531: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 9532:  F: full access
 9533:  U,I,K: authentication modes (cxx only)
 9534:  '': forbidden
 9535:  1: user needs to choose course
 9536:  2: browse allowed
 9537:  A: passphrase authentication needed
 9538: 
 9539: =item *
 9540: 
 9541: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 9542: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 9543: and course level
 9544: 
 9545: =item *
 9546: 
 9547: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
 9548: (rolesplain.tab); plain text explanation of a user role term.
 9549: $type is Course (default) or Group.
 9550: If $forcedefault evaluates to true, text returned will be default 
 9551: text for $type. Otherwise, if this is a course, the text returned 
 9552: will be a custom name for the role (if defined in the course's 
 9553: environment).  If no custom name is defined the default is returned.
 9554:    
 9555: =item *
 9556: 
 9557: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
 9558: All arguments are optional. Returns a hash of a roles, either for
 9559: co-author/assistant author roles for a user's Construction Space
 9560: (default), or if $context is 'userroles', roles for the user himself,
 9561: In the hash, keys are set to colon-separated $uname,$udom,$role, and
 9562: (optionally) if $withsec is true, a fourth colon-separated item - $section.
 9563: For each key, value is set to colon-separated start and end times for
 9564: the role.  If no username and domain are specified, will default to
 9565: current user/domain. Types, roles, and roledoms are references to arrays
 9566: of role statuses (active, future or previous), roles 
 9567: (e.g., cc,in, st etc.) and domains of the roles which can be used
 9568: to restrict the list of roles reported. If no array ref is 
 9569: provided for types, will default to return only active roles.
 9570: 
 9571: =back
 9572: 
 9573: =head2 User Modification
 9574: 
 9575: =over 4
 9576: 
 9577: =item *
 9578: 
 9579: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
 9580: user for the level given by URL.  Optional start and end dates (leave empty
 9581: string or zero for "no date")
 9582: 
 9583: =item *
 9584: 
 9585: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 9586: change a users, password, possible return values are: ok,
 9587: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 9588: refused
 9589: 
 9590: =item *
 9591: 
 9592: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 9593: 
 9594: =item *
 9595: 
 9596: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
 9597:            $forceid,$desiredhome,$email,$inststatus) : 
 9598: modify user
 9599: 
 9600: =item *
 9601: 
 9602: modifystudent
 9603: 
 9604: modify a student's enrollment and identification information.
 9605: The course id is resolved based on the current users environment.  
 9606: This means the envoking user must be a course coordinator or otherwise
 9607: associated with a course.
 9608: 
 9609: This call is essentially a wrapper for lonnet::modifyuser and
 9610: lonnet::modify_student_enrollment
 9611: 
 9612: Inputs: 
 9613: 
 9614: =over 4
 9615: 
 9616: =item B<$udom> Student's loncapa domain
 9617: 
 9618: =item B<$uname> Student's loncapa login name
 9619: 
 9620: =item B<$uid> Student/Employee ID
 9621: 
 9622: =item B<$umode> Student's authentication mode
 9623: 
 9624: =item B<$upass> Student's password
 9625: 
 9626: =item B<$first> Student's first name
 9627: 
 9628: =item B<$middle> Student's middle name
 9629: 
 9630: =item B<$last> Student's last name
 9631: 
 9632: =item B<$gene> Student's generation
 9633: 
 9634: =item B<$usec> Student's section in course
 9635: 
 9636: =item B<$end> Unix time of the roles expiration
 9637: 
 9638: =item B<$start> Unix time of the roles start date
 9639: 
 9640: =item B<$forceid> If defined, allow $uid to be changed
 9641: 
 9642: =item B<$desiredhome> server to use as home server for student
 9643: 
 9644: =item B<$email> Student's permanent e-mail address
 9645: 
 9646: =item B<$type> Type of enrollment (auto or manual)
 9647: 
 9648: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
 9649: 
 9650: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
 9651: 
 9652: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
 9653: 
 9654: =item B<$context> role change context (shown in User Management Logs display in a course)
 9655: 
 9656: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
 9657: 
 9658: =back
 9659: 
 9660: =item *
 9661: 
 9662: modify_student_enrollment
 9663: 
 9664: Change a students enrollment status in a class.  The environment variable
 9665: 'role.request.course' must be defined for this function to proceed.
 9666: 
 9667: Inputs:
 9668: 
 9669: =over 4
 9670: 
 9671: =item $udom, students domain
 9672: 
 9673: =item $uname, students name
 9674: 
 9675: =item $uid, students user id
 9676: 
 9677: =item $first, students first name
 9678: 
 9679: =item $middle
 9680: 
 9681: =item $last
 9682: 
 9683: =item $gene
 9684: 
 9685: =item $usec
 9686: 
 9687: =item $end
 9688: 
 9689: =item $start
 9690: 
 9691: =item $type
 9692: 
 9693: =item $locktype
 9694: 
 9695: =item $cid
 9696: 
 9697: =item $selfenroll
 9698: 
 9699: =item $context
 9700: 
 9701: =back
 9702: 
 9703: 
 9704: =item *
 9705: 
 9706: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 9707: custom role; give a custom role to a user for the level given by URL.  Specify
 9708: name and domain of role author, and role name
 9709: 
 9710: =item *
 9711: 
 9712: revokerole($udom,$uname,$url,$role) : revoke a role for url
 9713: 
 9714: =item *
 9715: 
 9716: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 9717: 
 9718: =back
 9719: 
 9720: =head2 Course Infomation
 9721: 
 9722: =over 4
 9723: 
 9724: =item *
 9725: 
 9726: coursedescription($courseid) : returns a hash of information about the
 9727: specified course id, including all environment settings for the
 9728: course, the description of the course will be in the hash under the
 9729: key 'description'
 9730: 
 9731: =item *
 9732: 
 9733: resdata($name,$domain,$type,@which) : request for current parameter
 9734: setting for a specific $type, where $type is either 'course' or 'user',
 9735: @what should be a list of parameters to ask about. This routine caches
 9736: answers for 5 minutes.
 9737: 
 9738: =item *
 9739: 
 9740: get_courseresdata($courseid, $domain) : dump the entire course resource
 9741: data base, returning a hash that is keyed by the resource name and has
 9742: values that are the resource value.  I believe that the timestamps and
 9743: versions are also returned.
 9744: 
 9745: 
 9746: =back
 9747: 
 9748: =head2 Course Modification
 9749: 
 9750: =over 4
 9751: 
 9752: =item *
 9753: 
 9754: writecoursepref($courseid,%prefs) : write preferences (environment
 9755: database) for a course
 9756: 
 9757: =item *
 9758: 
 9759: createcourse($udom,$description,$url) : make/modify course
 9760: 
 9761: =back
 9762: 
 9763: =head2 Resource Subroutines
 9764: 
 9765: =over 4
 9766: 
 9767: =item *
 9768: 
 9769: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 9770: 
 9771: =item *
 9772: 
 9773: repcopy($filename) : subscribes to the requested file, and attempts to
 9774: replicate from the owning library server, Might return
 9775: 'unavailable', 'not_found', 'forbidden', 'ok', or
 9776: 'bad_request', also attempts to grab the metadata for the
 9777: resource. Expects the local filesystem pathname
 9778: (/home/httpd/html/res/....)
 9779: 
 9780: =back
 9781: 
 9782: =head2 Resource Information
 9783: 
 9784: =over 4
 9785: 
 9786: =item *
 9787: 
 9788: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 9789: a vairety of different possible values, $varname should be a request
 9790: string, and the other parameters can be used to specify who and what
 9791: one is asking about.
 9792: 
 9793: Possible values for $varname are environment.lastname (or other item
 9794: from the envirnment hash), user.name (or someother aspect about the
 9795: user), resource.0.maxtries (or some other part and parameter of a
 9796: resource)
 9797: 
 9798: =item *
 9799: 
 9800: directcondval($number) : get current value of a condition; reads from a state
 9801: string
 9802: 
 9803: =item *
 9804: 
 9805: condval($condidx) : value of condition index based on state
 9806: 
 9807: =item *
 9808: 
 9809: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 9810: resource's metadata, $what should be either a specific key, or either
 9811: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 9812: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 9813: 
 9814: this function automatically caches all requests
 9815: 
 9816: =item *
 9817: 
 9818: metadata_query($query,$custom,$customshow) : make a metadata query against the
 9819: network of library servers; returns file handle of where SQL and regex results
 9820: will be stored for query
 9821: 
 9822: =item *
 9823: 
 9824: symbread($filename) : return symbolic list entry (filename argument optional);
 9825: returns the data handle
 9826: 
 9827: =item *
 9828: 
 9829: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 9830: a possible symb for the URL in $thisfn, and if is an encryypted
 9831: resource that the user accessed using /enc/ returns a 1 on success, 0
 9832: on failure, user must be in a course, as it assumes the existance of
 9833: the course initial hash, and uses $env('request.course.id'}
 9834: 
 9835: 
 9836: =item *
 9837: 
 9838: symbclean($symb) : removes versions numbers from a symb, returns the
 9839: cleaned symb
 9840: 
 9841: =item *
 9842: 
 9843: is_on_map($uri) : checks if the $uri is somewhere on the current
 9844: course map, user must be in a course for it to work.
 9845: 
 9846: =item *
 9847: 
 9848: numval($salt) : return random seed value (addend for rndseed)
 9849: 
 9850: =item *
 9851: 
 9852: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 9853: a random seed, all arguments are optional, if they aren't sent it uses the
 9854: environment to derive them. Note: if symb isn't sent and it can't get one
 9855: from &symbread it will use the current time as its return value
 9856: 
 9857: =item *
 9858: 
 9859: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 9860: unfakeable, receipt
 9861: 
 9862: =item *
 9863: 
 9864: receipt() : API to ireceipt working off of env values; given out to users
 9865: 
 9866: =item *
 9867: 
 9868: countacc($url) : count the number of accesses to a given URL
 9869: 
 9870: =item *
 9871: 
 9872: 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
 9873: 
 9874: =item *
 9875: 
 9876: 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)
 9877: 
 9878: =item *
 9879: 
 9880: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 9881: 
 9882: =item *
 9883: 
 9884: devalidate($symb) : devalidate temporary spreadsheet calculations,
 9885: forcing spreadsheet to reevaluate the resource scores next time.
 9886: 
 9887: =back
 9888: 
 9889: =head2 Storing/Retreiving Data
 9890: 
 9891: =over 4
 9892: 
 9893: =item *
 9894: 
 9895: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 9896: for this url; hashref needs to be given and should be a \%hashname; the
 9897: remaining args aren't required and if they aren't passed or are '' they will
 9898: be derived from the env
 9899: 
 9900: =item *
 9901: 
 9902: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 9903: uses critical subroutine
 9904: 
 9905: =item *
 9906: 
 9907: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 9908: all args are optional
 9909: 
 9910: =item *
 9911: 
 9912: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 9913: dumps the complete (or key matching regexp) namespace into a hash
 9914: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 9915: normally &store()ed into
 9916: 
 9917: $range should be either an integer '100' (give me the first 100
 9918:                                            matching records)
 9919:               or be  two integers sperated by a - with no spaces
 9920:                  '30-50' (give me the 30th through the 50th matching
 9921:                           records)
 9922: 
 9923: 
 9924: =item *
 9925: 
 9926: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 9927: replaces a &store() version of data with a replacement set of data
 9928: for a particular resource in a namespace passed in the $storehash hash 
 9929: reference
 9930: 
 9931: =item *
 9932: 
 9933: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 9934: works very similar to store/cstore, but all data is stored in a
 9935: temporary location and can be reset using tmpreset, $storehash should
 9936: be a hash reference, returns nothing on success
 9937: 
 9938: =item *
 9939: 
 9940: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 9941: similar to restore, but all data is stored in a temporary location and
 9942: can be reset using tmpreset. Returns a hash of values on success,
 9943: error string otherwise.
 9944: 
 9945: =item *
 9946: 
 9947: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 9948: deltes all keys for $symb form the temporary storage hash.
 9949: 
 9950: =item *
 9951: 
 9952: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9953: reference filled in from namesp ($udom and $uname are optional)
 9954: 
 9955: =item *
 9956: 
 9957: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 9958: namesp ($udom and $uname are optional)
 9959: 
 9960: =item *
 9961: 
 9962: dump($namespace,$udom,$uname,$regexp,$range) : 
 9963: dumps the complete (or key matching regexp) namespace into a hash
 9964: ($udom, $uname, $regexp, $range are optional)
 9965: 
 9966: $range should be either an integer '100' (give me the first 100
 9967:                                            matching records)
 9968:               or be  two integers sperated by a - with no spaces
 9969:                  '30-50' (give me the 30th through the 50th matching
 9970:                           records)
 9971: =item *
 9972: 
 9973: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 9974: $store can be a scalar, an array reference, or if the amount to be 
 9975: incremented is > 1, a hash reference.
 9976: 
 9977: ($udom and $uname are optional)
 9978: 
 9979: =item *
 9980: 
 9981: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 9982: ($udom and $uname are optional)
 9983: 
 9984: =item *
 9985: 
 9986: cput($namespace,$storehash,$udom,$uname) : critical put
 9987: ($udom and $uname are optional)
 9988: 
 9989: =item *
 9990: 
 9991: newput($namespace,$storehash,$udom,$uname) :
 9992: 
 9993: Attempts to store the items in the $storehash, but only if they don't
 9994: currently exist, if this succeeds you can be certain that you have 
 9995: successfully created a new key value pair in the $namespace db.
 9996: 
 9997: 
 9998: Args:
 9999:  $namespace: name of database to store values to
10000:  $storehash: hashref to store to the db
10001:  $udom: (optional) domain of user containing the db
10002:  $uname: (optional) name of user caontaining the db
10003: 
10004: Returns:
10005:  'ok' -> succeeded in storing all keys of $storehash
10006:  'key_exists: <key>' -> failed to anything out of $storehash, as at
10007:                         least <key> already existed in the db (other
10008:                         requested keys may also already exist)
10009:  'error: <msg>' -> unable to tie the DB or other error occurred
10010:  'con_lost' -> unable to contact request server
10011:  'refused' -> action was not allowed by remote machine
10012: 
10013: 
10014: =item *
10015: 
10016: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10017: reference filled in from namesp (encrypts the return communication)
10018: ($udom and $uname are optional)
10019: 
10020: =item *
10021: 
10022: log($udom,$name,$home,$message) : write to permanent log for user; use
10023: critical subroutine
10024: 
10025: =item *
10026: 
10027: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
10028: array reference filled in from namespace found in domain level on either
10029: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
10030: 
10031: =item *
10032: 
10033: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
10034: domain level either on specified domain server ($uhome) or primary domain 
10035: server ($udom and $uhome are optional)
10036: 
10037: =item * 
10038: 
10039: get_domain_defaults($target_domain) : returns hash with defaults for
10040: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
10041: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
10042: or localauth), initial password or a kerberos realm, language (e.g., en-us).
10043: Values are retrieved from cache (if current), or from domain's configuration.db
10044: (if available), or lastly from values in lonTabs/dns_domain,tab, 
10045: or lonTabs/domain.tab. 
10046: 
10047: %domdefaults = &get_auth_defaults($target_domain);
10048: 
10049: =back
10050: 
10051: =head2 Network Status Functions
10052: 
10053: =over 4
10054: 
10055: =item *
10056: 
10057: dirlist($uri) : return directory list based on URI
10058: 
10059: =item *
10060: 
10061: spareserver() : find server with least workload from spare.tab
10062: 
10063: 
10064: =item *
10065: 
10066: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
10067: if there is no corresponding loncapa host.
10068: 
10069: =back
10070: 
10071: 
10072: =head2 Apache Request
10073: 
10074: =over 4
10075: 
10076: =item *
10077: 
10078: ssi($url,%hash) : server side include, does a complete request cycle on url to
10079: localhost, posts hash
10080: 
10081: =back
10082: 
10083: =head2 Data to String to Data
10084: 
10085: =over 4
10086: 
10087: =item *
10088: 
10089: hash2str(%hash) : convert a hash into a string complete with escaping and '='
10090: and '&' separators, supports elements that are arrayrefs and hashrefs
10091: 
10092: =item *
10093: 
10094: hashref2str($hashref) : convert a hashref into a string complete with
10095: escaping and '=' and '&' separators, supports elements that are
10096: arrayrefs and hashrefs
10097: 
10098: =item *
10099: 
10100: arrayref2str($arrayref) : convert an arrayref into a string complete
10101: with escaping and '&' separators, supports elements that are arrayrefs
10102: and hashrefs
10103: 
10104: =item *
10105: 
10106: str2hash($string) : convert string to hash using unescaping and
10107: splitting on '=' and '&', supports elements that are arrayrefs and
10108: hashrefs
10109: 
10110: =item *
10111: 
10112: str2array($string) : convert string to hash using unescaping and
10113: splitting on '&', supports elements that are arrayrefs and hashrefs
10114: 
10115: =back
10116: 
10117: =head2 Logging Routines
10118: 
10119: =over 4
10120: 
10121: These routines allow one to make log messages in the lonnet.log and
10122: lonnet.perm logfiles.
10123: 
10124: =item *
10125: 
10126: logtouch() : make sure the logfile, lonnet.log, exists
10127: 
10128: =item *
10129: 
10130: logthis() : append message to the normal lonnet.log file, it gets
10131: preiodically rolled over and deleted.
10132: 
10133: =item *
10134: 
10135: logperm() : append a permanent message to lonnet.perm.log, this log
10136: file never gets deleted by any automated portion of the system, only
10137: messages of critical importance should go in here.
10138: 
10139: =back
10140: 
10141: =head2 General File Helper Routines
10142: 
10143: =over 4
10144: 
10145: =item *
10146: 
10147: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10148: (a) files in /uploaded
10149:   (i) If a local copy of the file exists - 
10150:       compares modification date of local copy with last-modified date for 
10151:       definitive version stored on home server for course. If local copy is 
10152:       stale, requests a new version from the home server and stores it. 
10153:       If the original has been removed from the home server, then local copy 
10154:       is unlinked.
10155:   (ii) If local copy does not exist -
10156:       requests the file from the home server and stores it. 
10157:   
10158:   If $caller is 'uploadrep':  
10159:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10160:     for request for files originally uploaded via DOCS. 
10161:      - returns 'ok' if fresh local copy now available, -1 otherwise.
10162:   
10163:   Otherwise:
10164:      This indicates a call from the content generation phase of the request.
10165:      -  returns the entire contents of the file or -1.
10166:      
10167: (b) files in /res
10168:    - returns the entire contents of a file or -1; 
10169:    it properly subscribes to and replicates the file if neccessary.
10170: 
10171: 
10172: =item *
10173: 
10174: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10175:                   reference
10176: 
10177: returns either a stat() list of data about the file or an empty list
10178: if the file doesn't exist or couldn't find out about it (connection
10179: problems or user unknown)
10180: 
10181: =item *
10182: 
10183: filelocation($dir,$file) : returns file system location of a file
10184: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10185: directory that relative $file lookups are to looked in ($dir of /a/dir
10186: and a file of ../bob will become /a/bob)
10187: 
10188: =item *
10189: 
10190: hreflocation($dir,$file) : returns file system location or a URL; same as
10191: filelocation except for hrefs
10192: 
10193: =item *
10194: 
10195: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10196: 
10197: =back
10198: 
10199: =head2 Usererfile file routines (/uploaded*)
10200: 
10201: =over 4
10202: 
10203: =item *
10204: 
10205: userfileupload(): main rotine for putting a file in a user or course's
10206:                   filespace, arguments are,
10207: 
10208:  formname - required - this is the name of the element in $env where the
10209:            filename, and the contents of the file to create/modifed exist
10210:            the filename is in $env{'form.'.$formname.'.filename'} and the
10211:            contents of the file is located in $env{'form.'.$formname}
10212:  coursedoc - if true, store the file in the course of the active role
10213:              of the current user
10214:  subdir - required - subdirectory to put the file in under ../userfiles/
10215:          if undefined, it will be placed in "unknown"
10216: 
10217:  (This routine calls clean_filename() to remove any dangerous
10218:  characters from the filename, and then calls finuserfileupload() to
10219:  complete the transaction)
10220: 
10221:  returns either the url of the uploaded file (/uploaded/....) if successful
10222:  and /adm/notfound.html if unsuccessful
10223: 
10224: =item *
10225: 
10226: clean_filename(): routine for cleaing a filename up for storage in
10227:                  userfile space, argument is:
10228: 
10229:  filename - proposed filename
10230: 
10231: returns: the new clean filename
10232: 
10233: =item *
10234: 
10235: finishuserfileupload(): routine that creaes and sends the file to
10236: userspace, probably shouldn't be called directly
10237: 
10238:   docuname: username or courseid of destination for the file
10239:   docudom: domain of user/course of destination for the file
10240:   formname: same as for userfileupload()
10241:   fname: filename (inculding subdirectories) for the file
10242: 
10243:  returns either the url of the uploaded file (/uploaded/....) if successful
10244:  and /adm/notfound.html if unsuccessful
10245: 
10246: =item *
10247: 
10248: renameuserfile(): renames an existing userfile to a new name
10249: 
10250:   Args:
10251:    docuname: username or courseid of destination for the file
10252:    docudom: domain of user/course of destination for the file
10253:    old: current file name (including any subdirs under userfiles)
10254:    new: desired file name (including any subdirs under userfiles)
10255: 
10256: =item *
10257: 
10258: mkdiruserfile(): creates a directory is a userfiles dir
10259: 
10260:   Args:
10261:    docuname: username or courseid of destination for the file
10262:    docudom: domain of user/course of destination for the file
10263:    dir: dir to create (including any subdirs under userfiles)
10264: 
10265: =item *
10266: 
10267: removeuserfile(): removes a file that exists in userfiles
10268: 
10269:   Args:
10270:    docuname: username or courseid of destination for the file
10271:    docudom: domain of user/course of destination for the file
10272:    fname: filname to delete (including any subdirs under userfiles)
10273: 
10274: =item *
10275: 
10276: removeuploadedurl(): convience function for removeuserfile()
10277: 
10278:   Args:
10279:    url:  a full /uploaded/... url to delete
10280: 
10281: =item * 
10282: 
10283: get_portfile_permissions():
10284:   Args:
10285:     domain: domain of user or course contain the portfolio files
10286:     user: name of user or num of course contain the portfolio files
10287:   Returns:
10288:     hashref of a dump of the proper file_permissions.db
10289:    
10290: 
10291: =item * 
10292: 
10293: get_access_controls():
10294: 
10295: Args:
10296:   current_permissions: the hash ref returned from get_portfile_permissions()
10297:   group: (optional) the group you want the files associated with
10298:   file: (optional) the file you want access info on
10299: 
10300: Returns:
10301:     a hash (keys are file names) of hashes containing
10302:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10303:         values are XML containing access control settings (see below) 
10304: 
10305: Internal notes:
10306: 
10307:  access controls are stored in file_permissions.db as key=value pairs.
10308:     key -> path to file/file_name\0uniqueID:scope_end_start
10309:         where scope -> public,guest,course,group,domains or users.
10310:               end -> UNIX time for end of access (0 -> no end date)
10311:               start -> UNIX time for start of access
10312: 
10313:     value -> XML description of access control
10314:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10315:             <start></start>
10316:             <end></end>
10317: 
10318:             <password></password>  for scope type = guest
10319: 
10320:             <domain></domain>     for scope type = course or group
10321:             <number></number>
10322:             <roles id="">
10323:              <role></role>
10324:              <access></access>
10325:              <section></section>
10326:              <group></group>
10327:             </roles>
10328: 
10329:             <dom></dom>         for scope type = domains
10330: 
10331:             <users>             for scope type = users
10332:              <user>
10333:               <uname></uname>
10334:               <udom></udom>
10335:              </user>
10336:             </users>
10337:            </scope> 
10338:               
10339:  Access data is also aggregated for each file in an additional key=value pair:
10340:  key -> path to file/file_name\0accesscontrol 
10341:  value -> reference to hash
10342:           hash contains key = value pairs
10343:           where key = uniqueID:scope_end_start
10344:                 value = UNIX time record was last updated
10345: 
10346:           Used to improve speed of look-ups of access controls for each file.  
10347:  
10348:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10349: 
10350: modify_access_controls():
10351: 
10352: Modifies access controls for a portfolio file
10353: Args
10354: 1. file name
10355: 2. reference to hash of required changes,
10356: 3. domain
10357: 4. username
10358:   where domain,username are the domain of the portfolio owner 
10359:   (either a user or a course) 
10360: 
10361: Returns:
10362: 1. result of additions or updates ('ok' or 'error', with error message). 
10363: 2. result of deletions ('ok' or 'error', with error message).
10364: 3. reference to hash of any new or updated access controls.
10365: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10366:    key = integer (inbound ID)
10367:    value = uniqueID  
10368: 
10369: =back
10370: 
10371: =head2 HTTP Helper Routines
10372: 
10373: =over 4
10374: 
10375: =item *
10376: 
10377: escape() : unpack non-word characters into CGI-compatible hex codes
10378: 
10379: =item *
10380: 
10381: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10382: 
10383: =back
10384: 
10385: =head1 PRIVATE SUBROUTINES
10386: 
10387: =head2 Underlying communication routines (Shouldn't call)
10388: 
10389: =over 4
10390: 
10391: =item *
10392: 
10393: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10394: 
10395: =item *
10396: 
10397: reply() : uses subreply to send a message to remote machine, logs all failures
10398: 
10399: =item *
10400: 
10401: critical() : passes a critical message to another server; if cannot
10402: get through then place message in connection buffer directory and
10403: returns con_delayed, if incapable of saving message, returns
10404: con_failed
10405: 
10406: =item *
10407: 
10408: reconlonc() : tries to reconnect lonc client processes.
10409: 
10410: =back
10411: 
10412: =head2 Resource Access Logging
10413: 
10414: =over 4
10415: 
10416: =item *
10417: 
10418: flushcourselogs() : flush (save) buffer logs and access logs
10419: 
10420: =item *
10421: 
10422: courselog($what) : save message for course in hash
10423: 
10424: =item *
10425: 
10426: courseacclog($what) : save message for course using &courselog().  Perform
10427: special processing for specific resource types (problems, exams, quizzes, etc).
10428: 
10429: =item *
10430: 
10431: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10432: as a PerlChildExitHandler
10433: 
10434: =back
10435: 
10436: =head2 Other
10437: 
10438: =over 4
10439: 
10440: =item *
10441: 
10442: symblist($mapname,%newhash) : update symbolic storage links
10443: 
10444: =back
10445: 
10446: =cut
10447: 

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