File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.998: download - view: text, annotated - select for diffs
Fri May 8 12:45:28 2009 UTC (15 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Check for active DC roles only (start before $now, end after $now).

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.998 2009/05/08 12:45:28 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:             if (($trole ne 'st') || ($sec ne '')) {
 2713:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 2714:             }
 2715:         }
 2716:     }
 2717:     return;
 2718: }
 2719: 
 2720: sub get_course_adv_roles {
 2721:     my ($cid,$codes) = @_;
 2722:     $cid=$env{'request.course.id'} unless (defined($cid));
 2723:     my %coursehash=&coursedescription($cid);
 2724:     my $crstype = &Apache::loncommon::course_type($cid);
 2725:     my %nothide=();
 2726:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2727:         if ($user !~ /:/) {
 2728: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2729:         } else {
 2730:             $nothide{$user}=1;
 2731:         }
 2732:     }
 2733:     my %returnhash=();
 2734:     my %dumphash=
 2735:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2736:     my $now=time;
 2737:     my %privileged;
 2738:     foreach my $entry (keys %dumphash) {
 2739: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2740:         if (($tstart) && ($tstart<0)) { next; }
 2741:         if (($tend) && ($tend<$now)) { next; }
 2742:         if (($tstart) && ($now<$tstart)) { next; }
 2743:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2744: 	if ($username eq '' || $domain eq '') { next; }
 2745:         unless (ref($privileged{$domain}) eq 'HASH') {
 2746:             my %dompersonnel =
 2747:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 2748:             $privileged{$domain} = {};
 2749:             foreach my $server (keys(%dompersonnel)) {
 2750:                 if(ref($dompersonnel{$server}) eq 'HASH') {
 2751:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 2752:                         my ($trole,$uname,$udom) = split(/:/,$user);
 2753:                         $privileged{$udom}{$uname} = 1;
 2754:                     }
 2755:                 }
 2756:             }
 2757:         }
 2758:         if ((exists($privileged{$domain}{$username})) && 
 2759:             (!$nothide{$username.':'.$domain})) { next; }
 2760: 	if ($role eq 'cr') { next; }
 2761:         if ($codes) {
 2762:             if ($section) { $role .= ':'.$section; }
 2763:             if ($returnhash{$role}) {
 2764:                 $returnhash{$role}.=','.$username.':'.$domain;
 2765:             } else {
 2766:                 $returnhash{$role}=$username.':'.$domain;
 2767:             }
 2768:         } else {
 2769:             my $key=&plaintext($role,$crstype);
 2770:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 2771:             if ($returnhash{$key}) {
 2772: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2773:             } else {
 2774:                 $returnhash{$key}=$username.':'.$domain;
 2775:             }
 2776:         }
 2777:     }
 2778:     return %returnhash;
 2779: }
 2780: 
 2781: sub get_my_roles {
 2782:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2783:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2784:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2785:     my (%dumphash,%nothide);
 2786:     if ($context eq 'userroles') { 
 2787:         %dumphash = &dump('roles',$udom,$uname);
 2788:     } else {
 2789:         %dumphash=
 2790:             &dump('nohist_userroles',$udom,$uname);
 2791:         if ($hidepriv) {
 2792:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2793:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2794:                 if ($user !~ /:/) {
 2795:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2796:                 } else {
 2797:                     $nothide{$user} = 1;
 2798:                 }
 2799:             }
 2800:         }
 2801:     }
 2802:     my %returnhash=();
 2803:     my $now=time;
 2804:     foreach my $entry (keys(%dumphash)) {
 2805:         my ($role,$tend,$tstart);
 2806:         if ($context eq 'userroles') {
 2807: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2808:         } else {
 2809:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2810:         }
 2811:         if (($tstart) && ($tstart<0)) { next; }
 2812:         my $status = 'active';
 2813:         if (($tend) && ($tend<=$now)) {
 2814:             $status = 'previous';
 2815:         } 
 2816:         if (($tstart) && ($now<$tstart)) {
 2817:             $status = 'future';
 2818:         }
 2819:         if (ref($types) eq 'ARRAY') {
 2820:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2821:                 next;
 2822:             } 
 2823:         } else {
 2824:             if ($status ne 'active') {
 2825:                 next;
 2826:             }
 2827:         }
 2828:         my ($rolecode,$username,$domain,$section,$area);
 2829:         if ($context eq 'userroles') {
 2830:             ($area,$rolecode) = split(/_/,$entry);
 2831:             (undef,$domain,$username,$section) = split(/\//,$area);
 2832:         } else {
 2833:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2834:         }
 2835:         if (ref($roledoms) eq 'ARRAY') {
 2836:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2837:                 next;
 2838:             }
 2839:         }
 2840:         if (ref($roles) eq 'ARRAY') {
 2841:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2842:                 if ($role =~ /^cr\//) {
 2843:                     if (!grep(/^cr$/,@{$roles})) {
 2844:                         next;
 2845:                     }
 2846:                 } else {
 2847:                     next;
 2848:                 }
 2849:             }
 2850:         }
 2851:         if ($hidepriv) {
 2852:             if ((&privileged($username,$domain)) &&
 2853:                 (!$nothide{$username.':'.$domain})) { 
 2854:                 next;
 2855:             }
 2856:         }
 2857:         if ($withsec) {
 2858:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2859:                 $tstart.':'.$tend;
 2860:         } else {
 2861:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2862:         }
 2863:     }
 2864:     return %returnhash;
 2865: }
 2866: 
 2867: # ----------------------------------------------------- Frontpage Announcements
 2868: #
 2869: #
 2870: 
 2871: sub postannounce {
 2872:     my ($server,$text)=@_;
 2873:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2874:     unless ($text=~/\w/) { $text=''; }
 2875:     return &reply('setannounce:'.&escape($text),$server);
 2876: }
 2877: 
 2878: sub getannounce {
 2879: 
 2880:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2881: 	my $announcement='';
 2882: 	while (my $line = <$fh>) { $announcement .= $line; }
 2883: 	close($fh);
 2884: 	if ($announcement=~/\w/) { 
 2885: 	    return 
 2886:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2887:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2888: 	} else {
 2889: 	    return '';
 2890: 	}
 2891:     } else {
 2892: 	return '';
 2893:     }
 2894: }
 2895: 
 2896: # ---------------------------------------------------------- Course ID routines
 2897: # Deal with domain's nohist_courseid.db files
 2898: #
 2899: 
 2900: sub courseidput {
 2901:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2902:     my $outcome;
 2903:     if ($caller eq 'timeonly') {
 2904:         my $cids = '';
 2905:         foreach my $item (keys(%$storehash)) {
 2906:             $cids.=&escape($item).'&';
 2907:         }
 2908:         $cids=~s/\&$//;
 2909:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 2910:                           $coursehome);       
 2911:     } else {
 2912:         my $items = '';
 2913:         foreach my $item (keys(%$storehash)) {
 2914:             $items.= &escape($item).'='.
 2915:                      &freeze_escape($$storehash{$item}).'&';
 2916:         }
 2917:         $items=~s/\&$//;
 2918:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 2919:                           $coursehome);
 2920:     }
 2921:     if ($outcome eq 'unknown_cmd') {
 2922:         my $what;
 2923:         foreach my $cid (keys(%$storehash)) {
 2924:             $what .= &escape($cid).'=';
 2925:             foreach my $item ('description','inst_code','owner','type') {
 2926:                 $what .= &escape($storehash->{$cid}{$item}).':';
 2927:             }
 2928:             $what =~ s/\:$/&/;
 2929:         }
 2930:         $what =~ s/\&$//;  
 2931:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2932:     } else {
 2933:         return $outcome;
 2934:     }
 2935: }
 2936: 
 2937: sub courseiddump {
 2938:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 2939:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 2940:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
 2941:     my $as_hash = 1;
 2942:     my %returnhash;
 2943:     if (!$domfilter) { $domfilter=''; }
 2944:     my %libserv = &all_library();
 2945:     foreach my $tryserver (keys(%libserv)) {
 2946:         if ( (  $hostidflag == 1 
 2947: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2948: 	     || (!defined($hostidflag)) ) {
 2949: 
 2950: 	    if (($domfilter eq '') ||
 2951: 		(&host_domain($tryserver) eq $domfilter)) {
 2952:                 my $rep = 
 2953:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 2954:                          $sincefilter.':'.&escape($descfilter).':'.
 2955:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 2956:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 2957:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 2958:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 2959:                          $showhidden.':'.$caller,$tryserver);
 2960:                 my @pairs=split(/\&/,$rep);
 2961:                 foreach my $item (@pairs) {
 2962:                     my ($key,$value)=split(/\=/,$item,2);
 2963:                     $key = &unescape($key);
 2964:                     next if ($key =~ /^error: 2 /);
 2965:                     my $result = &thaw_unescape($value);
 2966:                     if (ref($result) eq 'HASH') {
 2967:                         $returnhash{$key}=$result;
 2968:                     } else {
 2969:                         my @responses = split(/:/,$value);
 2970:                         my @items = ('description','inst_code','owner','type');
 2971:                         for (my $i=0; $i<@responses; $i++) {
 2972:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 2973:                         }
 2974:                     } 
 2975:                 }
 2976:             }
 2977:         }
 2978:     }
 2979:     return %returnhash;
 2980: }
 2981: 
 2982: # ---------------------------------------------------------- DC e-mail
 2983: 
 2984: sub dcmailput {
 2985:     my ($domain,$msgid,$message,$server)=@_;
 2986:     my $status = &Apache::lonnet::critical(
 2987:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2988:        &escape($message),$server);
 2989:     return $status;
 2990: }
 2991: 
 2992: sub dcmaildump {
 2993:     my ($dom,$startdate,$enddate,$senders) = @_;
 2994:     my %returnhash=();
 2995: 
 2996:     if (defined(&domain($dom,'primary'))) {
 2997:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2998:                                                          &escape($enddate).':';
 2999: 	my @esc_senders=map { &escape($_)} @$senders;
 3000: 	$cmd.=&escape(join('&',@esc_senders));
 3001: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 3002:             my ($key,$value) = split(/\=/,$line,2);
 3003:             if (($key) && ($value)) {
 3004:                 $returnhash{&unescape($key)} = &unescape($value);
 3005:             }
 3006:         }
 3007:     }
 3008:     return %returnhash;
 3009: }
 3010: # ---------------------------------------------------------- Domain roles
 3011: 
 3012: sub get_domain_roles {
 3013:     my ($dom,$roles,$startdate,$enddate)=@_;
 3014:     if (undef($startdate) || $startdate eq '') {
 3015:         $startdate = '.';
 3016:     }
 3017:     if (undef($enddate) || $enddate eq '') {
 3018:         $enddate = '.';
 3019:     }
 3020:     my $rolelist;
 3021:     if (ref($roles) eq 'ARRAY') {
 3022:         $rolelist = join(':',@{$roles});
 3023:     }
 3024:     my %personnel = ();
 3025: 
 3026:     my %servers = &get_servers($dom,'library');
 3027:     foreach my $tryserver (keys(%servers)) {
 3028: 	%{$personnel{$tryserver}}=();
 3029: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 3030: 					    &escape($startdate).':'.
 3031: 					    &escape($enddate).':'.
 3032: 					    &escape($rolelist), $tryserver))) {
 3033: 	    my ($key,$value) = split(/\=/,$line,2);
 3034: 	    if (($key) && ($value)) {
 3035: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 3036: 	    }
 3037: 	}
 3038:     }
 3039:     return %personnel;
 3040: }
 3041: 
 3042: # ----------------------------------------------------------- Check out an item
 3043: 
 3044: sub get_first_access {
 3045:     my ($type,$argsymb)=@_;
 3046:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3047:     if ($argsymb) { $symb=$argsymb; }
 3048:     my ($map,$id,$res)=&decode_symb($symb);
 3049:     if ($type eq 'course') {
 3050: 	$res='course';
 3051:     } elsif ($type eq 'map') {
 3052: 	$res=&symbread($map);
 3053:     } else {
 3054: 	$res=$symb;
 3055:     }
 3056:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 3057:     return $times{"$courseid\0$res"};
 3058: }
 3059: 
 3060: sub set_first_access {
 3061:     my ($type)=@_;
 3062:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3063:     my ($map,$id,$res)=&decode_symb($symb);
 3064:     if ($type eq 'course') {
 3065: 	$res='course';
 3066:     } elsif ($type eq 'map') {
 3067: 	$res=&symbread($map);
 3068:     } else {
 3069: 	$res=$symb;
 3070:     }
 3071:     my $firstaccess=&get_first_access($type,$symb);
 3072:     if (!$firstaccess) {
 3073: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 3074:     }
 3075:     return 'already_set';
 3076: }
 3077: 
 3078: sub checkout {
 3079:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 3080:     my $now=time;
 3081:     my $lonhost=$perlvar{'lonHostID'};
 3082:     my $infostr=&escape(
 3083:                  'CHECKOUTTOKEN&'.
 3084:                  $tuname.'&'.
 3085:                  $tudom.'&'.
 3086:                  $tcrsid.'&'.
 3087:                  $symb.'&'.
 3088: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 3089:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 3090:     if ($token=~/^error\:/) { 
 3091:         &logthis("<font color=\"blue\">WARNING: ".
 3092:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 3093:                  "</font>");
 3094:         return ''; 
 3095:     }
 3096: 
 3097:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 3098:     $token=~tr/a-z/A-Z/;
 3099: 
 3100:     my %infohash=('resource.0.outtoken' => $token,
 3101:                   'resource.0.checkouttime' => $now,
 3102:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 3103: 
 3104:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3105:        return '';
 3106:     } else {
 3107:         &logthis("<font color=\"blue\">WARNING: ".
 3108:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 3109:                  "</font>");
 3110:     }    
 3111: 
 3112:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3113:                          &escape('Checkout '.$infostr.' - '.
 3114:                                                  $token)) ne 'ok') {
 3115: 	return '';
 3116:     } else {
 3117:         &logthis("<font color=\"blue\">WARNING: ".
 3118:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 3119:                  "</font>");
 3120:     }
 3121:     return $token;
 3122: }
 3123: 
 3124: # ------------------------------------------------------------ Check in an item
 3125: 
 3126: sub checkin {
 3127:     my $token=shift;
 3128:     my $now=time;
 3129:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 3130:     $lonhost=~tr/A-Z/a-z/;
 3131:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 3132:     $dtoken=~s/\W/\_/g;
 3133:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 3134:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 3135: 
 3136:     unless (($tuname) && ($tudom)) {
 3137:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 3138:         return '';
 3139:     }
 3140:     
 3141:     unless (&allowed('mgr',$tcrsid)) {
 3142:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 3143:                  $env{'user.name'}.' - '.$env{'user.domain'});
 3144:         return '';
 3145:     }
 3146: 
 3147:     my %infohash=('resource.0.intoken' => $token,
 3148:                   'resource.0.checkintime' => $now,
 3149:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 3150: 
 3151:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3152:        return '';
 3153:     }    
 3154: 
 3155:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3156:                          &escape('Checkin - '.$token)) ne 'ok') {
 3157: 	return '';
 3158:     }
 3159: 
 3160:     return ($symb,$tuname,$tudom,$tcrsid);    
 3161: }
 3162: 
 3163: # --------------------------------------------- Set Expire Date for Spreadsheet
 3164: 
 3165: sub expirespread {
 3166:     my ($uname,$udom,$stype,$usymb)=@_;
 3167:     my $cid=$env{'request.course.id'}; 
 3168:     if ($cid) {
 3169:        my $now=time;
 3170:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3171:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3172:                             $env{'course.'.$cid.'.num'}.
 3173: 	        	    ':nohist_expirationdates:'.
 3174:                             &escape($key).'='.$now,
 3175:                             $env{'course.'.$cid.'.home'})
 3176:     }
 3177:     return 'ok';
 3178: }
 3179: 
 3180: # ----------------------------------------------------- Devalidate Spreadsheets
 3181: 
 3182: sub devalidate {
 3183:     my ($symb,$uname,$udom)=@_;
 3184:     my $cid=$env{'request.course.id'}; 
 3185:     if ($cid) {
 3186:         # delete the stored spreadsheets for
 3187:         # - the student level sheet of this user in course's homespace
 3188:         # - the assessment level sheet for this resource 
 3189:         #   for this user in user's homespace
 3190: 	# - current conditional state info
 3191: 	my $key=$uname.':'.$udom.':';
 3192:         my $status=
 3193: 	    &del('nohist_calculatedsheets',
 3194: 		 [$key.'studentcalc:'],
 3195: 		 $env{'course.'.$cid.'.domain'},
 3196: 		 $env{'course.'.$cid.'.num'})
 3197: 		.' '.
 3198: 	    &del('nohist_calculatedsheets_'.$cid,
 3199: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3200:         unless ($status eq 'ok ok') {
 3201:            &logthis('Could not devalidate spreadsheet '.
 3202:                     $uname.' at '.$udom.' for '.
 3203: 		    $symb.': '.$status);
 3204:         }
 3205: 	&delenv('user.state.'.$cid);
 3206:     }
 3207: }
 3208: 
 3209: sub get_scalar {
 3210:     my ($string,$end) = @_;
 3211:     my $value;
 3212:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3213: 	$value = $1;
 3214:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3215: 	$value = $1;
 3216:     }
 3217:     return &unescape($value);
 3218: }
 3219: 
 3220: sub array2str {
 3221:   my (@array) = @_;
 3222:   my $result=&arrayref2str(\@array);
 3223:   $result=~s/^__ARRAY_REF__//;
 3224:   $result=~s/__END_ARRAY_REF__$//;
 3225:   return $result;
 3226: }
 3227: 
 3228: sub arrayref2str {
 3229:   my ($arrayref) = @_;
 3230:   my $result='__ARRAY_REF__';
 3231:   foreach my $elem (@$arrayref) {
 3232:     if(ref($elem) eq 'ARRAY') {
 3233:       $result.=&arrayref2str($elem).'&';
 3234:     } elsif(ref($elem) eq 'HASH') {
 3235:       $result.=&hashref2str($elem).'&';
 3236:     } elsif(ref($elem)) {
 3237:       #print("Got a ref of ".(ref($elem))." skipping.");
 3238:     } else {
 3239:       $result.=&escape($elem).'&';
 3240:     }
 3241:   }
 3242:   $result=~s/\&$//;
 3243:   $result .= '__END_ARRAY_REF__';
 3244:   return $result;
 3245: }
 3246: 
 3247: sub hash2str {
 3248:   my (%hash) = @_;
 3249:   my $result=&hashref2str(\%hash);
 3250:   $result=~s/^__HASH_REF__//;
 3251:   $result=~s/__END_HASH_REF__$//;
 3252:   return $result;
 3253: }
 3254: 
 3255: sub hashref2str {
 3256:   my ($hashref)=@_;
 3257:   my $result='__HASH_REF__';
 3258:   foreach my $key (sort(keys(%$hashref))) {
 3259:     if (ref($key) eq 'ARRAY') {
 3260:       $result.=&arrayref2str($key).'=';
 3261:     } elsif (ref($key) eq 'HASH') {
 3262:       $result.=&hashref2str($key).'=';
 3263:     } elsif (ref($key)) {
 3264:       $result.='=';
 3265:       #print("Got a ref of ".(ref($key))." skipping.");
 3266:     } else {
 3267: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3268:     }
 3269: 
 3270:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3271:       $result.=&arrayref2str($hashref->{$key}).'&';
 3272:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3273:       $result.=&hashref2str($hashref->{$key}).'&';
 3274:     } elsif(ref($hashref->{$key})) {
 3275:        $result.='&';
 3276:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3277:     } else {
 3278:       $result.=&escape($hashref->{$key}).'&';
 3279:     }
 3280:   }
 3281:   $result=~s/\&$//;
 3282:   $result .= '__END_HASH_REF__';
 3283:   return $result;
 3284: }
 3285: 
 3286: sub str2hash {
 3287:     my ($string)=@_;
 3288:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3289:     return %$hash;
 3290: }
 3291: 
 3292: sub str2hashref {
 3293:   my ($string) = @_;
 3294: 
 3295:   my %hash;
 3296: 
 3297:   if($string !~ /^__HASH_REF__/) {
 3298:       if (! ($string eq '' || !defined($string))) {
 3299: 	  $hash{'error'}='Not hash reference';
 3300:       }
 3301:       return (\%hash, $string);
 3302:   }
 3303: 
 3304:   $string =~ s/^__HASH_REF__//;
 3305: 
 3306:   while($string !~ /^__END_HASH_REF__/) {
 3307:       #key
 3308:       my $key='';
 3309:       if($string =~ /^__HASH_REF__/) {
 3310:           ($key, $string)=&str2hashref($string);
 3311:           if(defined($key->{'error'})) {
 3312:               $hash{'error'}='Bad data';
 3313:               return (\%hash, $string);
 3314:           }
 3315:       } elsif($string =~ /^__ARRAY_REF__/) {
 3316:           ($key, $string)=&str2arrayref($string);
 3317:           if($key->[0] eq 'Array reference error') {
 3318:               $hash{'error'}='Bad data';
 3319:               return (\%hash, $string);
 3320:           }
 3321:       } else {
 3322:           $string =~ s/^(.*?)=//;
 3323: 	  $key=&unescape($1);
 3324:       }
 3325:       $string =~ s/^=//;
 3326: 
 3327:       #value
 3328:       my $value='';
 3329:       if($string =~ /^__HASH_REF__/) {
 3330:           ($value, $string)=&str2hashref($string);
 3331:           if(defined($value->{'error'})) {
 3332:               $hash{'error'}='Bad data';
 3333:               return (\%hash, $string);
 3334:           }
 3335:       } elsif($string =~ /^__ARRAY_REF__/) {
 3336:           ($value, $string)=&str2arrayref($string);
 3337:           if($value->[0] eq 'Array reference error') {
 3338:               $hash{'error'}='Bad data';
 3339:               return (\%hash, $string);
 3340:           }
 3341:       } else {
 3342: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3343:       }
 3344:       $string =~ s/^&//;
 3345: 
 3346:       $hash{$key}=$value;
 3347:   }
 3348: 
 3349:   $string =~ s/^__END_HASH_REF__//;
 3350: 
 3351:   return (\%hash, $string);
 3352: }
 3353: 
 3354: sub str2array {
 3355:     my ($string)=@_;
 3356:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3357:     return @$array;
 3358: }
 3359: 
 3360: sub str2arrayref {
 3361:   my ($string) = @_;
 3362:   my @array;
 3363: 
 3364:   if($string !~ /^__ARRAY_REF__/) {
 3365:       if (! ($string eq '' || !defined($string))) {
 3366: 	  $array[0]='Array reference error';
 3367:       }
 3368:       return (\@array, $string);
 3369:   }
 3370: 
 3371:   $string =~ s/^__ARRAY_REF__//;
 3372: 
 3373:   while($string !~ /^__END_ARRAY_REF__/) {
 3374:       my $value='';
 3375:       if($string =~ /^__HASH_REF__/) {
 3376:           ($value, $string)=&str2hashref($string);
 3377:           if(defined($value->{'error'})) {
 3378:               $array[0] ='Array reference error';
 3379:               return (\@array, $string);
 3380:           }
 3381:       } elsif($string =~ /^__ARRAY_REF__/) {
 3382:           ($value, $string)=&str2arrayref($string);
 3383:           if($value->[0] eq 'Array reference error') {
 3384:               $array[0] ='Array reference error';
 3385:               return (\@array, $string);
 3386:           }
 3387:       } else {
 3388: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3389:       }
 3390:       $string =~ s/^&//;
 3391: 
 3392:       push(@array, $value);
 3393:   }
 3394: 
 3395:   $string =~ s/^__END_ARRAY_REF__//;
 3396: 
 3397:   return (\@array, $string);
 3398: }
 3399: 
 3400: # -------------------------------------------------------------------Temp Store
 3401: 
 3402: sub tmpreset {
 3403:   my ($symb,$namespace,$domain,$stuname) = @_;
 3404:   if (!$symb) {
 3405:     $symb=&symbread();
 3406:     if (!$symb) { $symb= $env{'request.url'}; }
 3407:   }
 3408:   $symb=escape($symb);
 3409: 
 3410:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3411:   $namespace=~s/\//\_/g;
 3412:   $namespace=~s/\W//g;
 3413: 
 3414:   if (!$domain) { $domain=$env{'user.domain'}; }
 3415:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3416:   if ($domain eq 'public' && $stuname eq 'public') {
 3417:       $stuname=$ENV{'REMOTE_ADDR'};
 3418:   }
 3419:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3420:   my %hash;
 3421:   if (tie(%hash,'GDBM_File',
 3422: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3423: 	  &GDBM_WRCREAT(),0640)) {
 3424:     foreach my $key (keys %hash) {
 3425:       if ($key=~ /:$symb/) {
 3426: 	delete($hash{$key});
 3427:       }
 3428:     }
 3429:   }
 3430: }
 3431: 
 3432: sub tmpstore {
 3433:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3434: 
 3435:   if (!$symb) {
 3436:     $symb=&symbread();
 3437:     if (!$symb) { $symb= $env{'request.url'}; }
 3438:   }
 3439:   $symb=escape($symb);
 3440: 
 3441:   if (!$namespace) {
 3442:     # I don't think we would ever want to store this for a course.
 3443:     # it seems this will only be used if we don't have a course.
 3444:     #$namespace=$env{'request.course.id'};
 3445:     #if (!$namespace) {
 3446:       $namespace=$env{'request.state'};
 3447:     #}
 3448:   }
 3449:   $namespace=~s/\//\_/g;
 3450:   $namespace=~s/\W//g;
 3451:   if (!$domain) { $domain=$env{'user.domain'}; }
 3452:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3453:   if ($domain eq 'public' && $stuname eq 'public') {
 3454:       $stuname=$ENV{'REMOTE_ADDR'};
 3455:   }
 3456:   my $now=time;
 3457:   my %hash;
 3458:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3459:   if (tie(%hash,'GDBM_File',
 3460: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3461: 	  &GDBM_WRCREAT(),0640)) {
 3462:     $hash{"version:$symb"}++;
 3463:     my $version=$hash{"version:$symb"};
 3464:     my $allkeys=''; 
 3465:     foreach my $key (keys(%$storehash)) {
 3466:       $allkeys.=$key.':';
 3467:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3468:     }
 3469:     $hash{"$version:$symb:timestamp"}=$now;
 3470:     $allkeys.='timestamp';
 3471:     $hash{"$version:keys:$symb"}=$allkeys;
 3472:     if (untie(%hash)) {
 3473:       return 'ok';
 3474:     } else {
 3475:       return "error:$!";
 3476:     }
 3477:   } else {
 3478:     return "error:$!";
 3479:   }
 3480: }
 3481: 
 3482: # -----------------------------------------------------------------Temp Restore
 3483: 
 3484: sub tmprestore {
 3485:   my ($symb,$namespace,$domain,$stuname) = @_;
 3486: 
 3487:   if (!$symb) {
 3488:     $symb=&symbread();
 3489:     if (!$symb) { $symb= $env{'request.url'}; }
 3490:   }
 3491:   $symb=escape($symb);
 3492: 
 3493:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3494: 
 3495:   if (!$domain) { $domain=$env{'user.domain'}; }
 3496:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3497:   if ($domain eq 'public' && $stuname eq 'public') {
 3498:       $stuname=$ENV{'REMOTE_ADDR'};
 3499:   }
 3500:   my %returnhash;
 3501:   $namespace=~s/\//\_/g;
 3502:   $namespace=~s/\W//g;
 3503:   my %hash;
 3504:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3505:   if (tie(%hash,'GDBM_File',
 3506: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3507: 	  &GDBM_READER(),0640)) {
 3508:     my $version=$hash{"version:$symb"};
 3509:     $returnhash{'version'}=$version;
 3510:     my $scope;
 3511:     for ($scope=1;$scope<=$version;$scope++) {
 3512:       my $vkeys=$hash{"$scope:keys:$symb"};
 3513:       my @keys=split(/:/,$vkeys);
 3514:       my $key;
 3515:       $returnhash{"$scope:keys"}=$vkeys;
 3516:       foreach $key (@keys) {
 3517: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3518: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3519:       }
 3520:     }
 3521:     if (!(untie(%hash))) {
 3522:       return "error:$!";
 3523:     }
 3524:   } else {
 3525:     return "error:$!";
 3526:   }
 3527:   return %returnhash;
 3528: }
 3529: 
 3530: # ----------------------------------------------------------------------- Store
 3531: 
 3532: sub store {
 3533:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3534:     my $home='';
 3535: 
 3536:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3537: 
 3538:     $symb=&symbclean($symb);
 3539:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3540: 
 3541:     if (!$domain) { $domain=$env{'user.domain'}; }
 3542:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3543: 
 3544:     &devalidate($symb,$stuname,$domain);
 3545: 
 3546:     $symb=escape($symb);
 3547:     if (!$namespace) { 
 3548:        unless ($namespace=$env{'request.course.id'}) { 
 3549:           return ''; 
 3550:        } 
 3551:     }
 3552:     if (!$home) { $home=$env{'user.home'}; }
 3553: 
 3554:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3555:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3556: 
 3557:     my $namevalue='';
 3558:     foreach my $key (keys(%$storehash)) {
 3559:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3560:     }
 3561:     $namevalue=~s/\&$//;
 3562:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3563:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3564: }
 3565: 
 3566: # -------------------------------------------------------------- Critical Store
 3567: 
 3568: sub cstore {
 3569:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3570:     my $home='';
 3571: 
 3572:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3573: 
 3574:     $symb=&symbclean($symb);
 3575:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3576: 
 3577:     if (!$domain) { $domain=$env{'user.domain'}; }
 3578:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3579: 
 3580:     &devalidate($symb,$stuname,$domain);
 3581: 
 3582:     $symb=escape($symb);
 3583:     if (!$namespace) { 
 3584:        unless ($namespace=$env{'request.course.id'}) { 
 3585:           return ''; 
 3586:        } 
 3587:     }
 3588:     if (!$home) { $home=$env{'user.home'}; }
 3589: 
 3590:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3591:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3592: 
 3593:     my $namevalue='';
 3594:     foreach my $key (keys(%$storehash)) {
 3595:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3596:     }
 3597:     $namevalue=~s/\&$//;
 3598:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3599:     return critical
 3600:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3601: }
 3602: 
 3603: # --------------------------------------------------------------------- Restore
 3604: 
 3605: sub restore {
 3606:     my ($symb,$namespace,$domain,$stuname) = @_;
 3607:     my $home='';
 3608: 
 3609:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3610: 
 3611:     if (!$symb) {
 3612:       unless ($symb=escape(&symbread())) { return ''; }
 3613:     } else {
 3614:       $symb=&escape(&symbclean($symb));
 3615:     }
 3616:     if (!$namespace) { 
 3617:        unless ($namespace=$env{'request.course.id'}) { 
 3618:           return ''; 
 3619:        } 
 3620:     }
 3621:     if (!$domain) { $domain=$env{'user.domain'}; }
 3622:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3623:     if (!$home) { $home=$env{'user.home'}; }
 3624:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3625: 
 3626:     my %returnhash=();
 3627:     foreach my $line (split(/\&/,$answer)) {
 3628: 	my ($name,$value)=split(/\=/,$line);
 3629:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3630:     }
 3631:     my $version;
 3632:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3633:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3634:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3635:        }
 3636:     }
 3637:     return %returnhash;
 3638: }
 3639: 
 3640: # ---------------------------------------------------------- Course Description
 3641: 
 3642: sub coursedescription {
 3643:     my ($courseid,$args)=@_;
 3644:     $courseid=~s/^\///;
 3645:     $courseid=~s/\_/\//g;
 3646:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3647:     my $chome=&homeserver($cnum,$cdomain);
 3648:     my $normalid=$cdomain.'_'.$cnum;
 3649:     # need to always cache even if we get errors otherwise we keep 
 3650:     # trying and trying and trying to get the course description.
 3651:     my %envhash=();
 3652:     my %returnhash=();
 3653:     
 3654:     my $expiretime=600;
 3655:     if ($env{'request.course.id'} eq $normalid) {
 3656: 	$expiretime=120;
 3657:     }
 3658: 
 3659:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3660:     if (!$args->{'freshen_cache'}
 3661: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3662: 	foreach my $key (keys(%env)) {
 3663: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3664: 	    my ($setting) = $1;
 3665: 	    $returnhash{$setting} = $env{$key};
 3666: 	}
 3667: 	return %returnhash;
 3668:     }
 3669: 
 3670:     # get the data agin
 3671:     if (!$args->{'one_time'}) {
 3672: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3673:     }
 3674: 
 3675:     if ($chome ne 'no_host') {
 3676:        %returnhash=&dump('environment',$cdomain,$cnum);
 3677:        if (!exists($returnhash{'con_lost'})) {
 3678:            $returnhash{'home'}= $chome;
 3679: 	   $returnhash{'domain'} = $cdomain;
 3680: 	   $returnhash{'num'} = $cnum;
 3681:            if (!defined($returnhash{'type'})) {
 3682:                $returnhash{'type'} = 'Course';
 3683:            }
 3684:            while (my ($name,$value) = each %returnhash) {
 3685:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3686:            }
 3687:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3688:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3689: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3690:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3691:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3692:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3693:        }
 3694:     }
 3695:     if (!$args->{'one_time'}) {
 3696: 	&appenv(\%envhash);
 3697:     }
 3698:     return %returnhash;
 3699: }
 3700: 
 3701: # -------------------------------------------------See if a user is privileged
 3702: 
 3703: sub privileged {
 3704:     my ($username,$domain)=@_;
 3705:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3706: 			&homeserver($username,$domain));
 3707:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3708:     my $now=time;
 3709:     if ($rolesdump ne '') {
 3710:         foreach my $entry (split(/&/,$rolesdump)) {
 3711: 	    if ($entry!~/^rolesdef_/) {
 3712: 		my ($area,$role)=split(/=/,$entry);
 3713: 		$area=~s/\_\w\w$//;
 3714: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3715: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3716: 		    my $active=1;
 3717: 		    if ($tend) {
 3718: 			if ($tend<$now) { $active=0; }
 3719: 		    }
 3720: 		    if ($tstart) {
 3721: 			if ($tstart>$now) { $active=0; }
 3722: 		    }
 3723: 		    if ($active) { return 1; }
 3724: 		}
 3725: 	    }
 3726: 	}
 3727:     }
 3728:     return 0;
 3729: }
 3730: 
 3731: # -------------------------------------------------------- Get user privileges
 3732: 
 3733: sub rolesinit {
 3734:     my ($domain,$username,$authhost)=@_;
 3735:     my %userroles;
 3736:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3737:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
 3738:     my %allroles=();
 3739:     my %allgroups=();   
 3740:     my $now=time;
 3741:     %userroles = ('user.login.time' => $now);
 3742:     my $group_privs;
 3743: 
 3744:     if ($rolesdump ne '') {
 3745:         foreach my $entry (split(/&/,$rolesdump)) {
 3746: 	  if ($entry!~/^rolesdef_/) {
 3747:             my ($area,$role)=split(/=/,$entry);
 3748: 	    $area=~s/\_\w\w$//;
 3749:             my ($trole,$tend,$tstart,$group_privs);
 3750: 	    if ($role=~/^cr/) { 
 3751: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3752: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3753: 		    ($tend,$tstart)=split('_',$trest);
 3754: 		} else {
 3755: 		    $trole=$role;
 3756: 		}
 3757:             } elsif ($role =~ m|^gr/|) {
 3758:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3759:                 ($trole,$group_privs) = split(/\//,$trole);
 3760:                 $group_privs = &unescape($group_privs);
 3761: 	    } else {
 3762: 		($trole,$tend,$tstart)=split(/_/,$role);
 3763: 	    }
 3764: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3765: 					 $username);
 3766: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3767:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3768:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3769:             if (($area ne '') && ($trole ne '')) {
 3770: 		my $spec=$trole.'.'.$area;
 3771: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3772: 		if ($trole =~ /^cr\//) {
 3773:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3774:                 } elsif ($trole eq 'gr') {
 3775:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3776: 		} else {
 3777:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3778: 		}
 3779:             }
 3780:           }
 3781:         }
 3782:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3783:         $userroles{'user.adv'}    = $adv;
 3784: 	$userroles{'user.author'} = $author;
 3785:         $env{'user.adv'}=$adv;
 3786:     }
 3787:     return \%userroles;  
 3788: }
 3789: 
 3790: sub set_arearole {
 3791:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3792: # log the associated role with the area
 3793:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3794:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3795: }
 3796: 
 3797: sub custom_roleprivs {
 3798:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3799:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3800:     my $homsvr=homeserver($rauthor,$rdomain);
 3801:     if (&hostname($homsvr) ne '') {
 3802:         my ($rdummy,$roledef)=
 3803:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3804:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3805:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3806:             if (defined($syspriv)) {
 3807:                 $$allroles{'cm./'}.=':'.$syspriv;
 3808:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3809:             }
 3810:             if ($tdomain ne '') {
 3811:                 if (defined($dompriv)) {
 3812:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3813:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3814:                 }
 3815:                 if (($trest ne '') && (defined($coursepriv))) {
 3816:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3817:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3818:                 }
 3819:             }
 3820:         }
 3821:     }
 3822: }
 3823: 
 3824: sub group_roleprivs {
 3825:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3826:     my $access = 1;
 3827:     my $now = time;
 3828:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3829:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3830:     if ($access) {
 3831:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3832:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3833:     }
 3834: }
 3835: 
 3836: sub standard_roleprivs {
 3837:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3838:     if (defined($pr{$trole.':s'})) {
 3839:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3840:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3841:     }
 3842:     if ($tdomain ne '') {
 3843:         if (defined($pr{$trole.':d'})) {
 3844:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3845:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3846:         }
 3847:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3848:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3849:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3850:         }
 3851:     }
 3852: }
 3853: 
 3854: sub set_userprivs {
 3855:     my ($userroles,$allroles,$allgroups) = @_; 
 3856:     my $author=0;
 3857:     my $adv=0;
 3858:     my %grouproles = ();
 3859:     if (keys(%{$allgroups}) > 0) {
 3860:         foreach my $role (keys %{$allroles}) {
 3861:             my ($trole,$area,$sec,$extendedarea);
 3862:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3863:                 $trole = $1;
 3864:                 $area = $2;
 3865:                 $sec = $3;
 3866:                 $extendedarea = $area.$sec;
 3867:                 if (exists($$allgroups{$area})) {
 3868:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3869:                         my $spec = $trole.'.'.$extendedarea;
 3870:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3871:                                                 $$allgroups{$area}{$group};
 3872:                     }
 3873:                 }
 3874:             }
 3875:         }
 3876:     }
 3877:     foreach my $group (keys(%grouproles)) {
 3878:         $$allroles{$group} = $grouproles{$group};
 3879:     }
 3880:     foreach my $role (keys(%{$allroles})) {
 3881:         my %thesepriv;
 3882:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3883:         foreach my $item (split(/:/,$$allroles{$role})) {
 3884:             if ($item ne '') {
 3885:                 my ($privilege,$restrictions)=split(/&/,$item);
 3886:                 if ($restrictions eq '') {
 3887:                     $thesepriv{$privilege}='F';
 3888:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3889:                     $thesepriv{$privilege}.=$restrictions;
 3890:                 }
 3891:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3892:             }
 3893:         }
 3894:         my $thesestr='';
 3895:         foreach my $priv (keys(%thesepriv)) {
 3896: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3897: 	}
 3898:         $userroles->{'user.priv.'.$role} = $thesestr;
 3899:     }
 3900:     return ($author,$adv);
 3901: }
 3902: 
 3903: sub role_status {
 3904:     my ($rolekey,$then,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 3905:     my @pwhere = ();
 3906:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 3907:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 3908:         unless (!defined($$role) || $$role eq '') {
 3909:             $$where=join('.',@pwhere);
 3910:             $$trolecode=$$role.'.'.$$where;
 3911:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 3912:             $$tstatus='is';
 3913:             if ($$tstart && $$tstart>$then) {
 3914:                 $$tstatus='future';
 3915:                 if ($$tstart<$now) { $$tstatus='will'; }
 3916:             }
 3917:             if ($$tend) {
 3918:                 if ($$tend<$then) {
 3919:                     $$tstatus='expired';
 3920:                 } elsif ($$tend<$now) {
 3921:                     $$tstatus='will_not';
 3922:                 }
 3923:             }
 3924:         }
 3925:     }
 3926: }
 3927: 
 3928: sub check_adhoc_privs {
 3929:     my ($cdom,$cnum,$then,$now,$checkrole) = @_;
 3930:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 3931:     if ($env{$cckey}) {
 3932:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 3933:         &role_status($cckey,$then,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 3934:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 3935:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
 3936:         }
 3937:     } else {
 3938:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
 3939:     }
 3940: }
 3941: 
 3942: sub set_adhoc_privileges {
 3943: # role can be cc or ca
 3944:     my ($dcdom,$pickedcourse,$role) = @_;
 3945:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 3946:     my $spec = $role.'.'.$area;
 3947:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 3948:                                   $env{'user.name'});
 3949:     my %ccrole = ();
 3950:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 3951:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 3952:     &appenv(\%userroles,[$role,'cm']);
 3953:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 3954:     &appenv( {'request.role'        => $spec,
 3955:               'request.role.domain' => $dcdom,
 3956:               'request.course.sec'  => ''
 3957:              }
 3958:            );
 3959:     my $tadv=0;
 3960:     if (&allowed('adv') eq 'F') { $tadv=1; }
 3961:     &appenv({'request.role.adv'    => $tadv});
 3962: }
 3963: 
 3964: # --------------------------------------------------------------- get interface
 3965: 
 3966: sub get {
 3967:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3968:    my $items='';
 3969:    foreach my $item (@$storearr) {
 3970:        $items.=&escape($item).'&';
 3971:    }
 3972:    $items=~s/\&$//;
 3973:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3974:    if (!$uname) { $uname=$env{'user.name'}; }
 3975:    my $uhome=&homeserver($uname,$udomain);
 3976: 
 3977:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3978:    my @pairs=split(/\&/,$rep);
 3979:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3980:      return @pairs;
 3981:    }
 3982:    my %returnhash=();
 3983:    my $i=0;
 3984:    foreach my $item (@$storearr) {
 3985:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3986:       $i++;
 3987:    }
 3988:    return %returnhash;
 3989: }
 3990: 
 3991: # --------------------------------------------------------------- del interface
 3992: 
 3993: sub del {
 3994:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3995:    my $items='';
 3996:    foreach my $item (@$storearr) {
 3997:        $items.=&escape($item).'&';
 3998:    }
 3999: 
 4000:    $items=~s/\&$//;
 4001:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4002:    if (!$uname) { $uname=$env{'user.name'}; }
 4003:    my $uhome=&homeserver($uname,$udomain);
 4004:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 4005: }
 4006: 
 4007: # -------------------------------------------------------------- dump interface
 4008: 
 4009: sub dump {
 4010:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4011:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4012:     if (!$uname) { $uname=$env{'user.name'}; }
 4013:     my $uhome=&homeserver($uname,$udomain);
 4014:     if ($regexp) {
 4015: 	$regexp=&escape($regexp);
 4016:     } else {
 4017: 	$regexp='.';
 4018:     }
 4019:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4020:     my @pairs=split(/\&/,$rep);
 4021:     my %returnhash=();
 4022:     foreach my $item (@pairs) {
 4023: 	my ($key,$value)=split(/=/,$item,2);
 4024: 	$key = &unescape($key);
 4025: 	next if ($key =~ /^error: 2 /);
 4026: 	$returnhash{$key}=&thaw_unescape($value);
 4027:     }
 4028:     return %returnhash;
 4029: }
 4030: 
 4031: # --------------------------------------------------------- dumpstore interface
 4032: 
 4033: sub dumpstore {
 4034:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4035:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4036:    if (!$uname) { $uname=$env{'user.name'}; }
 4037:    my $uhome=&homeserver($uname,$udomain);
 4038:    if ($regexp) {
 4039:        $regexp=&escape($regexp);
 4040:    } else {
 4041:        $regexp='.';
 4042:    }
 4043:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4044:    my @pairs=split(/\&/,$rep);
 4045:    my %returnhash=();
 4046:    foreach my $item (@pairs) {
 4047:        my ($key,$value)=split(/=/,$item,2);
 4048:        next if ($key =~ /^error: 2 /);
 4049:        $returnhash{$key}=&thaw_unescape($value);
 4050:    }
 4051:    return %returnhash;
 4052: }
 4053: 
 4054: # -------------------------------------------------------------- keys interface
 4055: 
 4056: sub getkeys {
 4057:    my ($namespace,$udomain,$uname)=@_;
 4058:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4059:    if (!$uname) { $uname=$env{'user.name'}; }
 4060:    my $uhome=&homeserver($uname,$udomain);
 4061:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 4062:    my @keyarray=();
 4063:    foreach my $key (split(/\&/,$rep)) {
 4064:       next if ($key =~ /^error: 2 /);
 4065:       push(@keyarray,&unescape($key));
 4066:    }
 4067:    return @keyarray;
 4068: }
 4069: 
 4070: # --------------------------------------------------------------- currentdump
 4071: sub currentdump {
 4072:    my ($courseid,$sdom,$sname)=@_;
 4073:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 4074:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 4075:    $sname    = $env{'user.name'}         if (! defined($sname));
 4076:    my $uhome = &homeserver($sname,$sdom);
 4077:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 4078:    return if ($rep =~ /^(error:|no_such_host)/);
 4079:    #
 4080:    my %returnhash=();
 4081:    #
 4082:    if ($rep eq "unknown_cmd") { 
 4083:        # an old lond will not know currentdump
 4084:        # Do a dump and make it look like a currentdump
 4085:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 4086:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 4087:        my %hash = @tmp;
 4088:        @tmp=();
 4089:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 4090:    } else {
 4091:        my @pairs=split(/\&/,$rep);
 4092:        foreach my $pair (@pairs) {
 4093:            my ($key,$value)=split(/=/,$pair,2);
 4094:            my ($symb,$param) = split(/:/,$key);
 4095:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 4096:                                                         &thaw_unescape($value);
 4097:        }
 4098:    }
 4099:    return %returnhash;
 4100: }
 4101: 
 4102: sub convert_dump_to_currentdump{
 4103:     my %hash = %{shift()};
 4104:     my %returnhash;
 4105:     # Code ripped from lond, essentially.  The only difference
 4106:     # here is the unescaping done by lonnet::dump().  Conceivably
 4107:     # we might run in to problems with parameter names =~ /^v\./
 4108:     while (my ($key,$value) = each(%hash)) {
 4109:         my ($v,$symb,$param) = split(/:/,$key);
 4110: 	$symb  = &unescape($symb);
 4111: 	$param = &unescape($param);
 4112:         next if ($v eq 'version' || $symb eq 'keys');
 4113:         next if (exists($returnhash{$symb}) &&
 4114:                  exists($returnhash{$symb}->{$param}) &&
 4115:                  $returnhash{$symb}->{'v.'.$param} > $v);
 4116:         $returnhash{$symb}->{$param}=$value;
 4117:         $returnhash{$symb}->{'v.'.$param}=$v;
 4118:     }
 4119:     #
 4120:     # Remove all of the keys in the hashes which keep track of
 4121:     # the version of the parameter.
 4122:     while (my ($symb,$param_hash) = each(%returnhash)) {
 4123:         # use a foreach because we are going to delete from the hash.
 4124:         foreach my $key (keys(%$param_hash)) {
 4125:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 4126:         }
 4127:     }
 4128:     return \%returnhash;
 4129: }
 4130: 
 4131: # ------------------------------------------------------ critical inc interface
 4132: 
 4133: sub cinc {
 4134:     return &inc(@_,'critical');
 4135: }
 4136: 
 4137: # --------------------------------------------------------------- inc interface
 4138: 
 4139: sub inc {
 4140:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 4141:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4142:     if (!$uname) { $uname=$env{'user.name'}; }
 4143:     my $uhome=&homeserver($uname,$udomain);
 4144:     my $items='';
 4145:     if (! ref($store)) {
 4146:         # got a single value, so use that instead
 4147:         $items = &escape($store).'=&';
 4148:     } elsif (ref($store) eq 'SCALAR') {
 4149:         $items = &escape($$store).'=&';        
 4150:     } elsif (ref($store) eq 'ARRAY') {
 4151:         $items = join('=&',map {&escape($_);} @{$store});
 4152:     } elsif (ref($store) eq 'HASH') {
 4153:         while (my($key,$value) = each(%{$store})) {
 4154:             $items.= &escape($key).'='.&escape($value).'&';
 4155:         }
 4156:     }
 4157:     $items=~s/\&$//;
 4158:     if ($critical) {
 4159: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 4160:     } else {
 4161: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 4162:     }
 4163: }
 4164: 
 4165: # --------------------------------------------------------------- put interface
 4166: 
 4167: sub put {
 4168:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4169:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4170:    if (!$uname) { $uname=$env{'user.name'}; }
 4171:    my $uhome=&homeserver($uname,$udomain);
 4172:    my $items='';
 4173:    foreach my $item (keys(%$storehash)) {
 4174:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4175:    }
 4176:    $items=~s/\&$//;
 4177:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4178: }
 4179: 
 4180: # ------------------------------------------------------------ newput interface
 4181: 
 4182: sub newput {
 4183:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4184:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4185:    if (!$uname) { $uname=$env{'user.name'}; }
 4186:    my $uhome=&homeserver($uname,$udomain);
 4187:    my $items='';
 4188:    foreach my $key (keys(%$storehash)) {
 4189:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4190:    }
 4191:    $items=~s/\&$//;
 4192:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 4193: }
 4194: 
 4195: # ---------------------------------------------------------  putstore interface
 4196: 
 4197: sub putstore {
 4198:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4199:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4200:    if (!$uname) { $uname=$env{'user.name'}; }
 4201:    my $uhome=&homeserver($uname,$udomain);
 4202:    my $items='';
 4203:    foreach my $key (keys(%$storehash)) {
 4204:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 4205:    }
 4206:    $items=~s/\&$//;
 4207:    my $esc_symb=&escape($symb);
 4208:    my $esc_v=&escape($version);
 4209:    my $reply =
 4210:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 4211: 	      $uhome);
 4212:    if ($reply eq 'unknown_cmd') {
 4213:        # gfall back to way things use to be done
 4214:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 4215: 			    $uname);
 4216:    }
 4217:    return $reply;
 4218: }
 4219: 
 4220: sub old_putstore {
 4221:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4222:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4223:     if (!$uname) { $uname=$env{'user.name'}; }
 4224:     my $uhome=&homeserver($uname,$udomain);
 4225:     my %newstorehash;
 4226:     foreach my $item (keys(%$storehash)) {
 4227: 	my $key = $version.':'.&escape($symb).':'.$item;
 4228: 	$newstorehash{$key} = $storehash->{$item};
 4229:     }
 4230:     my $items='';
 4231:     my %allitems = ();
 4232:     foreach my $item (keys(%newstorehash)) {
 4233: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 4234: 	    my $key = $1.':keys:'.$2;
 4235: 	    $allitems{$key} .= $3.':';
 4236: 	}
 4237: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 4238:     }
 4239:     foreach my $item (keys(%allitems)) {
 4240: 	$allitems{$item} =~ s/\:$//;
 4241: 	$items.= $item.'='.$allitems{$item}.'&';
 4242:     }
 4243:     $items=~s/\&$//;
 4244:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4245: }
 4246: 
 4247: # ------------------------------------------------------ critical put interface
 4248: 
 4249: sub cput {
 4250:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4251:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4252:    if (!$uname) { $uname=$env{'user.name'}; }
 4253:    my $uhome=&homeserver($uname,$udomain);
 4254:    my $items='';
 4255:    foreach my $item (keys(%$storehash)) {
 4256:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4257:    }
 4258:    $items=~s/\&$//;
 4259:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 4260: }
 4261: 
 4262: # -------------------------------------------------------------- eget interface
 4263: 
 4264: sub eget {
 4265:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4266:    my $items='';
 4267:    foreach my $item (@$storearr) {
 4268:        $items.=&escape($item).'&';
 4269:    }
 4270:    $items=~s/\&$//;
 4271:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4272:    if (!$uname) { $uname=$env{'user.name'}; }
 4273:    my $uhome=&homeserver($uname,$udomain);
 4274:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 4275:    my @pairs=split(/\&/,$rep);
 4276:    my %returnhash=();
 4277:    my $i=0;
 4278:    foreach my $item (@$storearr) {
 4279:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4280:       $i++;
 4281:    }
 4282:    return %returnhash;
 4283: }
 4284: 
 4285: # ------------------------------------------------------------ tmpput interface
 4286: sub tmpput {
 4287:     my ($storehash,$server,$context)=@_;
 4288:     my $items='';
 4289:     foreach my $item (keys(%$storehash)) {
 4290: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4291:     }
 4292:     $items=~s/\&$//;
 4293:     if (defined($context)) {
 4294:         $items .= ':'.&escape($context);
 4295:     }
 4296:     return &reply("tmpput:$items",$server);
 4297: }
 4298: 
 4299: # ------------------------------------------------------------ tmpget interface
 4300: sub tmpget {
 4301:     my ($token,$server)=@_;
 4302:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4303:     my $rep=&reply("tmpget:$token",$server);
 4304:     my %returnhash;
 4305:     foreach my $item (split(/\&/,$rep)) {
 4306: 	my ($key,$value)=split(/=/,$item);
 4307:         next if ($key =~ /^error: 2 /);
 4308: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 4309:     }
 4310:     return %returnhash;
 4311: }
 4312: 
 4313: # ------------------------------------------------------------ tmpget interface
 4314: sub tmpdel {
 4315:     my ($token,$server)=@_;
 4316:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4317:     return &reply("tmpdel:$token",$server);
 4318: }
 4319: 
 4320: # -------------------------------------------------- portfolio access checking
 4321: 
 4322: sub portfolio_access {
 4323:     my ($requrl) = @_;
 4324:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4325:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4326:     if ($result) {
 4327:         my %setters;
 4328:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4329:             my ($startblock,$endblock) =
 4330:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4331:             if ($startblock && $endblock) {
 4332:                 return 'B';
 4333:             }
 4334:         } else {
 4335:             my ($startblock,$endblock) =
 4336:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4337:             if ($startblock && $endblock) {
 4338:                 return 'B';
 4339:             }
 4340:         }
 4341:     }
 4342:     if ($result eq 'ok') {
 4343:        return 'F';
 4344:     } elsif ($result =~ /^[^:]+:guest_/) {
 4345:        return 'A';
 4346:     }
 4347:     return '';
 4348: }
 4349: 
 4350: sub get_portfolio_access {
 4351:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4352: 
 4353:     if (!ref($access_hash)) {
 4354: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4355: 	my %access_controls = &get_access_controls($current_perms,$group,
 4356: 						   $file_name);
 4357: 	$access_hash = $access_controls{$file_name};
 4358:     }
 4359: 
 4360:     my ($public,$guest,@domains,@users,@courses,@groups);
 4361:     my $now = time;
 4362:     if (ref($access_hash) eq 'HASH') {
 4363:         foreach my $key (keys(%{$access_hash})) {
 4364:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4365:             if ($start > $now) {
 4366:                 next;
 4367:             }
 4368:             if ($end && $end<$now) {
 4369:                 next;
 4370:             }
 4371:             if ($scope eq 'public') {
 4372:                 $public = $key;
 4373:                 last;
 4374:             } elsif ($scope eq 'guest') {
 4375:                 $guest = $key;
 4376:             } elsif ($scope eq 'domains') {
 4377:                 push(@domains,$key);
 4378:             } elsif ($scope eq 'users') {
 4379:                 push(@users,$key);
 4380:             } elsif ($scope eq 'course') {
 4381:                 push(@courses,$key);
 4382:             } elsif ($scope eq 'group') {
 4383:                 push(@groups,$key);
 4384:             }
 4385:         }
 4386:         if ($public) {
 4387:             return 'ok';
 4388:         }
 4389:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4390:             if ($guest) {
 4391:                 return $guest;
 4392:             }
 4393:         } else {
 4394:             if (@domains > 0) {
 4395:                 foreach my $domkey (@domains) {
 4396:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4397:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4398:                             return 'ok';
 4399:                         }
 4400:                     }
 4401:                 }
 4402:             }
 4403:             if (@users > 0) {
 4404:                 foreach my $userkey (@users) {
 4405:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4406:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4407:                             if (ref($item) eq 'HASH') {
 4408:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4409:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4410:                                     return 'ok';
 4411:                                 }
 4412:                             }
 4413:                         }
 4414:                     } 
 4415:                 }
 4416:             }
 4417:             my %roleshash;
 4418:             my @courses_and_groups = @courses;
 4419:             push(@courses_and_groups,@groups); 
 4420:             if (@courses_and_groups > 0) {
 4421:                 my (%allgroups,%allroles); 
 4422:                 my ($start,$end,$role,$sec,$group);
 4423:                 foreach my $envkey (%env) {
 4424:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4425:                         my $cid = $2.'_'.$3; 
 4426:                         if ($1 eq 'gr') {
 4427:                             $group = $4;
 4428:                             $allgroups{$cid}{$group} = $env{$envkey};
 4429:                         } else {
 4430:                             if ($4 eq '') {
 4431:                                 $sec = 'none';
 4432:                             } else {
 4433:                                 $sec = $4;
 4434:                             }
 4435:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4436:                         }
 4437:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4438:                         my $cid = $2.'_'.$3;
 4439:                         if ($4 eq '') {
 4440:                             $sec = 'none';
 4441:                         } else {
 4442:                             $sec = $4;
 4443:                         }
 4444:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4445:                     }
 4446:                 }
 4447:                 if (keys(%allroles) == 0) {
 4448:                     return;
 4449:                 }
 4450:                 foreach my $key (@courses_and_groups) {
 4451:                     my %content = %{$$access_hash{$key}};
 4452:                     my $cnum = $content{'number'};
 4453:                     my $cdom = $content{'domain'};
 4454:                     my $cid = $cdom.'_'.$cnum;
 4455:                     if (!exists($allroles{$cid})) {
 4456:                         next;
 4457:                     }    
 4458:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4459:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4460:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4461:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4462:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4463:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4464:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4465:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4466:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4467:                                         if (grep/^all$/,@sections) {
 4468:                                             return 'ok';
 4469:                                         } else {
 4470:                                             if (grep/^$sec$/,@sections) {
 4471:                                                 return 'ok';
 4472:                                             }
 4473:                                         }
 4474:                                     }
 4475:                                 }
 4476:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4477:                                     if (grep/^none$/,@groups) {
 4478:                                         return 'ok';
 4479:                                     }
 4480:                                 } else {
 4481:                                     if (grep/^all$/,@groups) {
 4482:                                         return 'ok';
 4483:                                     } 
 4484:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4485:                                         if (grep/^$group$/,@groups) {
 4486:                                             return 'ok';
 4487:                                         }
 4488:                                     }
 4489:                                 } 
 4490:                             }
 4491:                         }
 4492:                     }
 4493:                 }
 4494:             }
 4495:             if ($guest) {
 4496:                 return $guest;
 4497:             }
 4498:         }
 4499:     }
 4500:     return;
 4501: }
 4502: 
 4503: sub course_group_datechecker {
 4504:     my ($dates,$now,$status) = @_;
 4505:     my ($start,$end) = split(/\./,$dates);
 4506:     if (!$start && !$end) {
 4507:         return 'ok';
 4508:     }
 4509:     if (grep/^active$/,@{$status}) {
 4510:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4511:             return 'ok';
 4512:         }
 4513:     }
 4514:     if (grep/^previous$/,@{$status}) {
 4515:         if ($end > $now ) {
 4516:             return 'ok';
 4517:         }
 4518:     }
 4519:     if (grep/^future$/,@{$status}) {
 4520:         if ($start > $now) {
 4521:             return 'ok';
 4522:         }
 4523:     }
 4524:     return; 
 4525: }
 4526: 
 4527: sub parse_portfolio_url {
 4528:     my ($url) = @_;
 4529: 
 4530:     my ($type,$udom,$unum,$group,$file_name);
 4531:     
 4532:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4533: 	$type = 1;
 4534:         $udom = $1;
 4535:         $unum = $2;
 4536:         $file_name = $3;
 4537:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4538: 	$type = 2;
 4539:         $udom = $1;
 4540:         $unum = $2;
 4541:         $group = $3;
 4542:         $file_name = $3.'/'.$4;
 4543:     }
 4544:     if (wantarray) {
 4545: 	return ($type,$udom,$unum,$file_name,$group);
 4546:     }
 4547:     return $type;
 4548: }
 4549: 
 4550: sub is_portfolio_url {
 4551:     my ($url) = @_;
 4552:     return scalar(&parse_portfolio_url($url));
 4553: }
 4554: 
 4555: sub is_portfolio_file {
 4556:     my ($file) = @_;
 4557:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4558:         return 1;
 4559:     }
 4560:     return;
 4561: }
 4562: 
 4563: sub usertools_access {
 4564:     my ($uname,$udom,$tool,$action,$context) = @_;
 4565:     my ($access,%tools);
 4566:     if ($context eq '') {
 4567:         $context = 'tools';
 4568:     }
 4569:     if ($context eq 'requestcourses') {
 4570:         %tools = (
 4571:                       official   => 1,
 4572:                       unofficial => 1,
 4573:                  );
 4574:     } else {
 4575:         %tools = (
 4576:                       aboutme   => 1,
 4577:                       blog      => 1,
 4578:                       portfolio => 1,
 4579:                  );
 4580:     }
 4581:     return if (!defined($tools{$tool}));
 4582: 
 4583:     if ((!defined($udom)) || (!defined($uname))) {
 4584:         $udom = $env{'user.domain'};
 4585:         $uname = $env{'user.name'};
 4586:     }
 4587: 
 4588:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4589:         if ($action ne 'reload') {
 4590:             if ($context eq 'requestcourses') {
 4591:                 return $env{'environment.canrequest.'.$tool};
 4592:             } else {
 4593:                 return $env{'environment.availabletools.'.$tool};
 4594:             }
 4595:         }
 4596:     }
 4597: 
 4598:     my ($toolstatus,$inststatus);
 4599: 
 4600:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 4601:          ($action ne 'reload')) {
 4602:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 4603:         $inststatus = $env{'environment.inststatus'};
 4604:     } else {
 4605:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool);
 4606:         $toolstatus = $userenv{$context.'.'.$tool};
 4607:         $inststatus = $userenv{'inststatus'};
 4608:     }
 4609: 
 4610:     if ($toolstatus ne '') {
 4611:         if ($toolstatus) {
 4612:             $access = 1;
 4613:         } else {
 4614:             $access = 0;
 4615:         }
 4616:         return $access;
 4617:     }
 4618: 
 4619:     my $is_adv = &is_advanced_user($udom,$uname);
 4620:     my %domdef = &get_domain_defaults($udom);
 4621:     if (ref($domdef{$tool}) eq 'HASH') {
 4622:         if ($is_adv) {
 4623:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 4624:                 if ($domdef{$tool}{'_LC_adv'}) { 
 4625:                     $access = 1;
 4626:                 } else {
 4627:                     $access = 0;
 4628:                 }
 4629:                 return $access;
 4630:             }
 4631:         }
 4632:         if ($inststatus ne '') {
 4633:             my ($hasaccess,$hasnoaccess);
 4634:             foreach my $affiliation (split(/:/,$inststatus)) {
 4635:                 if ($domdef{$tool}{$affiliation} ne '') { 
 4636:                     if ($domdef{$tool}{$affiliation}) {
 4637:                         $hasaccess = 1;
 4638:                     } else {
 4639:                         $hasnoaccess = 1;
 4640:                     }
 4641:                 }
 4642:             }
 4643:             if ($hasaccess || $hasnoaccess) {
 4644:                 if ($hasaccess) {
 4645:                     $access = 1;
 4646:                 } elsif ($hasnoaccess) {
 4647:                     $access = 0; 
 4648:                 }
 4649:                 return $access;
 4650:             }
 4651:         } else {
 4652:             if ($domdef{$tool}{'default'} ne '') {
 4653:                 if ($domdef{$tool}{'default'}) {
 4654:                     $access = 1;
 4655:                 } elsif ($domdef{$tool}{'default'} == 0) {
 4656:                     $access = 0;
 4657:                 }
 4658:                 return $access;
 4659:             }
 4660:         }
 4661:     } else {
 4662:         if ($context eq 'tools') {
 4663:             $access = 1;
 4664:         } else {
 4665:             $access = 0;
 4666:         }
 4667:         return $access;
 4668:     }
 4669: }
 4670: 
 4671: sub is_advanced_user {
 4672:     my ($udom,$uname) = @_;
 4673:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 4674:     my %allroles;
 4675:     my $is_adv;
 4676:     foreach my $role (keys(%roleshash)) {
 4677:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 4678:         my $area = '/'.$tdomain.'/'.$trest;
 4679:         if ($sec ne '') {
 4680:             $area .= '/'.$sec;
 4681:         }
 4682:         if (($area ne '') && ($trole ne '')) {
 4683:             my $spec=$trole.'.'.$area;
 4684:             if ($trole =~ /^cr\//) {
 4685:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4686:             } elsif ($trole ne 'gr') {
 4687:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4688:             }
 4689:         }
 4690:     }
 4691:     foreach my $role (keys(%allroles)) {
 4692:         last if ($is_adv);
 4693:         foreach my $item (split(/:/,$allroles{$role})) {
 4694:             if ($item ne '') {
 4695:                 my ($privilege,$restrictions)=split(/&/,$item);
 4696:                 if ($privilege eq 'adv') {
 4697:                     $is_adv = 1;
 4698:                     last;
 4699:                 }
 4700:             }
 4701:         }
 4702:     }
 4703:     return $is_adv;
 4704: }
 4705: 
 4706: # ---------------------------------------------- Custom access rule evaluation
 4707: 
 4708: sub customaccess {
 4709:     my ($priv,$uri)=@_;
 4710:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4711:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4712:     $udom = &LONCAPA::clean_domain($udom);
 4713:     $ucrs = &LONCAPA::clean_username($ucrs);
 4714:     my $access=0;
 4715:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4716: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4717: 	if ($type eq 'user') {
 4718: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4719: 		my ($tdom,$tuname)=split(m{/},$scope);
 4720: 		if ($tdom) {
 4721: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4722: 		}
 4723: 		if ($tuname) {
 4724: 		    if ($tuname ne $env{'user.name'}) { next; }
 4725: 		}
 4726: 		$access=($effect eq 'allow');
 4727: 		last;
 4728: 	    }
 4729: 	} else {
 4730: 	    if ($role) {
 4731: 		if ($role ne $urole) { next; }
 4732: 	    }
 4733: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4734: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4735: 		if ($tdom) {
 4736: 		    if ($tdom ne $udom) { next; }
 4737: 		}
 4738: 		if ($tcrs) {
 4739: 		    if ($tcrs ne $ucrs) { next; }
 4740: 		}
 4741: 		if ($tsec) {
 4742: 		    if ($tsec ne $usec) { next; }
 4743: 		}
 4744: 		$access=($effect eq 'allow');
 4745: 		last;
 4746: 	    }
 4747: 	    if ($realm eq '' && $role eq '') {
 4748: 		$access=($effect eq 'allow');
 4749: 	    }
 4750: 	}
 4751:     }
 4752:     return $access;
 4753: }
 4754: 
 4755: # ------------------------------------------------- Check for a user privilege
 4756: 
 4757: sub allowed {
 4758:     my ($priv,$uri,$symb,$role)=@_;
 4759:     my $ver_orguri=$uri;
 4760:     $uri=&deversion($uri);
 4761:     my $orguri=$uri;
 4762:     $uri=&declutter($uri);
 4763: 
 4764:     if ($priv eq 'evb') {
 4765: # Evade communication block restrictions for specified role in a course
 4766:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4767:             return $1;
 4768:         } else {
 4769:             return;
 4770:         }
 4771:     }
 4772: 
 4773:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4774: # Free bre access to adm and meta resources
 4775:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4776: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4777: 	&& ($priv eq 'bre')) {
 4778: 	return 'F';
 4779:     }
 4780: 
 4781: # Free bre access to user's own portfolio contents
 4782:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4783:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4784: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4785:         my %setters;
 4786:         my ($startblock,$endblock) = 
 4787:             &Apache::loncommon::blockcheck(\%setters,'port');
 4788:         if ($startblock && $endblock) {
 4789:             return 'B';
 4790:         } else {
 4791:             return 'F';
 4792:         }
 4793:     }
 4794: 
 4795: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4796:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4797:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4798:         if (exists($env{'request.course.id'})) {
 4799:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4800:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4801:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4802:                 my $courseprivid=$env{'request.course.id'};
 4803:                 $courseprivid=~s/\_/\//;
 4804:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4805:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4806:                     return $1; 
 4807:                 } else {
 4808:                     if ($env{'request.course.sec'}) {
 4809:                         $courseprivid.='/'.$env{'request.course.sec'};
 4810:                     }
 4811:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4812:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4813:                         return $2;
 4814:                     }
 4815:                 }
 4816:             }
 4817:         }
 4818:     }
 4819: 
 4820: # Free bre to public access
 4821: 
 4822:     if ($priv eq 'bre') {
 4823:         my $copyright=&metadata($uri,'copyright');
 4824: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4825:            return 'F'; 
 4826:         }
 4827:         if ($copyright eq 'priv') {
 4828:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4829: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4830: 		return '';
 4831:             }
 4832:         }
 4833:         if ($copyright eq 'domain') {
 4834:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4835: 	    unless (($env{'user.domain'} eq $1) ||
 4836:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4837: 		return '';
 4838:             }
 4839:         }
 4840:         if ($env{'request.role'}=~ /li\.\//) {
 4841:             # Library role, so allow browsing of resources in this domain.
 4842:             return 'F';
 4843:         }
 4844:         if ($copyright eq 'custom') {
 4845: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4846:         }
 4847:     }
 4848:     # Domain coordinator is trying to create a course
 4849:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4850:         # uri is the requested domain in this case.
 4851:         # comparison to 'request.role.domain' shows if the user has selected
 4852:         # a role of dc for the domain in question.
 4853:         return 'F' if ($uri eq $env{'request.role.domain'});
 4854:     }
 4855: 
 4856:     my $thisallowed='';
 4857:     my $statecond=0;
 4858:     my $courseprivid='';
 4859: 
 4860: # Course
 4861: 
 4862:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4863:        $thisallowed.=$1;
 4864:     }
 4865: 
 4866: # Domain
 4867: 
 4868:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4869:        =~/\Q$priv\E\&([^\:]*)/) {
 4870:        $thisallowed.=$1;
 4871:     }
 4872: 
 4873: # Course: uri itself is a course
 4874:     my $courseuri=$uri;
 4875:     $courseuri=~s/\_(\d)/\/$1/;
 4876:     $courseuri=~s/^([^\/])/\/$1/;
 4877: 
 4878:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 4879:        =~/\Q$priv\E\&([^\:]*)/) {
 4880:        $thisallowed.=$1;
 4881:     }
 4882: 
 4883: # URI is an uploaded document for this course, default permissions don't matter
 4884: # not allowing 'edit' access (editupload) to uploaded course docs
 4885:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 4886: 	$thisallowed='';
 4887:         my ($match)=&is_on_map($uri);
 4888:         if ($match) {
 4889:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 4890:                   =~/\Q$priv\E\&([^\:]*)/) {
 4891:                 $thisallowed.=$1;
 4892:             }
 4893:         } else {
 4894:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 4895:             if ($refuri) {
 4896:                 if ($refuri =~ m|^/adm/|) {
 4897:                     $thisallowed='F';
 4898:                 } else {
 4899:                     $refuri=&declutter($refuri);
 4900:                     my ($match) = &is_on_map($refuri);
 4901:                     if ($match) {
 4902:                         $thisallowed='F';
 4903:                     }
 4904:                 }
 4905:             }
 4906:         }
 4907:     }
 4908: 
 4909:     if ($priv eq 'bre'
 4910: 	&& $thisallowed ne 'F' 
 4911: 	&& $thisallowed ne '2'
 4912: 	&& &is_portfolio_url($uri)) {
 4913: 	$thisallowed = &portfolio_access($uri);
 4914:     }
 4915:     
 4916: # Full access at system, domain or course-wide level? Exit.
 4917:     if ($thisallowed=~/F/) {
 4918: 	return 'F';
 4919:     }
 4920: 
 4921: # If this is generating or modifying users, exit with special codes
 4922: 
 4923:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4924: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4925: 	    my ($audom,$auname)=split('/',$uri);
 4926: # no author name given, so this just checks on the general right to make a co-author in this domain
 4927: 	    unless ($auname) { return $thisallowed; }
 4928: # an author name is given, so we are about to actually make a co-author for a certain account
 4929: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4930: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 4931: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 4932: 	}
 4933: 	return $thisallowed;
 4934:     }
 4935: #
 4936: # Gathered so far: system, domain and course wide privileges
 4937: #
 4938: # Course: See if uri or referer is an individual resource that is part of 
 4939: # the course
 4940: 
 4941:     if ($env{'request.course.id'}) {
 4942: 
 4943:        $courseprivid=$env{'request.course.id'};
 4944:        if ($env{'request.course.sec'}) {
 4945:           $courseprivid.='/'.$env{'request.course.sec'};
 4946:        }
 4947:        $courseprivid=~s/\_/\//;
 4948:        my $checkreferer=1;
 4949:        my ($match,$cond)=&is_on_map($uri);
 4950:        if ($match) {
 4951:            $statecond=$cond;
 4952:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4953:                =~/\Q$priv\E\&([^\:]*)/) {
 4954:                $thisallowed.=$1;
 4955:                $checkreferer=0;
 4956:            }
 4957:        }
 4958:        
 4959:        if ($checkreferer) {
 4960: 	  my $refuri=$env{'httpref.'.$orguri};
 4961:             unless ($refuri) {
 4962:                 foreach my $key (keys(%env)) {
 4963: 		    if ($key=~/^httpref\..*\*/) {
 4964: 			my $pattern=$key;
 4965:                         $pattern=~s/^httpref\.\/res\///;
 4966:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4967:                         $pattern=~s/\//\\\//g;
 4968:                         if ($orguri=~/$pattern/) {
 4969: 			    $refuri=$env{$key};
 4970:                         }
 4971:                     }
 4972:                 }
 4973:             }
 4974: 
 4975:          if ($refuri) { 
 4976: 	  $refuri=&declutter($refuri);
 4977:           my ($match,$cond)=&is_on_map($refuri);
 4978:             if ($match) {
 4979:               my $refstatecond=$cond;
 4980:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4981:                   =~/\Q$priv\E\&([^\:]*)/) {
 4982:                   $thisallowed.=$1;
 4983:                   $uri=$refuri;
 4984:                   $statecond=$refstatecond;
 4985:               }
 4986:           }
 4987:         }
 4988:        }
 4989:    }
 4990: 
 4991: #
 4992: # Gathered now: all privileges that could apply, and condition number
 4993: # 
 4994: #
 4995: # Full or no access?
 4996: #
 4997: 
 4998:     if ($thisallowed=~/F/) {
 4999: 	return 'F';
 5000:     }
 5001: 
 5002:     unless ($thisallowed) {
 5003:         return '';
 5004:     }
 5005: 
 5006: # Restrictions exist, deal with them
 5007: #
 5008: #   C:according to course preferences
 5009: #   R:according to resource settings
 5010: #   L:unless locked
 5011: #   X:according to user session state
 5012: #
 5013: 
 5014: # Possibly locked functionality, check all courses
 5015: # Locks might take effect only after 10 minutes cache expiration for other
 5016: # courses, and 2 minutes for current course
 5017: 
 5018:     my $envkey;
 5019:     if ($thisallowed=~/L/) {
 5020:         foreach $envkey (keys %env) {
 5021:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 5022:                my $courseid=$2;
 5023:                my $roleid=$1.'.'.$2;
 5024:                $courseid=~s/^\///;
 5025:                my $expiretime=600;
 5026:                if ($env{'request.role'} eq $roleid) {
 5027: 		  $expiretime=120;
 5028:                }
 5029: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 5030:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 5031:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 5032: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 5033:                }
 5034:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5035:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 5036: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 5037:                        &log($env{'user.domain'},$env{'user.name'},
 5038:                             $env{'user.home'},
 5039:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 5040:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5041:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5042: 		       return '';
 5043:                    }
 5044:                }
 5045:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5046:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 5047: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 5048:                        &log($env{'user.domain'},$env{'user.name'},
 5049:                             $env{'user.home'},
 5050:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 5051:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5052:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5053: 		       return '';
 5054:                    }
 5055:                }
 5056: 	   }
 5057:        }
 5058:     }
 5059:    
 5060: #
 5061: # Rest of the restrictions depend on selected course
 5062: #
 5063: 
 5064:     unless ($env{'request.course.id'}) {
 5065: 	if ($thisallowed eq 'A') {
 5066: 	    return 'A';
 5067:         } elsif ($thisallowed eq 'B') {
 5068:             return 'B';
 5069: 	} else {
 5070: 	    return '1';
 5071: 	}
 5072:     }
 5073: 
 5074: #
 5075: # Now user is definitely in a course
 5076: #
 5077: 
 5078: 
 5079: # Course preferences
 5080: 
 5081:    if ($thisallowed=~/C/) {
 5082:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5083:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 5084:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 5085: 	   =~/\Q$rolecode\E/) {
 5086: 	   if ($priv ne 'pch') { 
 5087: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5088: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 5089: 			$env{'request.course.id'});
 5090: 	   }
 5091:            return '';
 5092:        }
 5093: 
 5094:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 5095: 	   =~/\Q$unamedom\E/) {
 5096: 	   if ($priv ne 'pch') { 
 5097: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 5098: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 5099: 			$env{'request.course.id'});
 5100: 	   }
 5101:            return '';
 5102:        }
 5103:    }
 5104: 
 5105: # Resource preferences
 5106: 
 5107:    if ($thisallowed=~/R/) {
 5108:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5109:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 5110: 	   if ($priv ne 'pch') { 
 5111: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5112: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 5113: 	   }
 5114: 	   return '';
 5115:        }
 5116:    }
 5117: 
 5118: # Restricted by state or randomout?
 5119: 
 5120:    if ($thisallowed=~/X/) {
 5121:       if ($env{'acc.randomout'}) {
 5122: 	 if (!$symb) { $symb=&symbread($uri,1); }
 5123:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 5124:             return ''; 
 5125:          }
 5126:       }
 5127:       if (&condval($statecond)) {
 5128: 	 return '2';
 5129:       } else {
 5130:          return '';
 5131:       }
 5132:    }
 5133: 
 5134:     if ($thisallowed eq 'A') {
 5135: 	return 'A';
 5136:     } elsif ($thisallowed eq 'B') {
 5137:         return 'B';
 5138:     }
 5139:    return 'F';
 5140: }
 5141: 
 5142: sub split_uri_for_cond {
 5143:     my $uri=&deversion(&declutter(shift));
 5144:     my @uriparts=split(/\//,$uri);
 5145:     my $filename=pop(@uriparts);
 5146:     my $pathname=join('/',@uriparts);
 5147:     return ($pathname,$filename);
 5148: }
 5149: # --------------------------------------------------- Is a resource on the map?
 5150: 
 5151: sub is_on_map {
 5152:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 5153:     #Trying to find the conditional for the file
 5154:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 5155: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 5156:     if ($match) {
 5157: 	return (1,$1);
 5158:     } else {
 5159: 	return (0,0);
 5160:     }
 5161: }
 5162: 
 5163: # --------------------------------------------------------- Get symb from alias
 5164: 
 5165: sub get_symb_from_alias {
 5166:     my $symb=shift;
 5167:     my ($map,$resid,$url)=&decode_symb($symb);
 5168: # Already is a symb
 5169:     if ($url) { return $symb; }
 5170: # Must be an alias
 5171:     my $aliassymb='';
 5172:     my %bighash;
 5173:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5174:                             &GDBM_READER(),0640)) {
 5175:         my $rid=$bighash{'mapalias_'.$symb};
 5176: 	if ($rid) {
 5177: 	    my ($mapid,$resid)=split(/\./,$rid);
 5178: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 5179: 				    $resid,$bighash{'src_'.$rid});
 5180: 	}
 5181:         untie %bighash;
 5182:     }
 5183:     return $aliassymb;
 5184: }
 5185: 
 5186: # ----------------------------------------------------------------- Define Role
 5187: 
 5188: sub definerole {
 5189:   if (allowed('mcr','/')) {
 5190:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 5191:     foreach my $role (split(':',$sysrole)) {
 5192: 	my ($crole,$cqual)=split(/\&/,$role);
 5193:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 5194:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 5195: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5196:                return "refused:s:$crole&$cqual"; 
 5197:             }
 5198:         }
 5199:     }
 5200:     foreach my $role (split(':',$domrole)) {
 5201: 	my ($crole,$cqual)=split(/\&/,$role);
 5202:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 5203:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 5204: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 5205:                return "refused:d:$crole&$cqual"; 
 5206:             }
 5207:         }
 5208:     }
 5209:     foreach my $role (split(':',$courole)) {
 5210: 	my ($crole,$cqual)=split(/\&/,$role);
 5211:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 5212:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 5213: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5214:                return "refused:c:$crole&$cqual"; 
 5215:             }
 5216:         }
 5217:     }
 5218:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5219:                 "$env{'user.domain'}:$env{'user.name'}:".
 5220: 	        "rolesdef_$rolename=".
 5221:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 5222:     return reply($command,$env{'user.home'});
 5223:   } else {
 5224:     return 'refused';
 5225:   }
 5226: }
 5227: 
 5228: # ---------------- Make a metadata query against the network of library servers
 5229: 
 5230: sub metadata_query {
 5231:     my ($query,$custom,$customshow,$server_array)=@_;
 5232:     my %rhash;
 5233:     my %libserv = &all_library();
 5234:     my @server_list = (defined($server_array) ? @$server_array
 5235:                                               : keys(%libserv) );
 5236:     for my $server (@server_list) {
 5237: 	unless ($custom or $customshow) {
 5238: 	    my $reply=&reply("querysend:".&escape($query),$server);
 5239: 	    $rhash{$server}=$reply;
 5240: 	}
 5241: 	else {
 5242: 	    my $reply=&reply("querysend:".&escape($query).':'.
 5243: 			     &escape($custom).':'.&escape($customshow),
 5244: 			     $server);
 5245: 	    $rhash{$server}=$reply;
 5246: 	}
 5247:     }
 5248:     return \%rhash;
 5249: }
 5250: 
 5251: # ----------------------------------------- Send log queries and wait for reply
 5252: 
 5253: sub log_query {
 5254:     my ($uname,$udom,$query,%filters)=@_;
 5255:     my $uhome=&homeserver($uname,$udom);
 5256:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 5257:     my $uhost=&hostname($uhome);
 5258:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 5259:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 5260:                        $uhome);
 5261:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 5262:     return get_query_reply($queryid);
 5263: }
 5264: 
 5265: # -------------------------- Update MySQL table for portfolio file
 5266: 
 5267: sub update_portfolio_table {
 5268:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 5269:     if ($group ne '') {
 5270:         $file_name =~s /^\Q$group\E//;
 5271:     }
 5272:     my $homeserver = &homeserver($uname,$udom);
 5273:     my $queryid=
 5274:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 5275:                ':'.&escape($file_name).':'.$action,$homeserver);
 5276:     my $reply = &get_query_reply($queryid);
 5277:     return $reply;
 5278: }
 5279: 
 5280: # -------------------------- Update MySQL allusers table
 5281: 
 5282: sub update_allusers_table {
 5283:     my ($uname,$udom,$names) = @_;
 5284:     my $homeserver = &homeserver($uname,$udom);
 5285:     my $queryid=
 5286:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 5287:                'lastname='.&escape($names->{'lastname'}).'%%'.
 5288:                'firstname='.&escape($names->{'firstname'}).'%%'.
 5289:                'middlename='.&escape($names->{'middlename'}).'%%'.
 5290:                'generation='.&escape($names->{'generation'}).'%%'.
 5291:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 5292:                'id='.&escape($names->{'id'}),$homeserver);
 5293:     my $reply = &get_query_reply($queryid);
 5294:     return $reply;
 5295: }
 5296: 
 5297: # ------- Request retrieval of institutional classlists for course(s)
 5298: 
 5299: sub fetch_enrollment_query {
 5300:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 5301:     my $homeserver;
 5302:     my $maxtries = 1;
 5303:     if ($context eq 'automated') {
 5304:         $homeserver = $perlvar{'lonHostID'};
 5305:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 5306:     } else {
 5307:         $homeserver = &homeserver($cnum,$dom);
 5308:     }
 5309:     my $host=&hostname($homeserver);
 5310:     my $cmd = '';
 5311:     foreach my $affiliate (keys %{$affiliatesref}) {
 5312:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5313:     }
 5314:     $cmd =~ s/%%$//;
 5315:     $cmd = &escape($cmd);
 5316:     my $query = 'fetchenrollment';
 5317:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 5318:     unless ($queryid=~/^\Q$host\E\_/) { 
 5319:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 5320:         return 'error: '.$queryid;
 5321:     }
 5322:     my $reply = &get_query_reply($queryid);
 5323:     my $tries = 1;
 5324:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5325:         $reply = &get_query_reply($queryid);
 5326:         $tries ++;
 5327:     }
 5328:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5329:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5330:     } else {
 5331:         my @responses = split(/:/,$reply);
 5332:         if ($homeserver eq $perlvar{'lonHostID'}) {
 5333:             foreach my $line (@responses) {
 5334:                 my ($key,$value) = split(/=/,$line,2);
 5335:                 $$replyref{$key} = $value;
 5336:             }
 5337:         } else {
 5338:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 5339:             foreach my $line (@responses) {
 5340:                 my ($key,$value) = split(/=/,$line);
 5341:                 $$replyref{$key} = $value;
 5342:                 if ($value > 0) {
 5343:                     foreach my $item (@{$$affiliatesref{$key}}) {
 5344:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 5345:                         my $destname = $pathname.'/'.$filename;
 5346:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 5347:                         if ($xml_classlist =~ /^error/) {
 5348:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 5349:                         } else {
 5350:                             if ( open(FILE,">$destname") ) {
 5351:                                 print FILE &unescape($xml_classlist);
 5352:                                 close(FILE);
 5353:                             } else {
 5354:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 5355:                             }
 5356:                         }
 5357:                     }
 5358:                 }
 5359:             }
 5360:         }
 5361:         return 'ok';
 5362:     }
 5363:     return 'error';
 5364: }
 5365: 
 5366: sub get_query_reply {
 5367:     my $queryid=shift;
 5368:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 5369:     my $reply='';
 5370:     for (1..100) {
 5371: 	sleep 2;
 5372:         if (-e $replyfile.'.end') {
 5373: 	    if (open(my $fh,$replyfile)) {
 5374: 		$reply = join('',<$fh>);
 5375: 		close($fh);
 5376: 	   } else { return 'error: reply_file_error'; }
 5377:            return &unescape($reply);
 5378: 	}
 5379:     }
 5380:     return 'timeout:'.$queryid;
 5381: }
 5382: 
 5383: sub courselog_query {
 5384: #
 5385: # possible filters:
 5386: # url: url or symb
 5387: # username
 5388: # domain
 5389: # action: view, submit, grade
 5390: # start: timestamp
 5391: # end: timestamp
 5392: #
 5393:     my (%filters)=@_;
 5394:     unless ($env{'request.course.id'}) { return 'no_course'; }
 5395:     if ($filters{'url'}) {
 5396: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 5397:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 5398:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 5399:     }
 5400:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5401:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5402:     return &log_query($cname,$cdom,'courselog',%filters);
 5403: }
 5404: 
 5405: sub userlog_query {
 5406: #
 5407: # possible filters:
 5408: # action: log check role
 5409: # start: timestamp
 5410: # end: timestamp
 5411: #
 5412:     my ($uname,$udom,%filters)=@_;
 5413:     return &log_query($uname,$udom,'userlog',%filters);
 5414: }
 5415: 
 5416: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 5417: 
 5418: sub auto_run {
 5419:     my ($cnum,$cdom) = @_;
 5420:     my $response = 0;
 5421:     my $settings;
 5422:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 5423:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5424:         $settings = $domconfig{'autoenroll'};
 5425:         if ($settings->{'run'} eq '1') {
 5426:             $response = 1;
 5427:         }
 5428:     } else {
 5429:         my $homeserver;
 5430:         if (&is_course($cdom,$cnum)) {
 5431:             $homeserver = &homeserver($cnum,$cdom);
 5432:         } else {
 5433:             $homeserver = &domain($cdom,'primary');
 5434:         }
 5435:         if ($homeserver ne 'no_host') {
 5436:             $response = &reply('autorun:'.$cdom,$homeserver);
 5437:         }
 5438:     }
 5439:     return $response;
 5440: }
 5441: 
 5442: sub auto_get_sections {
 5443:     my ($cnum,$cdom,$inst_coursecode) = @_;
 5444:     my $homeserver = &homeserver($cnum,$cdom);
 5445:     my @secs = ();
 5446:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 5447:     unless ($response eq 'refused') {
 5448:         @secs = split(/:/,$response);
 5449:     }
 5450:     return @secs;
 5451: }
 5452: 
 5453: sub auto_new_course {
 5454:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 5455:     my $homeserver = &homeserver($cnum,$cdom);
 5456:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 5457:     return $response;
 5458: }
 5459: 
 5460: sub auto_validate_courseID {
 5461:     my ($cnum,$cdom,$inst_course_id) = @_;
 5462:     my $homeserver = &homeserver($cnum,$cdom);
 5463:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5464:     return $response;
 5465: }
 5466: 
 5467: sub auto_create_password {
 5468:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5469:     my ($homeserver,$response);
 5470:     my $create_passwd = 0;
 5471:     my $authchk = '';
 5472:     if ($udom =~ /^$match_domain$/) {
 5473:         $homeserver = &domain($udom,'primary');
 5474:     }
 5475:     if ($homeserver eq '') {
 5476:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5477:             $homeserver = &homeserver($cnum,$cdom);
 5478:         }
 5479:     }
 5480:     if ($homeserver eq '') {
 5481:         $authchk = 'nodomain';
 5482:     } else {
 5483:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5484:         if ($response eq 'refused') {
 5485:             $authchk = 'refused';
 5486:         } else {
 5487:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5488:         }
 5489:     }
 5490:     return ($authparam,$create_passwd,$authchk);
 5491: }
 5492: 
 5493: sub auto_photo_permission {
 5494:     my ($cnum,$cdom,$students) = @_;
 5495:     my $homeserver = &homeserver($cnum,$cdom);
 5496:     my ($outcome,$perm_reqd,$conditions) = 
 5497: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5498:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5499: 	return (undef,undef);
 5500:     }
 5501:     return ($outcome,$perm_reqd,$conditions);
 5502: }
 5503: 
 5504: sub auto_checkphotos {
 5505:     my ($uname,$udom,$pid) = @_;
 5506:     my $homeserver = &homeserver($uname,$udom);
 5507:     my ($result,$resulttype);
 5508:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5509: 				   &escape($uname).':'.&escape($pid),
 5510: 				   $homeserver));
 5511:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5512: 	return (undef,undef);
 5513:     }
 5514:     if ($outcome) {
 5515:         ($result,$resulttype) = split(/:/,$outcome);
 5516:     } 
 5517:     return ($result,$resulttype);
 5518: }
 5519: 
 5520: sub auto_photochoice {
 5521:     my ($cnum,$cdom) = @_;
 5522:     my $homeserver = &homeserver($cnum,$cdom);
 5523:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5524: 						       &escape($cdom),
 5525: 						       $homeserver)));
 5526:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5527: 	return (undef,undef);
 5528:     }
 5529:     return ($update,$comment);
 5530: }
 5531: 
 5532: sub auto_photoupdate {
 5533:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5534:     my $homeserver = &homeserver($cnum,$dom);
 5535:     my $host=&hostname($homeserver);
 5536:     my $cmd = '';
 5537:     my $maxtries = 1;
 5538:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5539:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5540:     }
 5541:     $cmd =~ s/%%$//;
 5542:     $cmd = &escape($cmd);
 5543:     my $query = 'institutionalphotos';
 5544:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5545:     unless ($queryid=~/^\Q$host\E\_/) {
 5546:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5547:         return 'error: '.$queryid;
 5548:     }
 5549:     my $reply = &get_query_reply($queryid);
 5550:     my $tries = 1;
 5551:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5552:         $reply = &get_query_reply($queryid);
 5553:         $tries ++;
 5554:     }
 5555:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5556:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5557:     } else {
 5558:         my @responses = split(/:/,$reply);
 5559:         my $outcome = shift(@responses); 
 5560:         foreach my $item (@responses) {
 5561:             my ($key,$value) = split(/=/,$item);
 5562:             $$photo{$key} = $value;
 5563:         }
 5564:         return $outcome;
 5565:     }
 5566:     return 'error';
 5567: }
 5568: 
 5569: sub auto_instcode_format {
 5570:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5571: 	$cat_order) = @_;
 5572:     my $courses = '';
 5573:     my @homeservers;
 5574:     if ($caller eq 'global') {
 5575: 	my %servers = &get_servers($codedom,'library');
 5576: 	foreach my $tryserver (keys(%servers)) {
 5577: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5578: 		push(@homeservers,$tryserver);
 5579: 	    }
 5580:         }
 5581:     } else {
 5582:         push(@homeservers,&homeserver($caller,$codedom));
 5583:     }
 5584:     foreach my $code (keys(%{$instcodes})) {
 5585:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5586:     }
 5587:     chop($courses);
 5588:     my $ok_response = 0;
 5589:     my $response;
 5590:     while (@homeservers > 0 && $ok_response == 0) {
 5591:         my $server = shift(@homeservers); 
 5592:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5593:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5594:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5595: 		split(/:/,$response);
 5596:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5597:             push(@{$codetitles},&str2array($codetitles_str));
 5598:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5599:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5600:             $ok_response = 1;
 5601:         }
 5602:     }
 5603:     if ($ok_response) {
 5604:         return 'ok';
 5605:     } else {
 5606:         return $response;
 5607:     }
 5608: }
 5609: 
 5610: sub auto_instcode_defaults {
 5611:     my ($domain,$returnhash,$code_order) = @_;
 5612:     my @homeservers;
 5613: 
 5614:     my %servers = &get_servers($domain,'library');
 5615:     foreach my $tryserver (keys(%servers)) {
 5616: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5617: 	    push(@homeservers,$tryserver);
 5618: 	}
 5619:     }
 5620: 
 5621:     my $response;
 5622:     foreach my $server (@homeservers) {
 5623:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5624:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5625: 	
 5626: 	foreach my $pair (split(/\&/,$response)) {
 5627: 	    my ($name,$value)=split(/\=/,$pair);
 5628: 	    if ($name eq 'code_order') {
 5629: 		@{$code_order} = split(/\&/,&unescape($value));
 5630: 	    } else {
 5631: 		$returnhash->{&unescape($name)}=&unescape($value);
 5632: 	    }
 5633: 	}
 5634: 	return 'ok';
 5635:     }
 5636: 
 5637:     return $response;
 5638: } 
 5639: 
 5640: sub auto_validate_class_sec {
 5641:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5642:     my $homeserver = &homeserver($cnum,$cdom);
 5643:     my $ownerlist;
 5644:     if (ref($owners) eq 'ARRAY') {
 5645:         $ownerlist = join(',',@{$owners});
 5646:     } else {
 5647:         $ownerlist = $owners;
 5648:     }
 5649:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 5650:                         &escape($ownerlist).':'.$cdom,$homeserver);
 5651:     return $response;
 5652: }
 5653: 
 5654: # ------------------------------------------------------- Course Group routines
 5655: 
 5656: sub get_coursegroups {
 5657:     my ($cdom,$cnum,$group,$namespace) = @_;
 5658:     return(&dump($namespace,$cdom,$cnum,$group));
 5659: }
 5660: 
 5661: sub modify_coursegroup {
 5662:     my ($cdom,$cnum,$groupsettings) = @_;
 5663:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 5664: }
 5665: 
 5666: sub toggle_coursegroup_status {
 5667:     my ($cdom,$cnum,$group,$action) = @_;
 5668:     my ($from_namespace,$to_namespace);
 5669:     if ($action eq 'delete') {
 5670:         $from_namespace = 'coursegroups';
 5671:         $to_namespace = 'deleted_groups';
 5672:     } else {
 5673:         $from_namespace = 'deleted_groups';
 5674:         $to_namespace = 'coursegroups';
 5675:     }
 5676:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 5677:     if (my $tmp = &error(%curr_group)) {
 5678:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 5679:         return ('read error',$tmp);
 5680:     } else {
 5681:         my %savedsettings = %curr_group; 
 5682:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 5683:         my $deloutcome;
 5684:         if ($result eq 'ok') {
 5685:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 5686:         } else {
 5687:             return ('write error',$result);
 5688:         }
 5689:         if ($deloutcome eq 'ok') {
 5690:             return 'ok';
 5691:         } else {
 5692:             return ('delete error',$deloutcome);
 5693:         }
 5694:     }
 5695: }
 5696: 
 5697: sub modify_group_roles {
 5698:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 5699:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 5700:     my $role = 'gr/'.&escape($userprivs);
 5701:     my ($uname,$udom) = split(/:/,$user);
 5702:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 5703:     if ($result eq 'ok') {
 5704:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 5705:     }
 5706:     return $result;
 5707: }
 5708: 
 5709: sub modify_coursegroup_membership {
 5710:     my ($cdom,$cnum,$membership) = @_;
 5711:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 5712:     return $result;
 5713: }
 5714: 
 5715: sub get_active_groups {
 5716:     my ($udom,$uname,$cdom,$cnum) = @_;
 5717:     my $now = time;
 5718:     my %groups = ();
 5719:     foreach my $key (keys(%env)) {
 5720:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 5721:             my ($start,$end) = split(/\./,$env{$key});
 5722:             if (($end!=0) && ($end<$now)) { next; }
 5723:             if (($start!=0) && ($start>$now)) { next; }
 5724:             if ($1 eq $cdom && $2 eq $cnum) {
 5725:                 $groups{$3} = $env{$key} ;
 5726:             }
 5727:         }
 5728:     }
 5729:     return %groups;
 5730: }
 5731: 
 5732: sub get_group_membership {
 5733:     my ($cdom,$cnum,$group) = @_;
 5734:     return(&dump('groupmembership',$cdom,$cnum,$group));
 5735: }
 5736: 
 5737: sub get_users_groups {
 5738:     my ($udom,$uname,$courseid) = @_;
 5739:     my @usersgroups;
 5740:     my $cachetime=1800;
 5741: 
 5742:     my $hashid="$udom:$uname:$courseid";
 5743:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 5744:     if (defined($cached)) {
 5745:         @usersgroups = split(/:/,$grouplist);
 5746:     } else {  
 5747:         $grouplist = '';
 5748:         my $courseurl = &courseid_to_courseurl($courseid);
 5749:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 5750:         my $access_end = $env{'course.'.$courseid.
 5751:                               '.default_enrollment_end_date'};
 5752:         my $now = time;
 5753:         foreach my $key (keys(%roleshash)) {
 5754:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 5755:                 my $group = $1;
 5756:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 5757:                     my $start = $2;
 5758:                     my $end = $1;
 5759:                     if ($start == -1) { next; } # deleted from group
 5760:                     if (($start!=0) && ($start>$now)) { next; }
 5761:                     if (($end!=0) && ($end<$now)) {
 5762:                         if ($access_end && $access_end < $now) {
 5763:                             if ($access_end - $end < 86400) {
 5764:                                 push(@usersgroups,$group);
 5765:                             }
 5766:                         }
 5767:                         next;
 5768:                     }
 5769:                     push(@usersgroups,$group);
 5770:                 }
 5771:             }
 5772:         }
 5773:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 5774:         $grouplist = join(':',@usersgroups);
 5775:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 5776:     }
 5777:     return @usersgroups;
 5778: }
 5779: 
 5780: sub devalidate_getgroups_cache {
 5781:     my ($udom,$uname,$cdom,$cnum)=@_;
 5782:     my $courseid = $cdom.'_'.$cnum;
 5783: 
 5784:     my $hashid="$udom:$uname:$courseid";
 5785:     &devalidate_cache_new('getgroups',$hashid);
 5786: }
 5787: 
 5788: # ------------------------------------------------------------------ Plain Text
 5789: 
 5790: sub plaintext {
 5791:     my ($short,$type,$cid,$forcedefault) = @_;
 5792:     if ($short =~ /^cr/) {
 5793: 	return (split('/',$short))[-1];
 5794:     }
 5795:     if (!defined($cid)) {
 5796:         $cid = $env{'request.course.id'};
 5797:     }
 5798:     if (defined($cid) && ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '')) {
 5799:         unless ($forcedefault) {
 5800:             my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 5801:             &Apache::lonlocal::mt_escape(\$roletext);
 5802:             return &Apache::lonlocal::mt($roletext);
 5803:         }
 5804:     }
 5805:     my %rolenames = (
 5806:                       Course => 'std',
 5807:                       Group => 'alt1',
 5808:                     );
 5809:     if (defined($type) && 
 5810:          defined($rolenames{$type}) && 
 5811:          defined($prp{$short}{$rolenames{$type}})) {
 5812:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 5813:     } else {
 5814:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 5815:     }
 5816: }
 5817: 
 5818: # ----------------------------------------------------------------- Assign Role
 5819: 
 5820: sub assignrole {
 5821:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 5822:         $context)=@_;
 5823:     my $mrole;
 5824:     if ($role =~ /^cr\//) {
 5825:         my $cwosec=$url;
 5826:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5827: 	unless (&allowed('ccr',$cwosec)) {
 5828:            &logthis('Refused custom assignrole: '.
 5829:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5830: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 5831:            return 'refused'; 
 5832:         }
 5833:         $mrole='cr';
 5834:     } elsif ($role =~ /^gr\//) {
 5835:         my $cwogrp=$url;
 5836:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 5837:         unless (&allowed('mdg',$cwogrp)) {
 5838:             &logthis('Refused group assignrole: '.
 5839:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5840:                     $env{'user.name'}.' at '.$env{'user.domain'});
 5841:             return 'refused';
 5842:         }
 5843:         $mrole='gr';
 5844:     } else {
 5845:         my $cwosec=$url;
 5846:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5847:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 5848:             my $refused;
 5849:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 5850:                 if (!(&allowed('c'.$role,$url))) {
 5851:                     $refused = 1;
 5852:                 }
 5853:             } else {
 5854:                 $refused = 1;
 5855:             }
 5856:             if ($refused) {
 5857:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5858:                     $refused = '';
 5859:                 } else {
 5860:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 5861:                              ' '.$role.' '.$end.' '.$start.' by '.
 5862: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 5863:                     return 'refused';
 5864:                 }
 5865:             }
 5866:         }
 5867:         $mrole=$role;
 5868:     }
 5869:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5870:                 "$udom:$uname:$url".'_'."$mrole=$role";
 5871:     if ($end) { $command.='_'.$end; }
 5872:     if ($start) {
 5873: 	if ($end) { 
 5874:            $command.='_'.$start; 
 5875:         } else {
 5876:            $command.='_0_'.$start;
 5877:         }
 5878:     }
 5879:     my $origstart = $start;
 5880:     my $origend = $end;
 5881:     my $delflag;
 5882: # actually delete
 5883:     if ($deleteflag) {
 5884: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 5885: # modify command to delete the role
 5886:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 5887:                 "$udom:$uname:$url".'_'."$mrole";
 5888: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 5889: # set start and finish to negative values for userrolelog
 5890:            $start=-1;
 5891:            $end=-1;
 5892:            $delflag = 1;
 5893:         }
 5894:     }
 5895: # send command
 5896:     my $answer=&reply($command,&homeserver($uname,$udom));
 5897: # log new user role if status is ok
 5898:     if ($answer eq 'ok') {
 5899: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 5900: # for course roles, perform group memberships changes triggered by role change.
 5901:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 5902:         unless ($role =~ /^gr/) {
 5903:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 5904:                                              $origstart,$selfenroll,$context);
 5905:         }
 5906:     }
 5907:     return $answer;
 5908: }
 5909: 
 5910: # -------------------------------------------------- Modify user authentication
 5911: # Overrides without validation
 5912: 
 5913: sub modifyuserauth {
 5914:     my ($udom,$uname,$umode,$upass)=@_;
 5915:     my $uhome=&homeserver($uname,$udom);
 5916:     unless (&allowed('mau',$udom)) { return 'refused'; }
 5917:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 5918:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5919:              ' in domain '.$env{'request.role.domain'});  
 5920:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 5921: 		     &escape($upass),$uhome);
 5922:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 5923:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 5924:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5925:     &log($udom,,$uname,$uhome,
 5926:         'Authentication changed by '.$env{'user.domain'}.', '.
 5927:                                      $env{'user.name'}.', '.$umode.
 5928:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5929:     unless ($reply eq 'ok') {
 5930:         &logthis('Authentication mode error: '.$reply);
 5931: 	return 'error: '.$reply;
 5932:     }   
 5933:     return 'ok';
 5934: }
 5935: 
 5936: # --------------------------------------------------------------- Modify a user
 5937: 
 5938: sub modifyuser {
 5939:     my ($udom,    $uname, $uid,
 5940:         $umode,   $upass, $first,
 5941:         $middle,  $last,  $gene,
 5942:         $forceid, $desiredhome, $email, $inststatus)=@_;
 5943:     $udom= &LONCAPA::clean_domain($udom);
 5944:     $uname=&LONCAPA::clean_username($uname);
 5945:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 5946:              $umode.', '.$first.', '.$middle.', '.
 5947: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 5948:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 5949:                                      ' desiredhome not specified'). 
 5950:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5951:              ' in domain '.$env{'request.role.domain'});
 5952:     my $uhome=&homeserver($uname,$udom,'true');
 5953: # ----------------------------------------------------------------- Create User
 5954:     if (($uhome eq 'no_host') && 
 5955: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 5956:         my $unhome='';
 5957:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 5958:             $unhome = $desiredhome;
 5959: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 5960: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 5961:         } else { # load balancing routine for determining $unhome
 5962:             my $loadm=10000000;
 5963: 	    my %servers = &get_servers($udom,'library');
 5964: 	    foreach my $tryserver (keys(%servers)) {
 5965: 		my $answer=reply('load',$tryserver);
 5966: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 5967: 		    $loadm=$answer;
 5968: 		    $unhome=$tryserver;
 5969: 		}
 5970: 	    }
 5971:         }
 5972:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 5973: 	    return 'error: unable to find a home server for '.$uname.
 5974:                    ' in domain '.$udom;
 5975:         }
 5976:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 5977:                          &escape($upass),$unhome);
 5978: 	unless ($reply eq 'ok') {
 5979:             return 'error: '.$reply;
 5980:         }   
 5981:         $uhome=&homeserver($uname,$udom,'true');
 5982:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 5983: 	    return 'error: unable verify users home machine.';
 5984:         }
 5985:     }   # End of creation of new user
 5986: # ---------------------------------------------------------------------- Add ID
 5987:     if ($uid) {
 5988:        $uid=~tr/A-Z/a-z/;
 5989:        my %uidhash=&idrget($udom,$uname);
 5990:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 5991:          && (!$forceid)) {
 5992: 	  unless ($uid eq $uidhash{$uname}) {
 5993: 	      return 'error: user id "'.$uid.'" does not match '.
 5994:                   'current user id "'.$uidhash{$uname}.'".';
 5995:           }
 5996:        } else {
 5997: 	  &idput($udom,($uname => $uid));
 5998:        }
 5999:     }
 6000: # -------------------------------------------------------------- Add names, etc
 6001:     my @tmp=&get('environment',
 6002: 		   ['firstname','middlename','lastname','generation','id',
 6003:                     'permanentemail','inststatus'],
 6004: 		   $udom,$uname);
 6005:     my %names;
 6006:     if ($tmp[0] =~ m/^error:.*/) { 
 6007:         %names=(); 
 6008:     } else {
 6009:         %names = @tmp;
 6010:     }
 6011: #
 6012: # Make sure to not trash student environment if instructor does not bother
 6013: # to supply name and email information
 6014: #
 6015:     if ($first)  { $names{'firstname'}  = $first; }
 6016:     if (defined($middle)) { $names{'middlename'} = $middle; }
 6017:     if ($last)   { $names{'lastname'}   = $last; }
 6018:     if (defined($gene))   { $names{'generation'} = $gene; }
 6019:     if ($email) {
 6020:        $email=~s/[^\w\@\.\-\,]//gs;
 6021:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 6022:     }
 6023:     if ($uid) { $names{'id'}  = $uid; }
 6024:     if (defined($inststatus)) {
 6025:         $names{'inststatus'} = '';
 6026:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 6027:         if (ref($usertypes) eq 'HASH') {
 6028:             my @okstatuses; 
 6029:             foreach my $item (split(/:/,$inststatus)) {
 6030:                 if (defined($usertypes->{$item})) {
 6031:                     push(@okstatuses,$item);  
 6032:                 }
 6033:             }
 6034:             if (@okstatuses) {
 6035:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 6036:             }
 6037:         }
 6038:     }
 6039:     my $reply = &put('environment', \%names, $udom,$uname);
 6040:     if ($reply ne 'ok') { return 'error: '.$reply; }
 6041:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 6042:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 6043:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 6044:                  $umode.', '.$first.', '.$middle.', '.
 6045: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
 6046:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 6047:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 6048:     } else {
 6049:         $logmsg .= ' during self creation';
 6050:     }
 6051:     &logthis($logmsg);
 6052:     return 'ok';
 6053: }
 6054: 
 6055: # -------------------------------------------------------------- Modify student
 6056: 
 6057: sub modifystudent {
 6058:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 6059:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 6060:         $selfenroll,$context,$inststatus)=@_;
 6061:     if (!$cid) {
 6062: 	unless ($cid=$env{'request.course.id'}) {
 6063: 	    return 'not_in_class';
 6064: 	}
 6065:     }
 6066: # --------------------------------------------------------------- Make the user
 6067:     my $reply=&modifyuser
 6068: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 6069:          $desiredhome,$email,$inststatus);
 6070:     unless ($reply eq 'ok') { return $reply; }
 6071:     # This will cause &modify_student_enrollment to get the uid from the
 6072:     # students environment
 6073:     $uid = undef if (!$forceid);
 6074:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 6075: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 6076:     return $reply;
 6077: }
 6078: 
 6079: sub modify_student_enrollment {
 6080:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 6081:     my ($cdom,$cnum,$chome);
 6082:     if (!$cid) {
 6083: 	unless ($cid=$env{'request.course.id'}) {
 6084: 	    return 'not_in_class';
 6085: 	}
 6086: 	$cdom=$env{'course.'.$cid.'.domain'};
 6087: 	$cnum=$env{'course.'.$cid.'.num'};
 6088:     } else {
 6089: 	($cdom,$cnum)=split(/_/,$cid);
 6090:     }
 6091:     $chome=$env{'course.'.$cid.'.home'};
 6092:     if (!$chome) {
 6093: 	$chome=&homeserver($cnum,$cdom);
 6094:     }
 6095:     if (!$chome) { return 'unknown_course'; }
 6096:     # Make sure the user exists
 6097:     my $uhome=&homeserver($uname,$udom);
 6098:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6099: 	return 'error: no such user';
 6100:     }
 6101:     # Get student data if we were not given enough information
 6102:     if (!defined($first)  || $first  eq '' || 
 6103:         !defined($last)   || $last   eq '' || 
 6104:         !defined($uid)    || $uid    eq '' || 
 6105:         !defined($middle) || $middle eq '' || 
 6106:         !defined($gene)   || $gene   eq '') {
 6107:         # They did not supply us with enough data to enroll the student, so
 6108:         # we need to pick up more information.
 6109:         my %tmp = &get('environment',
 6110:                        ['firstname','middlename','lastname', 'generation','id']
 6111:                        ,$udom,$uname);
 6112: 
 6113:         #foreach my $key (keys(%tmp)) {
 6114:         #    &logthis("key $key = ".$tmp{$key});
 6115:         #}
 6116:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 6117:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 6118:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 6119:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 6120:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 6121:     }
 6122:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 6123:     my $reply=cput('classlist',
 6124: 		   {"$uname:$udom" => 
 6125: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 6126: 		   $cdom,$cnum);
 6127:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 6128: 	return 'error: '.$reply;
 6129:     } else {
 6130: 	&devalidate_getsection_cache($udom,$uname,$cid);
 6131:     }
 6132:     # Add student role to user
 6133:     my $uurl='/'.$cid;
 6134:     $uurl=~s/\_/\//g;
 6135:     if ($usec) {
 6136: 	$uurl.='/'.$usec;
 6137:     }
 6138:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 6139: }
 6140: 
 6141: sub format_name {
 6142:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 6143:     my $name;
 6144:     if ($first ne 'lastname') {
 6145: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 6146:     } else {
 6147: 	if ($lastname=~/\S/) {
 6148: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 6149: 	    $name=~s/\s+,/,/;
 6150: 	} else {
 6151: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 6152: 	}
 6153:     }
 6154:     $name=~s/^\s+//;
 6155:     $name=~s/\s+$//;
 6156:     $name=~s/\s+/ /g;
 6157:     return $name;
 6158: }
 6159: 
 6160: # ------------------------------------------------- Write to course preferences
 6161: 
 6162: sub writecoursepref {
 6163:     my ($courseid,%prefs)=@_;
 6164:     $courseid=~s/^\///;
 6165:     $courseid=~s/\_/\//g;
 6166:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6167:     my $chome=homeserver($cnum,$cdomain);
 6168:     if (($chome eq '') || ($chome eq 'no_host')) { 
 6169: 	return 'error: no such course';
 6170:     }
 6171:     my $cstring='';
 6172:     foreach my $pref (keys(%prefs)) {
 6173: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 6174:     }
 6175:     $cstring=~s/\&$//;
 6176:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 6177: }
 6178: 
 6179: # ---------------------------------------------------------- Make/modify course
 6180: 
 6181: sub createcourse {
 6182:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 6183:         $course_owner,$crstype)=@_;
 6184:     $url=&declutter($url);
 6185:     my $cid='';
 6186:     unless (&allowed('ccc',$udom)) {
 6187:         return 'refused';
 6188:     }
 6189: # ------------------------------------------------------------------- Create ID
 6190:    my $uname=int(1+rand(9)).
 6191:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6192:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6193:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6194: # ----------------------------------------------- Make sure that does not exist
 6195:    my $uhome=&homeserver($uname,$udom,'true');
 6196:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6197:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6198:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6199:        $uhome=&homeserver($uname,$udom,'true');       
 6200:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6201:            return 'error: unable to generate unique course-ID';
 6202:        } 
 6203:    }
 6204: # ------------------------------------------------ Check supplied server name
 6205:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 6206:     if (! &is_library($course_server)) {
 6207:         return 'error:bad server name '.$course_server;
 6208:     }
 6209: # ------------------------------------------------------------- Make the course
 6210:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 6211:                       $course_server);
 6212:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 6213:     $uhome=&homeserver($uname,$udom,'true');
 6214:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6215: 	return 'error: no such course';
 6216:     }
 6217: # ----------------------------------------------------------------- Course made
 6218: # log existence
 6219:     my $newcourse = {
 6220:                     $udom.'_'.$uname => {
 6221:                                      description => $description,
 6222:                                      inst_code   => $inst_code,
 6223:                                      owner       => $course_owner,
 6224:                                      type        => $crstype,
 6225:                                                 },
 6226:                     };
 6227:     &courseidput($udom,$newcourse,$uhome,'notime');
 6228: # set toplevel url
 6229:     my $topurl=$url;
 6230:     unless ($nonstandard) {
 6231: # ------------------------------------------ For standard courses, make top url
 6232:         my $mapurl=&clutter($url);
 6233:         if ($mapurl eq '/res/') { $mapurl=''; }
 6234:         $env{'form.initmap'}=(<<ENDINITMAP);
 6235: <map>
 6236: <resource id="1" type="start"></resource>
 6237: <resource id="2" src="$mapurl"></resource>
 6238: <resource id="3" type="finish"></resource>
 6239: <link index="1" from="1" to="2"></link>
 6240: <link index="2" from="2" to="3"></link>
 6241: </map>
 6242: ENDINITMAP
 6243:         $topurl=&declutter(
 6244:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 6245:                           );
 6246:     }
 6247: # ----------------------------------------------------------- Write preferences
 6248:     &writecoursepref($udom.'_'.$uname,
 6249:                      ('description' => $description,
 6250:                       'url'         => $topurl));
 6251:     return '/'.$udom.'/'.$uname;
 6252: }
 6253: 
 6254: sub is_course {
 6255:     my ($cdom,$cnum) = @_;
 6256:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 6257: 				undef,'.');
 6258:     if (exists($courses{$cdom.'_'.$cnum})) {
 6259:         return 1;
 6260:     }
 6261:     return 0;
 6262: }
 6263: 
 6264: # ---------------------------------------------------------- Assign Custom Role
 6265: 
 6266: sub assigncustomrole {
 6267:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 6268:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 6269:                        $end,$start,$deleteflag,$selfenroll,$context);
 6270: }
 6271: 
 6272: # ----------------------------------------------------------------- Revoke Role
 6273: 
 6274: sub revokerole {
 6275:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 6276:     my $now=time;
 6277:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 6278: }
 6279: 
 6280: # ---------------------------------------------------------- Revoke Custom Role
 6281: 
 6282: sub revokecustomrole {
 6283:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 6284:     my $now=time;
 6285:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 6286:            $deleteflag,$selfenroll,$context);
 6287: }
 6288: 
 6289: # ------------------------------------------------------------ Disk usage
 6290: sub diskusage {
 6291:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 6292:     $directorypath =~ s/\/$//;
 6293:     my $listing=&reply('du2:'.&escape($directorypath).':'
 6294:                        .&escape($getpropath).':'.&escape($uname).':'
 6295:                        .&escape($udom),homeserver($uname,$udom));
 6296:     if ($listing eq 'unknown_cmd') {
 6297:         if ($getpropath) {
 6298:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 6299:         }
 6300:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 6301:     }
 6302:     return $listing;
 6303: }
 6304: 
 6305: sub is_locked {
 6306:     my ($file_name, $domain, $user) = @_;
 6307:     my @check;
 6308:     my $is_locked;
 6309:     push @check, $file_name;
 6310:     my %locked = &get('file_permissions',\@check,
 6311: 		      $env{'user.domain'},$env{'user.name'});
 6312:     my ($tmp)=keys(%locked);
 6313:     if ($tmp=~/^error:/) { undef(%locked); }
 6314:     
 6315:     if (ref($locked{$file_name}) eq 'ARRAY') {
 6316:         $is_locked = 'false';
 6317:         foreach my $entry (@{$locked{$file_name}}) {
 6318:            if (ref($entry) eq 'ARRAY') { 
 6319:                $is_locked = 'true';
 6320:                last;
 6321:            }
 6322:        }
 6323:     } else {
 6324:         $is_locked = 'false';
 6325:     }
 6326: }
 6327: 
 6328: sub declutter_portfile {
 6329:     my ($file) = @_;
 6330:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 6331:     return $file;
 6332: }
 6333: 
 6334: # ------------------------------------------------------------- Mark as Read Only
 6335: 
 6336: sub mark_as_readonly {
 6337:     my ($domain,$user,$files,$what) = @_;
 6338:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6339:     my ($tmp)=keys(%current_permissions);
 6340:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6341:     foreach my $file (@{$files}) {
 6342: 	$file = &declutter_portfile($file);
 6343:         push(@{$current_permissions{$file}},$what);
 6344:     }
 6345:     &put('file_permissions',\%current_permissions,$domain,$user);
 6346:     return;
 6347: }
 6348: 
 6349: # ------------------------------------------------------------Save Selected Files
 6350: 
 6351: sub save_selected_files {
 6352:     my ($user, $path, @files) = @_;
 6353:     my $filename = $user."savedfiles";
 6354:     my @other_files = &files_not_in_path($user, $path);
 6355:     open (OUT, '>'.$tmpdir.$filename);
 6356:     foreach my $file (@files) {
 6357:         print (OUT $env{'form.currentpath'}.$file."\n");
 6358:     }
 6359:     foreach my $file (@other_files) {
 6360:         print (OUT $file."\n");
 6361:     }
 6362:     close (OUT);
 6363:     return 'ok';
 6364: }
 6365: 
 6366: sub clear_selected_files {
 6367:     my ($user) = @_;
 6368:     my $filename = $user."savedfiles";
 6369:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6370:     print (OUT undef);
 6371:     close (OUT);
 6372:     return ("ok");    
 6373: }
 6374: 
 6375: sub files_in_path {
 6376:     my ($user, $path) = @_;
 6377:     my $filename = $user."savedfiles";
 6378:     my %return_files;
 6379:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6380:     while (my $line_in = <IN>) {
 6381:         chomp ($line_in);
 6382:         my @paths_and_file = split (m!/!, $line_in);
 6383:         my $file_part = pop (@paths_and_file);
 6384:         my $path_part = join ('/', @paths_and_file);
 6385:         $path_part.='/';
 6386:         my $path_and_file = $path_part.$file_part;
 6387:         if ($path_part eq $path) {
 6388:             $return_files{$file_part}= 'selected';
 6389:         }
 6390:     }
 6391:     close (IN);
 6392:     return (\%return_files);
 6393: }
 6394: 
 6395: # called in portfolio select mode, to show files selected NOT in current directory
 6396: sub files_not_in_path {
 6397:     my ($user, $path) = @_;
 6398:     my $filename = $user."savedfiles";
 6399:     my @return_files;
 6400:     my $path_part;
 6401:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6402:     while (my $line = <IN>) {
 6403:         #ok, I know it's clunky, but I want it to work
 6404:         my @paths_and_file = split(m|/|, $line);
 6405:         my $file_part = pop(@paths_and_file);
 6406:         chomp($file_part);
 6407:         my $path_part = join('/', @paths_and_file);
 6408:         $path_part .= '/';
 6409:         my $path_and_file = $path_part.$file_part;
 6410:         if ($path_part ne $path) {
 6411:             push(@return_files, ($path_and_file));
 6412:         }
 6413:     }
 6414:     close(OUT);
 6415:     return (@return_files);
 6416: }
 6417: 
 6418: #----------------------------------------------Get portfolio file permissions
 6419: 
 6420: sub get_portfile_permissions {
 6421:     my ($domain,$user) = @_;
 6422:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6423:     my ($tmp)=keys(%current_permissions);
 6424:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6425:     return \%current_permissions;
 6426: }
 6427: 
 6428: #---------------------------------------------Get portfolio file access controls
 6429: 
 6430: sub get_access_controls {
 6431:     my ($current_permissions,$group,$file) = @_;
 6432:     my %access;
 6433:     my $real_file = $file;
 6434:     $file =~ s/\.meta$//;
 6435:     if (defined($file)) {
 6436:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 6437:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 6438:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 6439:             }
 6440:         }
 6441:     } else {
 6442:         foreach my $key (keys(%{$current_permissions})) {
 6443:             if ($key =~ /\0accesscontrol$/) {
 6444:                 if (defined($group)) {
 6445:                     if ($key !~ m-^\Q$group\E/-) {
 6446:                         next;
 6447:                     }
 6448:                 }
 6449:                 my ($fullpath) = split(/\0/,$key);
 6450:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 6451:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 6452:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 6453:                     }
 6454:                 }
 6455:             }
 6456:         }
 6457:     }
 6458:     return %access;
 6459: }
 6460: 
 6461: sub modify_access_controls {
 6462:     my ($file_name,$changes,$domain,$user)=@_;
 6463:     my ($outcome,$deloutcome);
 6464:     my %store_permissions;
 6465:     my %new_values;
 6466:     my %new_control;
 6467:     my %translation;
 6468:     my @deletions = ();
 6469:     my $now = time;
 6470:     if (exists($$changes{'activate'})) {
 6471:         if (ref($$changes{'activate'}) eq 'HASH') {
 6472:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 6473:             my $numnew = scalar(@newitems);
 6474:             for (my $i=0; $i<$numnew; $i++) {
 6475:                 my $newkey = $newitems[$i];
 6476:                 my $newid = &Apache::loncommon::get_cgi_id();
 6477:                 if ($newkey =~ /^\d+:/) { 
 6478:                     $newkey =~ s/^(\d+)/$newid/;
 6479:                     $translation{$1} = $newid;
 6480:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 6481:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 6482:                     $translation{$1} = $newid;
 6483:                 }
 6484:                 $new_values{$file_name."\0".$newkey} = 
 6485:                                           $$changes{'activate'}{$newitems[$i]};
 6486:                 $new_control{$newkey} = $now;
 6487:             }
 6488:         }
 6489:     }
 6490:     my %todelete;
 6491:     my %changed_items;
 6492:     foreach my $action ('delete','update') {
 6493:         if (exists($$changes{$action})) {
 6494:             if (ref($$changes{$action}) eq 'HASH') {
 6495:                 foreach my $key (keys(%{$$changes{$action}})) {
 6496:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 6497:                     if ($action eq 'delete') { 
 6498:                         $todelete{$itemnum} = 1;
 6499:                     } else {
 6500:                         $changed_items{$itemnum} = $key;
 6501:                     }
 6502:                 }
 6503:             }
 6504:         }
 6505:     }
 6506:     # get lock on access controls for file.
 6507:     my $lockhash = {
 6508:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 6509:                                                        ':'.$env{'user.domain'},
 6510:                    }; 
 6511:     my $tries = 0;
 6512:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6513:    
 6514:     while (($gotlock ne 'ok') && $tries <3) {
 6515:         $tries ++;
 6516:         sleep 1;
 6517:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6518:     }
 6519:     if ($gotlock eq 'ok') {
 6520:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 6521:         my ($tmp)=keys(%curr_permissions);
 6522:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 6523:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 6524:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 6525:             if (ref($curr_controls) eq 'HASH') {
 6526:                 foreach my $control_item (keys(%{$curr_controls})) {
 6527:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 6528:                     if (defined($todelete{$itemnum})) {
 6529:                         push(@deletions,$file_name."\0".$control_item);
 6530:                     } else {
 6531:                         if (defined($changed_items{$itemnum})) {
 6532:                             $new_control{$changed_items{$itemnum}} = $now;
 6533:                             push(@deletions,$file_name."\0".$control_item);
 6534:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 6535:                         } else {
 6536:                             $new_control{$control_item} = $$curr_controls{$control_item};
 6537:                         }
 6538:                     }
 6539:                 }
 6540:             }
 6541:         }
 6542:         my ($group);
 6543:         if (&is_course($domain,$user)) {
 6544:             ($group,my $file) = split(/\//,$file_name,2);
 6545:         }
 6546:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 6547:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 6548:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 6549:         #  remove lock
 6550:         my @del_lock = ($file_name."\0".'locked_access_records');
 6551:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 6552:         my $sqlresult =
 6553:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 6554:                                     $group);
 6555:     } else {
 6556:         $outcome = "error: could not obtain lockfile\n";  
 6557:     }
 6558:     return ($outcome,$deloutcome,\%new_values,\%translation);
 6559: }
 6560: 
 6561: sub make_public_indefinitely {
 6562:     my ($requrl) = @_;
 6563:     my $now = time;
 6564:     my $action = 'activate';
 6565:     my $aclnum = 0;
 6566:     if (&is_portfolio_url($requrl)) {
 6567:         my (undef,$udom,$unum,$file_name,$group) =
 6568:             &parse_portfolio_url($requrl);
 6569:         my $current_perms = &get_portfile_permissions($udom,$unum);
 6570:         my %access_controls = &get_access_controls($current_perms,
 6571:                                                    $group,$file_name);
 6572:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 6573:             my ($num,$scope,$end,$start) = 
 6574:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6575:             if ($scope eq 'public') {
 6576:                 if ($start <= $now && $end == 0) {
 6577:                     $action = 'none';
 6578:                 } else {
 6579:                     $action = 'update';
 6580:                     $aclnum = $num;
 6581:                 }
 6582:                 last;
 6583:             }
 6584:         }
 6585:         if ($action eq 'none') {
 6586:              return 'ok';
 6587:         } else {
 6588:             my %changes;
 6589:             my $newend = 0;
 6590:             my $newstart = $now;
 6591:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 6592:             $changes{$action}{$newkey} = {
 6593:                 type => 'public',
 6594:                 time => {
 6595:                     start => $newstart,
 6596:                     end   => $newend,
 6597:                 },
 6598:             };
 6599:             my ($outcome,$deloutcome,$new_values,$translation) =
 6600:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 6601:             return $outcome;
 6602:         }
 6603:     } else {
 6604:         return 'invalid';
 6605:     }
 6606: }
 6607: 
 6608: #------------------------------------------------------Get Marked as Read Only
 6609: 
 6610: sub get_marked_as_readonly {
 6611:     my ($domain,$user,$what,$group) = @_;
 6612:     my $current_permissions = &get_portfile_permissions($domain,$user);
 6613:     my @readonly_files;
 6614:     my $cmp1=$what;
 6615:     if (ref($what)) { $cmp1=join('',@{$what}) };
 6616:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6617:         if (defined($group)) {
 6618:             if ($file_name !~ m-^\Q$group\E/-) {
 6619:                 next;
 6620:             }
 6621:         }
 6622:         if (ref($value) eq "ARRAY"){
 6623:             foreach my $stored_what (@{$value}) {
 6624:                 my $cmp2=$stored_what;
 6625:                 if (ref($stored_what) eq 'ARRAY') {
 6626:                     $cmp2=join('',@{$stored_what});
 6627:                 }
 6628:                 if ($cmp1 eq $cmp2) {
 6629:                     push(@readonly_files, $file_name);
 6630:                     last;
 6631:                 } elsif (!defined($what)) {
 6632:                     push(@readonly_files, $file_name);
 6633:                     last;
 6634:                 }
 6635:             }
 6636:         }
 6637:     }
 6638:     return @readonly_files;
 6639: }
 6640: #-----------------------------------------------------------Get Marked as Read Only Hash
 6641: 
 6642: sub get_marked_as_readonly_hash {
 6643:     my ($current_permissions,$group,$what) = @_;
 6644:     my %readonly_files;
 6645:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6646:         if (defined($group)) {
 6647:             if ($file_name !~ m-^\Q$group\E/-) {
 6648:                 next;
 6649:             }
 6650:         }
 6651:         if (ref($value) eq "ARRAY"){
 6652:             foreach my $stored_what (@{$value}) {
 6653:                 if (ref($stored_what) eq 'ARRAY') {
 6654:                     foreach my $lock_descriptor(@{$stored_what}) {
 6655:                         if ($lock_descriptor eq 'graded') {
 6656:                             $readonly_files{$file_name} = 'graded';
 6657:                         } elsif ($lock_descriptor eq 'handback') {
 6658:                             $readonly_files{$file_name} = 'handback';
 6659:                         } else {
 6660:                             if (!exists($readonly_files{$file_name})) {
 6661:                                 $readonly_files{$file_name} = 'locked';
 6662:                             }
 6663:                         }
 6664:                     }
 6665:                 } 
 6666:             }
 6667:         } 
 6668:     }
 6669:     return %readonly_files;
 6670: }
 6671: # ------------------------------------------------------------ Unmark as Read Only
 6672: 
 6673: sub unmark_as_readonly {
 6674:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 6675:     # for portfolio submissions, $what contains [$symb,$crsid] 
 6676:     my ($domain,$user,$what,$file_name,$group) = @_;
 6677:     $file_name = &declutter_portfile($file_name);
 6678:     my $symb_crs = $what;
 6679:     if (ref($what)) { $symb_crs=join('',@$what); }
 6680:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 6681:     my ($tmp)=keys(%current_permissions);
 6682:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6683:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 6684:     foreach my $file (@readonly_files) {
 6685: 	my $clean_file = &declutter_portfile($file);
 6686: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 6687: 	my $current_locks = $current_permissions{$file};
 6688:         my @new_locks;
 6689:         my @del_keys;
 6690:         if (ref($current_locks) eq "ARRAY"){
 6691:             foreach my $locker (@{$current_locks}) {
 6692:                 my $compare=$locker;
 6693:                 if (ref($locker) eq 'ARRAY') {
 6694:                     $compare=join('',@{$locker});
 6695:                     if ($compare ne $symb_crs) {
 6696:                         push(@new_locks, $locker);
 6697:                     }
 6698:                 }
 6699:             }
 6700:             if (scalar(@new_locks) > 0) {
 6701:                 $current_permissions{$file} = \@new_locks;
 6702:             } else {
 6703:                 push(@del_keys, $file);
 6704:                 &del('file_permissions',\@del_keys, $domain, $user);
 6705:                 delete($current_permissions{$file});
 6706:             }
 6707:         }
 6708:     }
 6709:     &put('file_permissions',\%current_permissions,$domain,$user);
 6710:     return;
 6711: }
 6712: 
 6713: # ------------------------------------------------------------ Directory lister
 6714: 
 6715: sub dirlist {
 6716:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 6717:     $uri=~s/^\///;
 6718:     $uri=~s/\/$//;
 6719:     my ($udom, $uname);
 6720:     if ($getuserdir) {
 6721:         $udom = $userdomain;
 6722:         $uname = $username;
 6723:     } else {
 6724:         (undef,$udom,$uname)=split(/\//,$uri);
 6725:         if(defined($userdomain)) {
 6726:             $udom = $userdomain;
 6727:         }
 6728:         if(defined($username)) {
 6729:             $uname = $username;
 6730:         }
 6731:     }
 6732:     my ($dirRoot,$listing,@listing_results);
 6733: 
 6734:     $dirRoot = $perlvar{'lonDocRoot'};
 6735:     if (defined($getpropath)) {
 6736:         $dirRoot = &propath($udom,$uname);
 6737:         $dirRoot =~ s/\/$//;
 6738:     } elsif (defined($getuserdir)) {
 6739:         my $subdir=$uname.'__';
 6740:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 6741:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 6742:                    ."/$udom/$subdir/$uname";
 6743:     } elsif (defined($alternateRoot)) {
 6744:         $dirRoot = $alternateRoot;
 6745:     }
 6746: 
 6747:     if($udom) {
 6748:         if($uname) {
 6749:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 6750:                               .$getuserdir.':'.&escape($dirRoot)
 6751:                               .':'.&escape($uname).':'.&escape($udom),
 6752:                               &homeserver($uname,$udom));
 6753:             if ($listing eq 'unknown_cmd') {
 6754:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 6755:                                   &homeserver($uname,$udom));
 6756:             } else {
 6757:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6758:             }
 6759:             if ($listing eq 'unknown_cmd') {
 6760:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 6761: 				  &homeserver($uname,$udom));
 6762:                 @listing_results = split(/:/,$listing);
 6763:             } else {
 6764:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6765:             }
 6766:             return @listing_results;
 6767:         } elsif(!$alternateRoot) {
 6768:             my %allusers;
 6769: 	    my %servers = &get_servers($udom,'library');
 6770:  	    foreach my $tryserver (keys(%servers)) {
 6771:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 6772:                                   &escape($udom),$tryserver);
 6773:                 if ($listing eq 'unknown_cmd') {
 6774: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 6775: 				      $udom, $tryserver);
 6776:                 } else {
 6777:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 6778:                 }
 6779: 		if ($listing eq 'unknown_cmd') {
 6780: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 6781: 				      $udom, $tryserver);
 6782: 		    @listing_results = split(/:/,$listing);
 6783: 		} else {
 6784: 		    @listing_results =
 6785: 			map { &unescape($_); } split(/:/,$listing);
 6786: 		}
 6787: 		if ($listing_results[0] ne 'no_such_dir' && 
 6788: 		    $listing_results[0] ne 'empty'       &&
 6789: 		    $listing_results[0] ne 'con_lost') {
 6790: 		    foreach my $line (@listing_results) {
 6791: 			my ($entry) = split(/&/,$line,2);
 6792: 			$allusers{$entry} = 1;
 6793: 		    }
 6794: 		}
 6795:             }
 6796:             my $alluserstr='';
 6797:             foreach my $user (sort(keys(%allusers))) {
 6798:                 $alluserstr.=$user.'&user:';
 6799:             }
 6800:             $alluserstr=~s/:$//;
 6801:             return split(/:/,$alluserstr);
 6802:         } else {
 6803:             return ('missing user name');
 6804:         }
 6805:     } elsif(!defined($getpropath)) {
 6806:         my @all_domains = sort(&all_domains());
 6807:         foreach my $domain (@all_domains) {
 6808:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 6809:         }
 6810:         return @all_domains;
 6811:     } else {
 6812:         return ('missing domain');
 6813:     }
 6814: }
 6815: 
 6816: # --------------------------------------------- GetFileTimestamp
 6817: # This function utilizes dirlist and returns the date stamp for
 6818: # when it was last modified.  It will also return an error of -1
 6819: # if an error occurs
 6820: 
 6821: sub GetFileTimestamp {
 6822:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 6823:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 6824:     $studentName   = &LONCAPA::clean_username($studentName);
 6825:     my ($fileStat) = 
 6826:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
 6827:                                  undef,$getuserdir);
 6828:     my @stats = split('&', $fileStat);
 6829:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6830:         # @stats contains first the filename, then the stat output
 6831:         return $stats[10]; # so this is 10 instead of 9.
 6832:     } else {
 6833:         return -1;
 6834:     }
 6835: }
 6836: 
 6837: sub stat_file {
 6838:     my ($uri) = @_;
 6839:     $uri = &clutter_with_no_wrapper($uri);
 6840: 
 6841:     my ($udom,$uname,$file);
 6842:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 6843: 	($udom,$uname,$file) =
 6844: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 6845: 	$file = 'userfiles/'.$file;
 6846:     }
 6847:     if ($uri =~ m-^/res/-) {
 6848: 	($udom,$uname) = 
 6849: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 6850: 	$file = $uri;
 6851:     }
 6852: 
 6853:     if (!$udom || !$uname || !$file) {
 6854: 	# unable to handle the uri
 6855: 	return ();
 6856:     }
 6857:     my $getpropath;
 6858:     if ($file =~ /^userfiles\//) {
 6859:         $getpropath = 1;
 6860:     }
 6861:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
 6862:     my @stats = split('&', $result);
 6863:     
 6864:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6865: 	shift(@stats); #filename is first
 6866: 	return @stats;
 6867:     }
 6868:     return ();
 6869: }
 6870: 
 6871: # -------------------------------------------------------- Value of a Condition
 6872: 
 6873: # gets the value of a specific preevaluated condition
 6874: #    stored in the string  $env{user.state.<cid>}
 6875: # or looks up a condition reference in the bighash and if if hasn't
 6876: # already been evaluated recurses into docondval to get the value of
 6877: # the condition, then memoizing it to 
 6878: #   $env{user.state.<cid>.<condition>}
 6879: sub directcondval {
 6880:     my $number=shift;
 6881:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 6882: 	&Apache::lonuserstate::evalstate();
 6883:     }
 6884:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 6885: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 6886:     } elsif ($number =~ /^_/) {
 6887: 	my $sub_condition;
 6888: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6889: 		&GDBM_READER(),0640)) {
 6890: 	    $sub_condition=$bighash{'conditions'.$number};
 6891: 	    untie(%bighash);
 6892: 	}
 6893: 	my $value = &docondval($sub_condition);
 6894: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 6895: 	return $value;
 6896:     }
 6897:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 6898:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 6899:     } else {
 6900:        return 2;
 6901:     }
 6902: }
 6903: 
 6904: # get the collection of conditions for this resource
 6905: sub condval {
 6906:     my $condidx=shift;
 6907:     my $allpathcond='';
 6908:     foreach my $cond (split(/\|/,$condidx)) {
 6909: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 6910: 	    $allpathcond.=
 6911: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 6912: 	}
 6913:     }
 6914:     $allpathcond=~s/\|$//;
 6915:     return &docondval($allpathcond);
 6916: }
 6917: 
 6918: #evaluates an expression of conditions
 6919: sub docondval {
 6920:     my ($allpathcond) = @_;
 6921:     my $result=0;
 6922:     if ($env{'request.course.id'}
 6923: 	&& defined($allpathcond)) {
 6924: 	my $operand='|';
 6925: 	my @stack;
 6926: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 6927: 	    if ($chunk eq '(') {
 6928: 		push @stack,($operand,$result);
 6929: 	    } elsif ($chunk eq ')') {
 6930: 		my $before=pop @stack;
 6931: 		if (pop @stack eq '&') {
 6932: 		    $result=$result>$before?$before:$result;
 6933: 		} else {
 6934: 		    $result=$result>$before?$result:$before;
 6935: 		}
 6936: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 6937: 		$operand=$chunk;
 6938: 	    } else {
 6939: 		my $new=directcondval($chunk);
 6940: 		if ($operand eq '&') {
 6941: 		    $result=$result>$new?$new:$result;
 6942: 		} else {
 6943: 		    $result=$result>$new?$result:$new;
 6944: 		}
 6945: 	    }
 6946: 	}
 6947:     }
 6948:     return $result;
 6949: }
 6950: 
 6951: # ---------------------------------------------------- Devalidate courseresdata
 6952: 
 6953: sub devalidatecourseresdata {
 6954:     my ($coursenum,$coursedomain)=@_;
 6955:     my $hashid=$coursenum.':'.$coursedomain;
 6956:     &devalidate_cache_new('courseres',$hashid);
 6957: }
 6958: 
 6959: 
 6960: # --------------------------------------------------- Course Resourcedata Query
 6961: #
 6962: #  Parameters:
 6963: #      $coursenum    - Number of the course.
 6964: #      $coursedomain - Domain at which the course was created.
 6965: #  Returns:
 6966: #     A hash of the course parameters along (I think) with timestamps
 6967: #     and version info.
 6968: 
 6969: sub get_courseresdata {
 6970:     my ($coursenum,$coursedomain)=@_;
 6971:     my $coursehom=&homeserver($coursenum,$coursedomain);
 6972:     my $hashid=$coursenum.':'.$coursedomain;
 6973:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 6974:     my %dumpreply;
 6975:     unless (defined($cached)) {
 6976: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 6977: 	$result=\%dumpreply;
 6978: 	my ($tmp) = keys(%dumpreply);
 6979: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6980: 	    &do_cache_new('courseres',$hashid,$result,600);
 6981: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 6982: 	    return $tmp;
 6983: 	} elsif ($tmp =~ /^(error)/) {
 6984: 	    $result=undef;
 6985: 	    &do_cache_new('courseres',$hashid,$result,600);
 6986: 	}
 6987:     }
 6988:     return $result;
 6989: }
 6990: 
 6991: sub devalidateuserresdata {
 6992:     my ($uname,$udom)=@_;
 6993:     my $hashid="$udom:$uname";
 6994:     &devalidate_cache_new('userres',$hashid);
 6995: }
 6996: 
 6997: sub get_userresdata {
 6998:     my ($uname,$udom)=@_;
 6999:     #most student don\'t have any data set, check if there is some data
 7000:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 7001: 
 7002:     my $hashid="$udom:$uname";
 7003:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 7004:     if (!defined($cached)) {
 7005: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 7006: 	$result=\%resourcedata;
 7007: 	&do_cache_new('userres',$hashid,$result,600);
 7008:     }
 7009:     my ($tmp)=keys(%$result);
 7010:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 7011: 	return $result;
 7012:     }
 7013:     #error 2 occurs when the .db doesn't exist
 7014:     if ($tmp!~/error: 2 /) {
 7015: 	&logthis("<font color=\"blue\">WARNING:".
 7016: 		 " Trying to get resource data for ".
 7017: 		 $uname." at ".$udom.": ".
 7018: 		 $tmp."</font>");
 7019:     } elsif ($tmp=~/error: 2 /) {
 7020: 	#&EXT_cache_set($udom,$uname);
 7021: 	&do_cache_new('userres',$hashid,undef,600);
 7022: 	undef($tmp); # not really an error so don't send it back
 7023:     }
 7024:     return $tmp;
 7025: }
 7026: #----------------------------------------------- resdata - return resource data
 7027: #  Purpose:
 7028: #    Return resource data for either users or for a course.
 7029: #  Parameters:
 7030: #     $name      - Course/user name.
 7031: #     $domain    - Name of the domain the user/course is registered on.
 7032: #     $type      - Type of thing $name is (must be 'course' or 'user'
 7033: #     @which     - Array of names of resources desired.
 7034: #  Returns:
 7035: #     The value of the first reasource in @which that is found in the
 7036: #     resource hash.
 7037: #  Exceptional Conditions:
 7038: #     If the $type passed in is not valid (not the string 'course' or 
 7039: #     'user', an undefined  reference is returned.
 7040: #     If none of the resources are found, an undef is returned
 7041: sub resdata {
 7042:     my ($name,$domain,$type,@which)=@_;
 7043:     my $result;
 7044:     if ($type eq 'course') {
 7045: 	$result=&get_courseresdata($name,$domain);
 7046:     } elsif ($type eq 'user') {
 7047: 	$result=&get_userresdata($name,$domain);
 7048:     }
 7049:     if (!ref($result)) { return $result; }    
 7050:     foreach my $item (@which) {
 7051: 	if (defined($result->{$item->[0]})) {
 7052: 	    return [$result->{$item->[0]},$item->[1]];
 7053: 	}
 7054:     }
 7055:     return undef;
 7056: }
 7057: 
 7058: #
 7059: # EXT resource caching routines
 7060: #
 7061: 
 7062: sub clear_EXT_cache_status {
 7063:     &delenv('cache.EXT.');
 7064: }
 7065: 
 7066: sub EXT_cache_status {
 7067:     my ($target_domain,$target_user) = @_;
 7068:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7069:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 7070:         # We know already the user has no data
 7071:         return 1;
 7072:     } else {
 7073:         return 0;
 7074:     }
 7075: }
 7076: 
 7077: sub EXT_cache_set {
 7078:     my ($target_domain,$target_user) = @_;
 7079:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7080:     #&appenv({$cachename => time});
 7081: }
 7082: 
 7083: # --------------------------------------------------------- Value of a Variable
 7084: sub EXT {
 7085: 
 7086:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 7087:     unless ($varname) { return ''; }
 7088:     #get real user name/domain, courseid and symb
 7089:     my $courseid;
 7090:     my $publicuser;
 7091:     if ($symbparm) {
 7092: 	$symbparm=&get_symb_from_alias($symbparm);
 7093:     }
 7094:     if (!($uname && $udom)) {
 7095:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 7096:       if (!$symbparm) {	$symbparm=$cursymb; }
 7097:     } else {
 7098: 	$courseid=$env{'request.course.id'};
 7099:     }
 7100:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 7101:     my $rest;
 7102:     if (defined($therest[0])) {
 7103:        $rest=join('.',@therest);
 7104:     } else {
 7105:        $rest='';
 7106:     }
 7107: 
 7108:     my $qualifierrest=$qualifier;
 7109:     if ($rest) { $qualifierrest.='.'.$rest; }
 7110:     my $spacequalifierrest=$space;
 7111:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 7112:     if ($realm eq 'user') {
 7113: # --------------------------------------------------------------- user.resource
 7114: 	if ($space eq 'resource') {
 7115: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 7116: 		  || defined($Apache::lonhomework::parsing_a_task))
 7117: 		 &&
 7118: 		 ($symbparm eq &symbread()) ) {	
 7119: 		# if we are in the middle of processing the resource the
 7120: 		# get the value we are planning on committing
 7121:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 7122:                     return $Apache::lonhomework::results{$qualifierrest};
 7123:                 } else {
 7124:                     return $Apache::lonhomework::history{$qualifierrest};
 7125:                 }
 7126: 	    } else {
 7127: 		my %restored;
 7128: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 7129: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 7130: 		} else {
 7131: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 7132: 		}
 7133: 		return $restored{$qualifierrest};
 7134: 	    }
 7135: # ----------------------------------------------------------------- user.access
 7136:         } elsif ($space eq 'access') {
 7137: 	    # FIXME - not supporting calls for a specific user
 7138:             return &allowed($qualifier,$rest);
 7139: # ------------------------------------------ user.preferences, user.environment
 7140:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 7141: 	    if (($uname eq $env{'user.name'}) &&
 7142: 		($udom eq $env{'user.domain'})) {
 7143: 		return $env{join('.',('environment',$qualifierrest))};
 7144: 	    } else {
 7145: 		my %returnhash;
 7146: 		if (!$publicuser) {
 7147: 		    %returnhash=&userenvironment($udom,$uname,
 7148: 						 $qualifierrest);
 7149: 		}
 7150: 		return $returnhash{$qualifierrest};
 7151: 	    }
 7152: # ----------------------------------------------------------------- user.course
 7153:         } elsif ($space eq 'course') {
 7154: 	    # FIXME - not supporting calls for a specific user
 7155:             return $env{join('.',('request.course',$qualifier))};
 7156: # ------------------------------------------------------------------- user.role
 7157:         } elsif ($space eq 'role') {
 7158: 	    # FIXME - not supporting calls for a specific user
 7159:             my ($role,$where)=split(/\./,$env{'request.role'});
 7160:             if ($qualifier eq 'value') {
 7161: 		return $role;
 7162:             } elsif ($qualifier eq 'extent') {
 7163:                 return $where;
 7164:             }
 7165: # ----------------------------------------------------------------- user.domain
 7166:         } elsif ($space eq 'domain') {
 7167:             return $udom;
 7168: # ------------------------------------------------------------------- user.name
 7169:         } elsif ($space eq 'name') {
 7170:             return $uname;
 7171: # ---------------------------------------------------- Any other user namespace
 7172:         } else {
 7173: 	    my %reply;
 7174: 	    if (!$publicuser) {
 7175: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 7176: 	    }
 7177: 	    return $reply{$qualifierrest};
 7178:         }
 7179:     } elsif ($realm eq 'query') {
 7180: # ---------------------------------------------- pull stuff out of query string
 7181:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 7182: 						[$spacequalifierrest]);
 7183: 	return $env{'form.'.$spacequalifierrest}; 
 7184:    } elsif ($realm eq 'request') {
 7185: # ------------------------------------------------------------- request.browser
 7186:         if ($space eq 'browser') {
 7187: 	    if ($qualifier eq 'textremote') {
 7188: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 7189: 		    return 1;
 7190: 		} else {
 7191: 		    return 0;
 7192: 		}
 7193: 	    } else {
 7194: 		return $env{'browser.'.$qualifier};
 7195: 	    }
 7196: # ------------------------------------------------------------ request.filename
 7197:         } else {
 7198:             return $env{'request.'.$spacequalifierrest};
 7199:         }
 7200:     } elsif ($realm eq 'course') {
 7201: # ---------------------------------------------------------- course.description
 7202:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 7203:     } elsif ($realm eq 'resource') {
 7204: 
 7205: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 7206: 	    if (!$symbparm) { $symbparm=&symbread(); }
 7207: 	}
 7208: 
 7209: 	if ($space eq 'title') {
 7210: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 7211: 	    return &gettitle($symbparm);
 7212: 	}
 7213: 	
 7214: 	if ($space eq 'map') {
 7215: 	    my ($map) = &decode_symb($symbparm);
 7216: 	    return &symbread($map);
 7217: 	}
 7218: 	if ($space eq 'filename') {
 7219: 	    if ($symbparm) {
 7220: 		return &clutter((&decode_symb($symbparm))[2]);
 7221: 	    }
 7222: 	    return &hreflocation('',$env{'request.filename'});
 7223: 	}
 7224: 
 7225: 	my ($section, $group, @groups);
 7226: 	my ($courselevelm,$courselevel);
 7227: 	if ($symbparm && defined($courseid) && 
 7228: 	    $courseid eq $env{'request.course.id'}) {
 7229: 
 7230: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 7231: 
 7232: # ----------------------------------------------------- Cascading lookup scheme
 7233: 	    my $symbp=$symbparm;
 7234: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 7235: 
 7236: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 7237: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 7238: 
 7239: 	    if (($env{'user.name'} eq $uname) &&
 7240: 		($env{'user.domain'} eq $udom)) {
 7241: 		$section=$env{'request.course.sec'};
 7242:                 @groups = split(/:/,$env{'request.course.groups'});  
 7243:                 @groups=&sort_course_groups($courseid,@groups); 
 7244: 	    } else {
 7245: 		if (! defined($usection)) {
 7246: 		    $section=&getsection($udom,$uname,$courseid);
 7247: 		} else {
 7248: 		    $section = $usection;
 7249: 		}
 7250:                 @groups = &get_users_groups($udom,$uname,$courseid);
 7251: 	    }
 7252: 
 7253: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 7254: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 7255: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 7256: 
 7257: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 7258: 	    my $courselevelr=$courseid.'.'.$symbparm;
 7259: 	    $courselevelm=$courseid.'.'.$mapparm;
 7260: 
 7261: # ----------------------------------------------------------- first, check user
 7262: 
 7263: 	    my $userreply=&resdata($uname,$udom,'user',
 7264: 				       ([$courselevelr,'resource'],
 7265: 					[$courselevelm,'map'     ],
 7266: 					[$courselevel, 'course'  ]));
 7267: 	    if (defined($userreply)) { return &get_reply($userreply); }
 7268: 
 7269: # ------------------------------------------------ second, check some of course
 7270:             my $coursereply;
 7271:             if (@groups > 0) {
 7272:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 7273:                                        $mapparm,$spacequalifierrest);
 7274:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 7275:             }
 7276: 
 7277: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7278: 				  $env{'course.'.$courseid.'.domain'},
 7279: 				  'course',
 7280: 				  ([$seclevelr,   'resource'],
 7281: 				   [$seclevelm,   'map'     ],
 7282: 				   [$seclevel,    'course'  ],
 7283: 				   [$courselevelr,'resource']));
 7284: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7285: 
 7286: # ------------------------------------------------------ third, check map parms
 7287: 	    my %parmhash=();
 7288: 	    my $thisparm='';
 7289: 	    if (tie(%parmhash,'GDBM_File',
 7290: 		    $env{'request.course.fn'}.'_parms.db',
 7291: 		    &GDBM_READER(),0640)) {
 7292: 		$thisparm=$parmhash{$symbparm};
 7293: 		untie(%parmhash);
 7294: 	    }
 7295: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 7296: 	}
 7297: # ------------------------------------------ fourth, look in resource metadata
 7298: 
 7299: 	$spacequalifierrest=~s/\./\_/;
 7300: 	my $filename;
 7301: 	if (!$symbparm) { $symbparm=&symbread(); }
 7302: 	if ($symbparm) {
 7303: 	    $filename=(&decode_symb($symbparm))[2];
 7304: 	} else {
 7305: 	    $filename=$env{'request.filename'};
 7306: 	}
 7307: 	my $metadata=&metadata($filename,$spacequalifierrest);
 7308: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7309: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 7310: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7311: 
 7312: # ---------------------------------------------- fourth, look in rest of course
 7313: 	if ($symbparm && defined($courseid) && 
 7314: 	    $courseid eq $env{'request.course.id'}) {
 7315: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7316: 				     $env{'course.'.$courseid.'.domain'},
 7317: 				     'course',
 7318: 				     ([$courselevelm,'map'   ],
 7319: 				      [$courselevel, 'course']));
 7320: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7321: 	}
 7322: # ------------------------------------------------------------------ Cascade up
 7323: 	unless ($space eq '0') {
 7324: 	    my @parts=split(/_/,$space);
 7325: 	    my $id=pop(@parts);
 7326: 	    my $part=join('_',@parts);
 7327: 	    if ($part eq '') { $part='0'; }
 7328: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 7329: 				 $symbparm,$udom,$uname,$section,1);
 7330: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 7331: 	}
 7332: 	if ($recurse) { return undef; }
 7333: 	my $pack_def=&packages_tab_default($filename,$varname);
 7334: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 7335: # ---------------------------------------------------- Any other user namespace
 7336:     } elsif ($realm eq 'environment') {
 7337: # ----------------------------------------------------------------- environment
 7338: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 7339: 	    return $env{'environment.'.$spacequalifierrest};
 7340: 	} else {
 7341: 	    if ($uname eq 'anonymous' && $udom eq '') {
 7342: 		return '';
 7343: 	    }
 7344: 	    my %returnhash=&userenvironment($udom,$uname,
 7345: 					    $spacequalifierrest);
 7346: 	    return $returnhash{$spacequalifierrest};
 7347: 	}
 7348:     } elsif ($realm eq 'system') {
 7349: # ----------------------------------------------------------------- system.time
 7350: 	if ($space eq 'time') {
 7351: 	    return time;
 7352:         }
 7353:     } elsif ($realm eq 'server') {
 7354: # ----------------------------------------------------------------- system.time
 7355: 	if ($space eq 'name') {
 7356: 	    return $ENV{'SERVER_NAME'};
 7357:         }
 7358:     }
 7359:     return '';
 7360: }
 7361: 
 7362: sub get_reply {
 7363:     my ($reply_value) = @_;
 7364:     if (ref($reply_value) eq 'ARRAY') {
 7365:         if (wantarray) {
 7366: 	    return @$reply_value;
 7367:         }
 7368:         return $reply_value->[0];
 7369:     } else {
 7370:         return $reply_value;
 7371:     }
 7372: }
 7373: 
 7374: sub check_group_parms {
 7375:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 7376:     my @groupitems = ();
 7377:     my $resultitem;
 7378:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 7379:     foreach my $group (@{$groups}) {
 7380:         foreach my $level (@levels) {
 7381:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 7382:              push(@groupitems,[$item,$level->[1]]);
 7383:         }
 7384:     }
 7385:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 7386:                             $env{'course.'.$courseid.'.domain'},
 7387:                                      'course',@groupitems);
 7388:     return $coursereply;
 7389: }
 7390: 
 7391: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 7392:     my ($courseid,@groups) = @_;
 7393:     @groups = sort(@groups);
 7394:     return @groups;
 7395: }
 7396: 
 7397: sub packages_tab_default {
 7398:     my ($uri,$varname)=@_;
 7399:     my (undef,$part,$name)=split(/\./,$varname);
 7400: 
 7401:     my (@extension,@specifics,$do_default);
 7402:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 7403: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 7404: 	if ($pack_type eq 'default') {
 7405: 	    $do_default=1;
 7406: 	} elsif ($pack_type eq 'extension') {
 7407: 	    push(@extension,[$package,$pack_type,$pack_part]);
 7408: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 7409: 	    # only look at packages defaults for packages that this id is
 7410: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 7411: 	}
 7412:     }
 7413:     # first look for a package that matches the requested part id
 7414:     foreach my $package (@specifics) {
 7415: 	my (undef,$pack_type,$pack_part)=@{$package};
 7416: 	next if ($pack_part ne $part);
 7417: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7418: 	    return $packagetab{"$pack_type&$name&default"};
 7419: 	}
 7420:     }
 7421:     # look for any possible matching non extension_ package
 7422:     foreach my $package (@specifics) {
 7423: 	my (undef,$pack_type,$pack_part)=@{$package};
 7424: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7425: 	    return $packagetab{"$pack_type&$name&default"};
 7426: 	}
 7427: 	if ($pack_type eq 'part') { $pack_part='0'; }
 7428: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 7429: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 7430: 	}
 7431:     }
 7432:     # look for any posible extension_ match
 7433:     foreach my $package (@extension) {
 7434: 	my ($package,$pack_type)=@{$package};
 7435: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7436: 	    return $packagetab{"$pack_type&$name&default"};
 7437: 	}
 7438: 	if (defined($packagetab{$package."&$name&default"})) {
 7439: 	    return $packagetab{$package."&$name&default"};
 7440: 	}
 7441:     }
 7442:     # look for a global default setting
 7443:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 7444: 	return $packagetab{"default&$name&default"};
 7445:     }
 7446:     return undef;
 7447: }
 7448: 
 7449: sub add_prefix_and_part {
 7450:     my ($prefix,$part)=@_;
 7451:     my $keyroot;
 7452:     if (defined($prefix) && $prefix !~ /^__/) {
 7453: 	# prefix that has a part already
 7454: 	$keyroot=$prefix;
 7455:     } elsif (defined($prefix)) {
 7456: 	# prefix that is missing a part
 7457: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 7458:     } else {
 7459: 	# no prefix at all
 7460: 	if (defined($part)) { $keyroot='_'.$part; }
 7461:     }
 7462:     return $keyroot;
 7463: }
 7464: 
 7465: # ---------------------------------------------------------------- Get metadata
 7466: 
 7467: my %metaentry;
 7468: sub metadata {
 7469:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 7470:     $uri=&declutter($uri);
 7471:     # if it is a non metadata possible uri return quickly
 7472:     if (($uri eq '') || 
 7473: 	(($uri =~ m|^/*adm/|) && 
 7474: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 7475:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 7476: 	return undef;
 7477:     }
 7478:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 7479: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 7480: 	return undef;
 7481:     }
 7482:     my $filename=$uri;
 7483:     $uri=~s/\.meta$//;
 7484: #
 7485: # Is the metadata already cached?
 7486: # Look at timestamp of caching
 7487: # Everything is cached by the main uri, libraries are never directly cached
 7488: #
 7489:     if (!defined($liburi)) {
 7490: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 7491: 	if (defined($cached)) { return $result->{':'.$what}; }
 7492:     }
 7493:     {
 7494: #
 7495: # Is this a recursive call for a library?
 7496: #
 7497: #	if (! exists($metacache{$uri})) {
 7498: #	    $metacache{$uri}={};
 7499: #	}
 7500: 	my $cachetime = 60*60;
 7501:         if ($liburi) {
 7502: 	    $liburi=&declutter($liburi);
 7503:             $filename=$liburi;
 7504:         } else {
 7505: 	    &devalidate_cache_new('meta',$uri);
 7506: 	    undef(%metaentry);
 7507: 	}
 7508:         my %metathesekeys=();
 7509:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 7510: 	my $metastring;
 7511: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 7512: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 7513: 	    $metastring = 
 7514: 		&Apache::lonnet::ssi_body($which,
 7515: 					  ('grade_target' => 'meta'));
 7516: 	    $cachetime = 1; # only want this cached in the child not long term
 7517: 	} elsif ($uri !~ m -^(editupload)/-) {
 7518: 	    my $file=&filelocation('',&clutter($filename));
 7519: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 7520: 	    $metastring=&getfile($file);
 7521: 	}
 7522:         my $parser=HTML::LCParser->new(\$metastring);
 7523:         my $token;
 7524:         undef %metathesekeys;
 7525:         while ($token=$parser->get_token) {
 7526: 	    if ($token->[0] eq 'S') {
 7527: 		if (defined($token->[2]->{'package'})) {
 7528: #
 7529: # This is a package - get package info
 7530: #
 7531: 		    my $package=$token->[2]->{'package'};
 7532: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7533: 		    if (defined($token->[2]->{'id'})) { 
 7534: 			$keyroot.='_'.$token->[2]->{'id'}; 
 7535: 		    }
 7536: 		    if ($metaentry{':packages'}) {
 7537: 			$metaentry{':packages'}.=','.$package.$keyroot;
 7538: 		    } else {
 7539: 			$metaentry{':packages'}=$package.$keyroot;
 7540: 		    }
 7541: 		    foreach my $pack_entry (keys(%packagetab)) {
 7542: 			my $part=$keyroot;
 7543: 			$part=~s/^\_//;
 7544: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 7545: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 7546: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 7547: 			    # ignore package.tab specified default values
 7548:                             # here &package_tab_default() will fetch those
 7549: 			    if ($subp eq 'default') { next; }
 7550: 			    my $value=$packagetab{$pack_entry};
 7551: 			    my $unikey;
 7552: 			    if ($pack =~ /_0$/) {
 7553: 				$unikey='parameter_0_'.$name;
 7554: 				$part=0;
 7555: 			    } else {
 7556: 				$unikey='parameter'.$keyroot.'_'.$name;
 7557: 			    }
 7558: 			    if ($subp eq 'display') {
 7559: 				$value.=' [Part: '.$part.']';
 7560: 			    }
 7561: 			    $metaentry{':'.$unikey.'.part'}=$part;
 7562: 			    $metathesekeys{$unikey}=1;
 7563: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7564: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 7565: 			    }
 7566: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 7567: 				$metaentry{':'.$unikey}=
 7568: 				    $metaentry{':'.$unikey.'.default'};
 7569: 			    }
 7570: 			}
 7571: 		    }
 7572: 		} else {
 7573: #
 7574: # This is not a package - some other kind of start tag
 7575: #
 7576: 		    my $entry=$token->[1];
 7577: 		    my $unikey;
 7578: 		    if ($entry eq 'import') {
 7579: 			$unikey='';
 7580: 		    } else {
 7581: 			$unikey=$entry;
 7582: 		    }
 7583: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7584: 
 7585: 		    if (defined($token->[2]->{'id'})) { 
 7586: 			$unikey.='_'.$token->[2]->{'id'}; 
 7587: 		    }
 7588: 
 7589: 		    if ($entry eq 'import') {
 7590: #
 7591: # Importing a library here
 7592: #
 7593: 			if ($depthcount<20) {
 7594: 			    my $location=$parser->get_text('/import');
 7595: 			    my $dir=$filename;
 7596: 			    $dir=~s|[^/]*$||;
 7597: 			    $location=&filelocation($dir,$location);
 7598: 			    my $metadata = 
 7599: 				&metadata($uri,'keys', $location,$unikey,
 7600: 					  $depthcount+1);
 7601: 			    foreach my $meta (split(',',$metadata)) {
 7602: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 7603: 				$metathesekeys{$meta}=1;
 7604: 			    }
 7605: 			}
 7606: 		    } else { 
 7607: 			
 7608: 			if (defined($token->[2]->{'name'})) { 
 7609: 			    $unikey.='_'.$token->[2]->{'name'}; 
 7610: 			}
 7611: 			$metathesekeys{$unikey}=1;
 7612: 			foreach my $param (@{$token->[3]}) {
 7613: 			    $metaentry{':'.$unikey.'.'.$param} =
 7614: 				$token->[2]->{$param};
 7615: 			}
 7616: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 7617: 			my $default=$metaentry{':'.$unikey.'.default'};
 7618: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 7619: 		 # only ws inside the tag, and not in default, so use default
 7620: 		 # as value
 7621: 			    $metaentry{':'.$unikey}=$default;
 7622: 			} elsif ( $internaltext =~ /\S/ ) {
 7623: 		  # something interesting inside the tag
 7624: 			    $metaentry{':'.$unikey}=$internaltext;
 7625: 			} else {
 7626: 		  # no interesting values, don't set a default
 7627: 			}
 7628: # end of not-a-package not-a-library import
 7629: 		    }
 7630: # end of not-a-package start tag
 7631: 		}
 7632: # the next is the end of "start tag"
 7633: 	    }
 7634: 	}
 7635: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 7636: 	$extension = lc($extension);
 7637: 	if ($extension eq 'htm') { $extension='html'; }
 7638: 
 7639: 	foreach my $key (keys(%packagetab)) {
 7640: 	    #no specific packages #how's our extension
 7641: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 7642: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 7643: 					 \%metathesekeys);
 7644: 	}
 7645: 
 7646: 	if (!exists($metaentry{':packages'})
 7647: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 7648: 	    foreach my $key (keys(%packagetab)) {
 7649: 		#no specific packages well let's get default then
 7650: 		if ($key!~/^default&/) { next; }
 7651: 		&metadata_create_package_def($uri,$key,'default',
 7652: 					     \%metathesekeys);
 7653: 	    }
 7654: 	}
 7655: # are there custom rights to evaluate
 7656: 	if ($metaentry{':copyright'} eq 'custom') {
 7657: 
 7658:     #
 7659:     # Importing a rights file here
 7660:     #
 7661: 	    unless ($depthcount) {
 7662: 		my $location=$metaentry{':customdistributionfile'};
 7663: 		my $dir=$filename;
 7664: 		$dir=~s|[^/]*$||;
 7665: 		$location=&filelocation($dir,$location);
 7666: 		my $rights_metadata =
 7667: 		    &metadata($uri,'keys',$location,'_rights',
 7668: 			      $depthcount+1);
 7669: 		foreach my $rights (split(',',$rights_metadata)) {
 7670: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 7671: 		    $metathesekeys{$rights}=1;
 7672: 		}
 7673: 	    }
 7674: 	}
 7675: 	# uniqifiy package listing
 7676: 	my %seen;
 7677: 	my @uniq_packages =
 7678: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 7679: 	$metaentry{':packages'} = join(',',@uniq_packages);
 7680: 
 7681: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 7682: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 7683: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 7684: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 7685: # this is the end of "was not already recently cached
 7686:     }
 7687:     return $metaentry{':'.$what};
 7688: }
 7689: 
 7690: sub metadata_create_package_def {
 7691:     my ($uri,$key,$package,$metathesekeys)=@_;
 7692:     my ($pack,$name,$subp)=split(/\&/,$key);
 7693:     if ($subp eq 'default') { next; }
 7694:     
 7695:     if (defined($metaentry{':packages'})) {
 7696: 	$metaentry{':packages'}.=','.$package;
 7697:     } else {
 7698: 	$metaentry{':packages'}=$package;
 7699:     }
 7700:     my $value=$packagetab{$key};
 7701:     my $unikey;
 7702:     $unikey='parameter_0_'.$name;
 7703:     $metaentry{':'.$unikey.'.part'}=0;
 7704:     $$metathesekeys{$unikey}=1;
 7705:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7706: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 7707:     }
 7708:     if (defined($metaentry{':'.$unikey.'.default'})) {
 7709: 	$metaentry{':'.$unikey}=
 7710: 	    $metaentry{':'.$unikey.'.default'};
 7711:     }
 7712: }
 7713: 
 7714: sub metadata_generate_part0 {
 7715:     my ($metadata,$metacache,$uri) = @_;
 7716:     my %allnames;
 7717:     foreach my $metakey (keys(%$metadata)) {
 7718: 	if ($metakey=~/^parameter\_(.*)/) {
 7719: 	  my $part=$$metacache{':'.$metakey.'.part'};
 7720: 	  my $name=$$metacache{':'.$metakey.'.name'};
 7721: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 7722: 	    $allnames{$name}=$part;
 7723: 	  }
 7724: 	}
 7725:     }
 7726:     foreach my $name (keys(%allnames)) {
 7727:       $$metadata{"parameter_0_$name"}=1;
 7728:       my $key=":parameter_0_$name";
 7729:       $$metacache{"$key.part"}='0';
 7730:       $$metacache{"$key.name"}=$name;
 7731:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 7732: 					   $allnames{$name}.'_'.$name.
 7733: 					   '.type'};
 7734:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 7735: 			     '.display'};
 7736:       my $expr='[Part: '.$allnames{$name}.']';
 7737:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 7738:       $$metacache{"$key.display"}=$olddis;
 7739:     }
 7740: }
 7741: 
 7742: # ------------------------------------------------------ Devalidate title cache
 7743: 
 7744: sub devalidate_title_cache {
 7745:     my ($url)=@_;
 7746:     if (!$env{'request.course.id'}) { return; }
 7747:     my $symb=&symbread($url);
 7748:     if (!$symb) { return; }
 7749:     my $key=$env{'request.course.id'}."\0".$symb;
 7750:     &devalidate_cache_new('title',$key);
 7751: }
 7752: 
 7753: # ------------------------------------------------- Get the title of a resource
 7754: 
 7755: sub gettitle {
 7756:     my $urlsymb=shift;
 7757:     my $symb=&symbread($urlsymb);
 7758:     if ($symb) {
 7759: 	my $key=$env{'request.course.id'}."\0".$symb;
 7760: 	my ($result,$cached)=&is_cached_new('title',$key);
 7761: 	if (defined($cached)) { 
 7762: 	    return $result;
 7763: 	}
 7764: 	my ($map,$resid,$url)=&decode_symb($symb);
 7765: 	my $title='';
 7766: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 7767: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 7768: 	} else {
 7769: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7770: 		    &GDBM_READER(),0640)) {
 7771: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 7772: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 7773: 		untie(%bighash);
 7774: 	    }
 7775: 	}
 7776: 	$title=~s/\&colon\;/\:/gs;
 7777: 	if ($title) {
 7778: 	    return &do_cache_new('title',$key,$title,600);
 7779: 	}
 7780: 	$urlsymb=$url;
 7781:     }
 7782:     my $title=&metadata($urlsymb,'title');
 7783:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 7784:     return $title;
 7785: }
 7786: 
 7787: sub get_slot {
 7788:     my ($which,$cnum,$cdom)=@_;
 7789:     if (!$cnum || !$cdom) {
 7790: 	(undef,my $courseid)=&whichuser();
 7791: 	$cdom=$env{'course.'.$courseid.'.domain'};
 7792: 	$cnum=$env{'course.'.$courseid.'.num'};
 7793:     }
 7794:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 7795:     my %slotinfo;
 7796:     if (exists($remembered{$key})) {
 7797: 	$slotinfo{$which} = $remembered{$key};
 7798:     } else {
 7799: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 7800: 	&Apache::lonhomework::showhash(%slotinfo);
 7801: 	my ($tmp)=keys(%slotinfo);
 7802: 	if ($tmp=~/^error:/) { return (); }
 7803: 	$remembered{$key} = $slotinfo{$which};
 7804:     }
 7805:     if (ref($slotinfo{$which}) eq 'HASH') {
 7806: 	return %{$slotinfo{$which}};
 7807:     }
 7808:     return $slotinfo{$which};
 7809: }
 7810: # ------------------------------------------------- Update symbolic store links
 7811: 
 7812: sub symblist {
 7813:     my ($mapname,%newhash)=@_;
 7814:     $mapname=&deversion(&declutter($mapname));
 7815:     my %hash;
 7816:     if (($env{'request.course.fn'}) && (%newhash)) {
 7817:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7818:                       &GDBM_WRCREAT(),0640)) {
 7819: 	    foreach my $url (keys %newhash) {
 7820: 		next if ($url eq 'last_known'
 7821: 			 && $env{'form.no_update_last_known'});
 7822: 		$hash{declutter($url)}=&encode_symb($mapname,
 7823: 						    $newhash{$url}->[1],
 7824: 						    $newhash{$url}->[0]);
 7825:             }
 7826:             if (untie(%hash)) {
 7827: 		return 'ok';
 7828:             }
 7829:         }
 7830:     }
 7831:     return 'error';
 7832: }
 7833: 
 7834: # --------------------------------------------------------------- Verify a symb
 7835: 
 7836: sub symbverify {
 7837:     my ($symb,$thisurl)=@_;
 7838:     my $thisfn=$thisurl;
 7839:     $thisfn=&declutter($thisfn);
 7840: # direct jump to resource in page or to a sequence - will construct own symbs
 7841:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 7842: # check URL part
 7843:     my ($map,$resid,$url)=&decode_symb($symb);
 7844: 
 7845:     unless ($url eq $thisfn) { return 0; }
 7846: 
 7847:     $symb=&symbclean($symb);
 7848:     $thisurl=&deversion($thisurl);
 7849:     $thisfn=&deversion($thisfn);
 7850: 
 7851:     my %bighash;
 7852:     my $okay=0;
 7853: 
 7854:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7855:                             &GDBM_READER(),0640)) {
 7856:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 7857:         unless ($ids) { 
 7858:            $ids=$bighash{'ids_/'.$thisurl};
 7859:         }
 7860:         if ($ids) {
 7861: # ------------------------------------------------------------------- Has ID(s)
 7862: 	    foreach my $id (split(/\,/,$ids)) {
 7863: 	       my ($mapid,$resid)=split(/\./,$id);
 7864:                if (
 7865:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 7866:    eq $symb) { 
 7867: 		   if (($env{'request.role.adv'}) ||
 7868: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 7869: 		       $okay=1; 
 7870: 		   }
 7871: 	       }
 7872: 	   }
 7873:         }
 7874: 	untie(%bighash);
 7875:     }
 7876:     return $okay;
 7877: }
 7878: 
 7879: # --------------------------------------------------------------- Clean-up symb
 7880: 
 7881: sub symbclean {
 7882:     my $symb=shift;
 7883:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7884: # remove version from map
 7885:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 7886: 
 7887: # remove version from URL
 7888:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 7889: 
 7890: # remove wrapper
 7891: 
 7892:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 7893:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 7894:     return $symb;
 7895: }
 7896: 
 7897: # ---------------------------------------------- Split symb to find map and url
 7898: 
 7899: sub encode_symb {
 7900:     my ($map,$resid,$url)=@_;
 7901:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 7902: }
 7903: 
 7904: sub decode_symb {
 7905:     my $symb=shift;
 7906:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7907:     my ($map,$resid,$url)=split(/___/,$symb);
 7908:     return (&fixversion($map),$resid,&fixversion($url));
 7909: }
 7910: 
 7911: sub fixversion {
 7912:     my $fn=shift;
 7913:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 7914:     my %bighash;
 7915:     my $uri=&clutter($fn);
 7916:     my $key=$env{'request.course.id'}.'_'.$uri;
 7917: # is this cached?
 7918:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 7919:     if (defined($cached)) { return $result; }
 7920: # unfortunately not cached, or expired
 7921:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7922: 	    &GDBM_READER(),0640)) {
 7923:  	if ($bighash{'version_'.$uri}) {
 7924:  	    my $version=$bighash{'version_'.$uri};
 7925:  	    unless (($version eq 'mostrecent') || 
 7926: 		    ($version==&getversion($uri))) {
 7927:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 7928:  	    }
 7929:  	}
 7930:  	untie %bighash;
 7931:     }
 7932:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 7933: }
 7934: 
 7935: sub deversion {
 7936:     my $url=shift;
 7937:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 7938:     return $url;
 7939: }
 7940: 
 7941: # ------------------------------------------------------ Return symb list entry
 7942: 
 7943: sub symbread {
 7944:     my ($thisfn,$donotrecurse)=@_;
 7945:     my $cache_str='request.symbread.cached.'.$thisfn;
 7946:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 7947: # no filename provided? try from environment
 7948:     unless ($thisfn) {
 7949:         if ($env{'request.symb'}) {
 7950: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 7951: 	}
 7952: 	$thisfn=$env{'request.filename'};
 7953:     }
 7954:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7955: # is that filename actually a symb? Verify, clean, and return
 7956:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 7957: 	if (&symbverify($thisfn,$1)) {
 7958: 	    return $env{$cache_str}=&symbclean($thisfn);
 7959: 	}
 7960:     }
 7961:     $thisfn=declutter($thisfn);
 7962:     my %hash;
 7963:     my %bighash;
 7964:     my $syval='';
 7965:     if (($env{'request.course.fn'}) && ($thisfn)) {
 7966:         my $targetfn = $thisfn;
 7967:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 7968:             $targetfn = 'adm/wrapper/'.$thisfn;
 7969:         }
 7970: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 7971: 	    $targetfn=$1;
 7972: 	}
 7973:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7974:                       &GDBM_READER(),0640)) {
 7975: 	    $syval=$hash{$targetfn};
 7976:             untie(%hash);
 7977:         }
 7978: # ---------------------------------------------------------- There was an entry
 7979:         if ($syval) {
 7980: 	    #unless ($syval=~/\_\d+$/) {
 7981: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 7982: 		    #&appenv({'request.ambiguous' => $thisfn});
 7983: 		    #return $env{$cache_str}='';
 7984: 		#}    
 7985: 		#$syval.=$1;
 7986: 	    #}
 7987:         } else {
 7988: # ------------------------------------------------------- Was not in symb table
 7989:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7990:                             &GDBM_READER(),0640)) {
 7991: # ---------------------------------------------- Get ID(s) for current resource
 7992:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 7993:               unless ($ids) { 
 7994:                  $ids=$bighash{'ids_/'.$thisfn};
 7995:               }
 7996:               unless ($ids) {
 7997: # alias?
 7998: 		  $ids=$bighash{'mapalias_'.$thisfn};
 7999:               }
 8000:               if ($ids) {
 8001: # ------------------------------------------------------------------- Has ID(s)
 8002:                  my @possibilities=split(/\,/,$ids);
 8003:                  if ($#possibilities==0) {
 8004: # ----------------------------------------------- There is only one possibility
 8005: 		     my ($mapid,$resid)=split(/\./,$ids);
 8006: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 8007: 						    $resid,$thisfn);
 8008:                  } elsif (!$donotrecurse) {
 8009: # ------------------------------------------ There is more than one possibility
 8010:                      my $realpossible=0;
 8011:                      foreach my $id (@possibilities) {
 8012: 			 my $file=$bighash{'src_'.$id};
 8013:                          if (&allowed('bre',$file)) {
 8014:          		    my ($mapid,$resid)=split(/\./,$id);
 8015:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 8016: 				$realpossible++;
 8017:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 8018: 						    $resid,$thisfn);
 8019:                             }
 8020: 			 }
 8021:                      }
 8022: 		     if ($realpossible!=1) { $syval=''; }
 8023:                  } else {
 8024:                      $syval='';
 8025:                  }
 8026: 	      }
 8027:               untie(%bighash)
 8028:            }
 8029:         }
 8030:         if ($syval) {
 8031: 	    return $env{$cache_str}=$syval;
 8032:         }
 8033:     }
 8034:     &appenv({'request.ambiguous' => $thisfn});
 8035:     return $env{$cache_str}='';
 8036: }
 8037: 
 8038: # ---------------------------------------------------------- Return random seed
 8039: 
 8040: sub numval {
 8041:     my $txt=shift;
 8042:     $txt=~tr/A-J/0-9/;
 8043:     $txt=~tr/a-j/0-9/;
 8044:     $txt=~tr/K-T/0-9/;
 8045:     $txt=~tr/k-t/0-9/;
 8046:     $txt=~tr/U-Z/0-5/;
 8047:     $txt=~tr/u-z/0-5/;
 8048:     $txt=~s/\D//g;
 8049:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 8050:     return int($txt);
 8051: }
 8052: 
 8053: sub numval2 {
 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) { if ($total > 2**32) { return -1; } }
 8066:     return int($total);
 8067: }
 8068: 
 8069: sub numval3 {
 8070:     use integer;
 8071:     my $txt=shift;
 8072:     $txt=~tr/A-J/0-9/;
 8073:     $txt=~tr/a-j/0-9/;
 8074:     $txt=~tr/K-T/0-9/;
 8075:     $txt=~tr/k-t/0-9/;
 8076:     $txt=~tr/U-Z/0-5/;
 8077:     $txt=~tr/u-z/0-5/;
 8078:     $txt=~s/\D//g;
 8079:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8080:     my $total;
 8081:     foreach my $val (@txts) { $total+=$val; }
 8082:     if ($_64bit) { $total=(($total<<32)>>32); }
 8083:     return $total;
 8084: }
 8085: 
 8086: sub digest {
 8087:     my ($data)=@_;
 8088:     my $digest=&Digest::MD5::md5($data);
 8089:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 8090:     my ($e,$f);
 8091:     {
 8092:         use integer;
 8093:         $e=($a+$b);
 8094:         $f=($c+$d);
 8095:         if ($_64bit) {
 8096:             $e=(($e<<32)>>32);
 8097:             $f=(($f<<32)>>32);
 8098:         }
 8099:     }
 8100:     if (wantarray) {
 8101: 	return ($e,$f);
 8102:     } else {
 8103: 	my $g;
 8104: 	{
 8105: 	    use integer;
 8106: 	    $g=($e+$f);
 8107: 	    if ($_64bit) {
 8108: 		$g=(($g<<32)>>32);
 8109: 	    }
 8110: 	}
 8111: 	return $g;
 8112:     }
 8113: }
 8114: 
 8115: sub latest_rnd_algorithm_id {
 8116:     return '64bit5';
 8117: }
 8118: 
 8119: sub get_rand_alg {
 8120:     my ($courseid)=@_;
 8121:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 8122:     if ($courseid) {
 8123: 	return $env{"course.$courseid.rndseed"};
 8124:     }
 8125:     return &latest_rnd_algorithm_id();
 8126: }
 8127: 
 8128: sub validCODE {
 8129:     my ($CODE)=@_;
 8130:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 8131:     return 0;
 8132: }
 8133: 
 8134: sub getCODE {
 8135:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 8136:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 8137: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 8138: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 8139: 	return $Apache::lonhomework::history{'resource.CODE'};
 8140:     }
 8141:     return undef;
 8142: }
 8143: 
 8144: sub rndseed {
 8145:     my ($symb,$courseid,$domain,$username)=@_;
 8146:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 8147:     if (!defined($symb)) {
 8148: 	unless ($symb=$wsymb) { return time; }
 8149:     }
 8150:     if (!$courseid) { $courseid=$wcourseid; }
 8151:     if (!$domain) { $domain=$wdomain; }
 8152:     if (!$username) { $username=$wusername }
 8153:     my $which=&get_rand_alg();
 8154: 
 8155:     if (defined(&getCODE())) {
 8156: 	if ($which eq '64bit5') {
 8157: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 8158: 	} elsif ($which eq '64bit4') {
 8159: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 8160: 	} else {
 8161: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 8162: 	}
 8163:     } elsif ($which eq '64bit5') {
 8164: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 8165:     } elsif ($which eq '64bit4') {
 8166: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 8167:     } elsif ($which eq '64bit3') {
 8168: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 8169:     } elsif ($which eq '64bit2') {
 8170: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 8171:     } elsif ($which eq '64bit') {
 8172: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 8173:     }
 8174:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 8175: }
 8176: 
 8177: sub rndseed_32bit {
 8178:     my ($symb,$courseid,$domain,$username)=@_;
 8179:     {
 8180: 	use integer;
 8181: 	my $symbchck=unpack("%32C*",$symb) << 27;
 8182: 	my $symbseed=numval($symb) << 22;
 8183: 	my $namechck=unpack("%32C*",$username) << 17;
 8184: 	my $nameseed=numval($username) << 12;
 8185: 	my $domainseed=unpack("%32C*",$domain) << 7;
 8186: 	my $courseseed=unpack("%32C*",$courseid);
 8187: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 8188: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8189: 	#&logthis("rndseed :$num:$symb");
 8190: 	if ($_64bit) { $num=(($num<<32)>>32); }
 8191: 	return $num;
 8192:     }
 8193: }
 8194: 
 8195: sub rndseed_64bit {
 8196:     my ($symb,$courseid,$domain,$username)=@_;
 8197:     {
 8198: 	use integer;
 8199: 	my $symbchck=unpack("%32S*",$symb) << 21;
 8200: 	my $symbseed=numval($symb) << 10;
 8201: 	my $namechck=unpack("%32S*",$username);
 8202: 	
 8203: 	my $nameseed=numval($username) << 21;
 8204: 	my $domainseed=unpack("%32S*",$domain) << 10;
 8205: 	my $courseseed=unpack("%32S*",$courseid);
 8206: 	
 8207: 	my $num1=$symbchck+$symbseed+$namechck;
 8208: 	my $num2=$nameseed+$domainseed+$courseseed;
 8209: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8210: 	#&logthis("rndseed :$num:$symb");
 8211: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8212: 	return "$num1,$num2";
 8213:     }
 8214: }
 8215: 
 8216: sub rndseed_64bit2 {
 8217:     my ($symb,$courseid,$domain,$username)=@_;
 8218:     {
 8219: 	use integer;
 8220: 	# strings need to be an even # of cahracters long, it it is odd the
 8221:         # last characters gets thrown away
 8222: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8223: 	my $symbseed=numval($symb) << 10;
 8224: 	my $namechck=unpack("%32S*",$username.' ');
 8225: 	
 8226: 	my $nameseed=numval($username) << 21;
 8227: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8228: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8229: 	
 8230: 	my $num1=$symbchck+$symbseed+$namechck;
 8231: 	my $num2=$nameseed+$domainseed+$courseseed;
 8232: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8233: 	#&logthis("rndseed :$num:$symb");
 8234: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8235: 	return "$num1,$num2";
 8236:     }
 8237: }
 8238: 
 8239: sub rndseed_64bit3 {
 8240:     my ($symb,$courseid,$domain,$username)=@_;
 8241:     {
 8242: 	use integer;
 8243: 	# strings need to be an even # of cahracters long, it it is odd the
 8244:         # last characters gets thrown away
 8245: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8246: 	my $symbseed=numval2($symb) << 10;
 8247: 	my $namechck=unpack("%32S*",$username.' ');
 8248: 	
 8249: 	my $nameseed=numval2($username) << 21;
 8250: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8251: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8252: 	
 8253: 	my $num1=$symbchck+$symbseed+$namechck;
 8254: 	my $num2=$nameseed+$domainseed+$courseseed;
 8255: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8256: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8257: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8258: 	
 8259: 	return "$num1:$num2";
 8260:     }
 8261: }
 8262: 
 8263: sub rndseed_64bit4 {
 8264:     my ($symb,$courseid,$domain,$username)=@_;
 8265:     {
 8266: 	use integer;
 8267: 	# strings need to be an even # of cahracters long, it it is odd the
 8268:         # last characters gets thrown away
 8269: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8270: 	my $symbseed=numval3($symb) << 10;
 8271: 	my $namechck=unpack("%32S*",$username.' ');
 8272: 	
 8273: 	my $nameseed=numval3($username) << 21;
 8274: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8275: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8276: 	
 8277: 	my $num1=$symbchck+$symbseed+$namechck;
 8278: 	my $num2=$nameseed+$domainseed+$courseseed;
 8279: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8280: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8281: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8282: 	
 8283: 	return "$num1:$num2";
 8284:     }
 8285: }
 8286: 
 8287: sub rndseed_64bit5 {
 8288:     my ($symb,$courseid,$domain,$username)=@_;
 8289:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 8290:     return "$num1:$num2";
 8291: }
 8292: 
 8293: sub rndseed_CODE_64bit {
 8294:     my ($symb,$courseid,$domain,$username)=@_;
 8295:     {
 8296: 	use integer;
 8297: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8298: 	my $symbseed=numval2($symb);
 8299: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8300: 	my $CODEseed=numval(&getCODE());
 8301: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8302: 	my $num1=$symbseed+$CODEchck;
 8303: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8304: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8305: 	#&logthis("rndseed :$num1:$num2:$symb");
 8306: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8307: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8308: 	return "$num1:$num2";
 8309:     }
 8310: }
 8311: 
 8312: sub rndseed_CODE_64bit4 {
 8313:     my ($symb,$courseid,$domain,$username)=@_;
 8314:     {
 8315: 	use integer;
 8316: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8317: 	my $symbseed=numval3($symb);
 8318: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8319: 	my $CODEseed=numval3(&getCODE());
 8320: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8321: 	my $num1=$symbseed+$CODEchck;
 8322: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8323: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8324: 	#&logthis("rndseed :$num1:$num2:$symb");
 8325: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8326: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8327: 	return "$num1:$num2";
 8328:     }
 8329: }
 8330: 
 8331: sub rndseed_CODE_64bit5 {
 8332:     my ($symb,$courseid,$domain,$username)=@_;
 8333:     my $code = &getCODE();
 8334:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 8335:     return "$num1:$num2";
 8336: }
 8337: 
 8338: sub setup_random_from_rndseed {
 8339:     my ($rndseed)=@_;
 8340:     if ($rndseed =~/([,:])/) {
 8341: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 8342: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 8343:     } else {
 8344: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 8345:     }
 8346: }
 8347: 
 8348: sub latest_receipt_algorithm_id {
 8349:     return 'receipt3';
 8350: }
 8351: 
 8352: sub recunique {
 8353:     my $fucourseid=shift;
 8354:     my $unique;
 8355:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 8356: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8357: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 8358:     } else {
 8359: 	$unique=$perlvar{'lonReceipt'};
 8360:     }
 8361:     return unpack("%32C*",$unique);
 8362: }
 8363: 
 8364: sub recprefix {
 8365:     my $fucourseid=shift;
 8366:     my $prefix;
 8367:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 8368: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8369: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 8370:     } else {
 8371: 	$prefix=$perlvar{'lonHostID'};
 8372:     }
 8373:     return unpack("%32C*",$prefix);
 8374: }
 8375: 
 8376: sub ireceipt {
 8377:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 8378: 
 8379:     my $return =&recprefix($fucourseid).'-';
 8380: 
 8381:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 8382: 	$env{'request.state'} eq 'construct') {
 8383: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 8384: 	return $return;
 8385:     }
 8386: 
 8387:     my $cuname=unpack("%32C*",$funame);
 8388:     my $cudom=unpack("%32C*",$fudom);
 8389:     my $cucourseid=unpack("%32C*",$fucourseid);
 8390:     my $cusymb=unpack("%32C*",$fusymb);
 8391:     my $cunique=&recunique($fucourseid);
 8392:     my $cpart=unpack("%32S*",$part);
 8393:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 8394: 
 8395: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 8396: 			       
 8397: 	$return.= ($cunique%$cuname+
 8398: 		   $cunique%$cudom+
 8399: 		   $cusymb%$cuname+
 8400: 		   $cusymb%$cudom+
 8401: 		   $cucourseid%$cuname+
 8402: 		   $cucourseid%$cudom+
 8403: 		   $cpart%$cuname+
 8404: 		   $cpart%$cudom);
 8405:     } else {
 8406: 	$return.= ($cunique%$cuname+
 8407: 		   $cunique%$cudom+
 8408: 		   $cusymb%$cuname+
 8409: 		   $cusymb%$cudom+
 8410: 		   $cucourseid%$cuname+
 8411: 		   $cucourseid%$cudom);
 8412:     }
 8413:     return $return;
 8414: }
 8415: 
 8416: sub receipt {
 8417:     my ($part)=@_;
 8418:     my ($symb,$courseid,$domain,$name) = &whichuser();
 8419:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 8420: }
 8421: 
 8422: sub whichuser {
 8423:     my ($passedsymb)=@_;
 8424:     my ($symb,$courseid,$domain,$name,$publicuser);
 8425:     if (defined($env{'form.grade_symb'})) {
 8426: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 8427: 	my $allowed=&allowed('vgr',$tmp_courseid);
 8428: 	if (!$allowed &&
 8429: 	    exists($env{'request.course.sec'}) &&
 8430: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 8431: 	    $allowed=&allowed('vgr',$tmp_courseid.
 8432: 			      '/'.$env{'request.course.sec'});
 8433: 	}
 8434: 	if ($allowed) {
 8435: 	    ($symb)=&get_env_multiple('form.grade_symb');
 8436: 	    $courseid=$tmp_courseid;
 8437: 	    ($domain)=&get_env_multiple('form.grade_domain');
 8438: 	    ($name)=&get_env_multiple('form.grade_username');
 8439: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 8440: 	}
 8441:     }
 8442:     if (!$passedsymb) {
 8443: 	$symb=&symbread();
 8444:     } else {
 8445: 	$symb=$passedsymb;
 8446:     }
 8447:     $courseid=$env{'request.course.id'};
 8448:     $domain=$env{'user.domain'};
 8449:     $name=$env{'user.name'};
 8450:     if ($name eq 'public' && $domain eq 'public') {
 8451: 	if (!defined($env{'form.username'})) {
 8452: 	    $env{'form.username'}.=time.rand(10000000);
 8453: 	}
 8454: 	$name.=$env{'form.username'};
 8455:     }
 8456:     return ($symb,$courseid,$domain,$name,$publicuser);
 8457: 
 8458: }
 8459: 
 8460: # ------------------------------------------------------------ Serves up a file
 8461: # returns either the contents of the file or 
 8462: # -1 if the file doesn't exist
 8463: #
 8464: # if the target is a file that was uploaded via DOCS, 
 8465: # a check will be made to see if a current copy exists on the local server,
 8466: # if it does this will be served, otherwise a copy will be retrieved from
 8467: # the home server for the course and stored in /home/httpd/html/userfiles on
 8468: # the local server.   
 8469: 
 8470: sub getfile {
 8471:     my ($file) = @_;
 8472:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8473:     &repcopy($file);
 8474:     return &readfile($file);
 8475: }
 8476: 
 8477: sub repcopy_userfile {
 8478:     my ($file)=@_;
 8479:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8480:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 8481:     my ($cdom,$cnum,$filename) = 
 8482: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 8483:     my $uri="/uploaded/$cdom/$cnum/$filename";
 8484:     if (-e "$file") {
 8485: # we already have a local copy, check it out
 8486: 	my @fileinfo = stat($file);
 8487: 	my $rtncode;
 8488: 	my $info;
 8489: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 8490: 	if ($lwpresp ne 'ok') {
 8491: # there is no such file anymore, even though we had a local copy
 8492: 	    if ($rtncode eq '404') {
 8493: 		unlink($file);
 8494: 	    }
 8495: 	    return -1;
 8496: 	}
 8497: 	if ($info < $fileinfo[9]) {
 8498: # nice, the file we have is up-to-date, just say okay
 8499: 	    return 'ok';
 8500: 	} else {
 8501: # the file is outdated, get rid of it
 8502: 	    unlink($file);
 8503: 	}
 8504:     }
 8505: # one way or the other, at this point, we don't have the file
 8506: # construct the correct path for the file
 8507:     my @parts = ($cdom,$cnum); 
 8508:     if ($filename =~ m|^(.+)/[^/]+$|) {
 8509: 	push @parts, split(/\//,$1);
 8510:     }
 8511:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 8512:     foreach my $part (@parts) {
 8513: 	$path .= '/'.$part;
 8514: 	if (!-e $path) {
 8515: 	    mkdir($path,0770);
 8516: 	}
 8517:     }
 8518: # now the path exists for sure
 8519: # get a user agent
 8520:     my $ua=new LWP::UserAgent;
 8521:     my $transferfile=$file.'.in.transfer';
 8522: # FIXME: this should flock
 8523:     if (-e $transferfile) { return 'ok'; }
 8524:     my $request;
 8525:     $uri=~s/^\///;
 8526:     my $homeserver = &homeserver($cnum,$cdom);
 8527:     my $protocol = $protocol{$homeserver};
 8528:     $protocol = 'http' if ($protocol ne 'https');
 8529:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
 8530:     my $response=$ua->request($request,$transferfile);
 8531: # did it work?
 8532:     if ($response->is_error()) {
 8533: 	unlink($transferfile);
 8534: 	&logthis("Userfile repcopy failed for $uri");
 8535: 	return -1;
 8536:     }
 8537: # worked, rename the transfer file
 8538:     rename($transferfile,$file);
 8539:     return 'ok';
 8540: }
 8541: 
 8542: sub tokenwrapper {
 8543:     my $uri=shift;
 8544:     $uri=~s|^https?\://([^/]+)||;
 8545:     $uri=~s|^/||;
 8546:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 8547:     my $token=$1;
 8548:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 8549:     if ($udom && $uname && $file) {
 8550: 	$file=~s|(\?\.*)*$||;
 8551:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 8552:         my $homeserver = &homeserver($uname,$udom);
 8553:         my $protocol = $protocol{$homeserver};
 8554:         $protocol = 'http' if ($protocol ne 'https');
 8555:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
 8556:                (($uri=~/\?/)?'&':'?').'token='.$token.
 8557:                                '&tokenissued='.$perlvar{'lonHostID'};
 8558:     } else {
 8559:         return '/adm/notfound.html';
 8560:     }
 8561: }
 8562: 
 8563: # call with reqtype HEAD: get last modification time
 8564: # call with reqtype GET: get the file contents
 8565: # Do not call this with reqtype GET for large files! It loads everything into memory
 8566: #
 8567: sub getuploaded {
 8568:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 8569:     $uri=~s/^\///;
 8570:     my $homeserver = &homeserver($cnum,$cdom);
 8571:     my $protocol = $protocol{$homeserver};
 8572:     $protocol = 'http' if ($protocol ne 'https');
 8573:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
 8574:     my $ua=new LWP::UserAgent;
 8575:     my $request=new HTTP::Request($reqtype,$uri);
 8576:     my $response=$ua->request($request);
 8577:     $$rtncode = $response->code;
 8578:     if (! $response->is_success()) {
 8579: 	return 'failed';
 8580:     }      
 8581:     if ($reqtype eq 'HEAD') {
 8582: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 8583:     } elsif ($reqtype eq 'GET') {
 8584: 	$$info = $response->content;
 8585:     }
 8586:     return 'ok';
 8587: }
 8588: 
 8589: sub readfile {
 8590:     my $file = shift;
 8591:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 8592:     my $fh;
 8593:     open($fh,"<$file");
 8594:     my $a='';
 8595:     while (my $line = <$fh>) { $a .= $line; }
 8596:     return $a;
 8597: }
 8598: 
 8599: sub filelocation {
 8600:     my ($dir,$file) = @_;
 8601:     my $location;
 8602:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 8603: 
 8604:     if ($file =~ m-^/adm/-) {
 8605: 	$file=~s-^/adm/wrapper/-/-;
 8606: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8607:     }
 8608: 
 8609:     if ($file=~m:^/~:) { # is a contruction space reference
 8610:         $location = $file;
 8611:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 8612:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 8613: 	# is a correct contruction space reference
 8614:         $location = $file;
 8615:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
 8616:         $location = $file;
 8617:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 8618:         my ($udom,$uname,$filename)=
 8619:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 8620:         my $home=&homeserver($uname,$udom);
 8621:         my $is_me=0;
 8622:         my @ids=&current_machine_ids();
 8623:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 8624:         if ($is_me) {
 8625:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
 8626:         } else {
 8627:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 8628:   	      $udom.'/'.$uname.'/'.$filename;
 8629:         }
 8630:     } elsif ($file =~ m-^/adm/-) {
 8631: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 8632:     } else {
 8633:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8634:         $file=~s:^/res/:/:;
 8635:         if ( !( $file =~ m:^/:) ) {
 8636:             $location = $dir. '/'.$file;
 8637:         } else {
 8638:             $location = '/home/httpd/html/res'.$file;
 8639:         }
 8640:     }
 8641:     $location=~s://+:/:g; # remove duplicate /
 8642:     while ($location=~m{/\.\./}) {
 8643: 	if ($location =~ m{/[^/]+/\.\./}) {
 8644: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 8645: 	} else {
 8646: 	    $location=~ s{/\.\./}{/}g;
 8647: 	}
 8648:     } #remove dir/..
 8649:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 8650:     return $location;
 8651: }
 8652: 
 8653: sub hreflocation {
 8654:     my ($dir,$file)=@_;
 8655:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
 8656: 	$file=filelocation($dir,$file);
 8657:     } elsif ($file=~m-^/adm/-) {
 8658: 	$file=~s-^/adm/wrapper/-/-;
 8659: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8660:     }
 8661:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 8662: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 8663:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 8664: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 8665:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 8666: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 8667: 	    -/uploaded/$1/$2/-x;
 8668:     }
 8669:     if ($file=~ m{^/userfiles/}) {
 8670: 	$file =~ s{^/userfiles/}{/uploaded/};
 8671:     }
 8672:     return $file;
 8673: }
 8674: 
 8675: sub current_machine_domains {
 8676:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 8677: }
 8678: 
 8679: sub machine_domains {
 8680:     my ($hostname) = @_;
 8681:     my @domains;
 8682:     my %hostname = &all_hostnames();
 8683:     while( my($id, $name) = each(%hostname)) {
 8684: #	&logthis("-$id-$name-$hostname-");
 8685: 	if ($hostname eq $name) {
 8686: 	    push(@domains,&host_domain($id));
 8687: 	}
 8688:     }
 8689:     return @domains;
 8690: }
 8691: 
 8692: sub current_machine_ids {
 8693:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 8694: }
 8695: 
 8696: sub machine_ids {
 8697:     my ($hostname) = @_;
 8698:     $hostname ||= &hostname($perlvar{'lonHostID'});
 8699:     my @ids;
 8700:     my %name_to_host = &all_names();
 8701:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 8702: 	return @{ $name_to_host{$hostname} };
 8703:     }
 8704:     return;
 8705: }
 8706: 
 8707: sub additional_machine_domains {
 8708:     my @domains;
 8709:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 8710:     while( my $line = <$fh>) {
 8711:         $line =~ s/\s//g;
 8712:         push(@domains,$line);
 8713:     }
 8714:     return @domains;
 8715: }
 8716: 
 8717: sub default_login_domain {
 8718:     my $domain = $perlvar{'lonDefDomain'};
 8719:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 8720:     foreach my $posdom (&current_machine_domains(),
 8721:                         &additional_machine_domains()) {
 8722:         if (lc($posdom) eq lc($testdomain)) {
 8723:             $domain=$posdom;
 8724:             last;
 8725:         }
 8726:     }
 8727:     return $domain;
 8728: }
 8729: 
 8730: # ------------------------------------------------------------- Declutters URLs
 8731: 
 8732: sub declutter {
 8733:     my $thisfn=shift;
 8734:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8735:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8736:     $thisfn=~s/^\///;
 8737:     $thisfn=~s|^adm/wrapper/||;
 8738:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 8739:     $thisfn=~s/^res\///;
 8740:     $thisfn=~s/\?.+$//;
 8741:     return $thisfn;
 8742: }
 8743: 
 8744: # ------------------------------------------------------------- Clutter up URLs
 8745: 
 8746: sub clutter {
 8747:     my $thisfn='/'.&declutter(shift);
 8748:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 8749: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 8750:        $thisfn='/res'.$thisfn; 
 8751:     }
 8752:     if ($thisfn !~m|/adm|) {
 8753: 	if ($thisfn =~ m|/ext/|) {
 8754: 	    $thisfn='/adm/wrapper'.$thisfn;
 8755: 	} else {
 8756: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 8757: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 8758: 	    if ($embstyle eq 'ssi'
 8759: 		|| ($embstyle eq 'hdn')
 8760: 		|| ($embstyle eq 'rat')
 8761: 		|| ($embstyle eq 'prv')
 8762: 		|| ($embstyle eq 'ign')) {
 8763: 		#do nothing with these
 8764: 	    } elsif (($embstyle eq 'img') 
 8765: 		|| ($embstyle eq 'emb')
 8766: 		|| ($embstyle eq 'wrp')) {
 8767: 		$thisfn='/adm/wrapper'.$thisfn;
 8768: 	    } elsif ($embstyle eq 'unk'
 8769: 		     && $thisfn!~/\.(sequence|page)$/) {
 8770: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 8771: 	    } else {
 8772: #		&logthis("Got a blank emb style");
 8773: 	    }
 8774: 	}
 8775:     }
 8776:     return $thisfn;
 8777: }
 8778: 
 8779: sub clutter_with_no_wrapper {
 8780:     my $uri = &clutter(shift);
 8781:     if ($uri =~ m-^/adm/-) {
 8782: 	$uri =~ s-^/adm/wrapper/-/-;
 8783: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 8784:     }
 8785:     return $uri;
 8786: }
 8787: 
 8788: sub freeze_escape {
 8789:     my ($value)=@_;
 8790:     if (ref($value)) {
 8791: 	$value=&nfreeze($value);
 8792: 	return '__FROZEN__'.&escape($value);
 8793:     }
 8794:     return &escape($value);
 8795: }
 8796: 
 8797: 
 8798: sub thaw_unescape {
 8799:     my ($value)=@_;
 8800:     if ($value =~ /^__FROZEN__/) {
 8801: 	substr($value,0,10,undef);
 8802: 	$value=&unescape($value);
 8803: 	return &thaw($value);
 8804:     }
 8805:     return &unescape($value);
 8806: }
 8807: 
 8808: sub correct_line_ends {
 8809:     my ($result)=@_;
 8810:     $$result =~s/\r\n/\n/mg;
 8811:     $$result =~s/\r/\n/mg;
 8812: }
 8813: # ================================================================ Main Program
 8814: 
 8815: sub goodbye {
 8816:    &logthis("Starting Shut down");
 8817: #not converted to using infrastruture and probably shouldn't be
 8818:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 8819: #converted
 8820: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 8821:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 8822: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 8823: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 8824: #1.1 only
 8825: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 8826: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 8827: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 8828: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 8829:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 8830:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 8831:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 8832:    &flushcourselogs();
 8833:    &logthis("Shutting down");
 8834: }
 8835: 
 8836: sub get_dns {
 8837:     my ($url,$func,$ignore_cache) = @_;
 8838:     if (!$ignore_cache) {
 8839: 	my ($content,$cached)=
 8840: 	    &Apache::lonnet::is_cached_new('dns',$url);
 8841: 	if ($cached) {
 8842: 	    &$func($content);
 8843: 	    return;
 8844: 	}
 8845:     }
 8846: 
 8847:     my %alldns;
 8848:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8849:     foreach my $dns (<$config>) {
 8850: 	next if ($dns !~ /^\^(\S*)/x);
 8851:         my $line = $1;
 8852:         my ($host,$protocol) = split(/:/,$line);
 8853:         if ($protocol ne 'https') {
 8854:             $protocol = 'http';
 8855:         }
 8856: 	$alldns{$host} = $protocol;
 8857:     }
 8858:     while (%alldns) {
 8859: 	my ($dns) = keys(%alldns);
 8860: 	my $ua=new LWP::UserAgent;
 8861: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
 8862: 	my $response=$ua->request($request);
 8863:         delete($alldns{$dns});
 8864: 	next if ($response->is_error());
 8865: 	my @content = split("\n",$response->content);
 8866: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 8867: 	&$func(\@content);
 8868: 	return;
 8869:     }
 8870:     close($config);
 8871:     my $which = (split('/',$url))[3];
 8872:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 8873:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 8874:     my @content = <$config>;
 8875:     &$func(\@content);
 8876:     return;
 8877: }
 8878: # ------------------------------------------------------------ Read domain file
 8879: {
 8880:     my $loaded;
 8881:     my %domain;
 8882: 
 8883:     sub parse_domain_tab {
 8884: 	my ($lines) = @_;
 8885: 	foreach my $line (@$lines) {
 8886: 	    next if ($line =~ /^(\#|\s*$ )/x);
 8887: 
 8888: 	    chomp($line);
 8889: 	    my ($name,@elements) = split(/:/,$line,9);
 8890: 	    my %this_domain;
 8891: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 8892: 			       'lang_def', 'city', 'longi', 'lati',
 8893: 			       'primary') {
 8894: 		$this_domain{$field} = shift(@elements);
 8895: 	    }
 8896: 	    $domain{$name} = \%this_domain;
 8897: 	}
 8898:     }
 8899: 
 8900:     sub reset_domain_info {
 8901: 	undef($loaded);
 8902: 	undef(%domain);
 8903:     }
 8904: 
 8905:     sub load_domain_tab {
 8906: 	my ($ignore_cache) = @_;
 8907: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 8908: 	my $fh;
 8909: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 8910: 	    my @lines = <$fh>;
 8911: 	    &parse_domain_tab(\@lines);
 8912: 	}
 8913: 	close($fh);
 8914: 	$loaded = 1;
 8915:     }
 8916: 
 8917:     sub domain {
 8918: 	&load_domain_tab() if (!$loaded);
 8919: 
 8920: 	my ($name,$what) = @_;
 8921: 	return if ( !exists($domain{$name}) );
 8922: 
 8923: 	if (!$what) {
 8924: 	    return $domain{$name}{'description'};
 8925: 	}
 8926: 	return $domain{$name}{$what};
 8927:     }
 8928: 
 8929:     sub domain_info {
 8930:         &load_domain_tab() if (!$loaded);
 8931:         return %domain;
 8932:     }
 8933: 
 8934: }
 8935: 
 8936: 
 8937: # ------------------------------------------------------------- Read hosts file
 8938: {
 8939:     my %hostname;
 8940:     my %hostdom;
 8941:     my %libserv;
 8942:     my $loaded;
 8943:     my %name_to_host;
 8944: 
 8945:     sub parse_hosts_tab {
 8946: 	my ($file) = @_;
 8947: 	foreach my $configline (@$file) {
 8948: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 8949: 	    next if ($configline =~ /^\^/);
 8950: 	    chomp($configline);
 8951: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
 8952: 	    $name=~s/\s//g;
 8953: 	    if ($id && $domain && $role && $name) {
 8954: 		$hostname{$id}=$name;
 8955: 		push(@{$name_to_host{$name}}, $id);
 8956: 		$hostdom{$id}=$domain;
 8957: 		if ($role eq 'library') { $libserv{$id}=$name; }
 8958:                 if (defined($protocol)) {
 8959:                     if ($protocol eq 'https') {
 8960:                         $protocol{$id} = $protocol;
 8961:                     } else {
 8962:                         $protocol{$id} = 'http'; 
 8963:                     }
 8964:                 } else {
 8965:                     $protocol{$id} = 'http';
 8966:                 }
 8967: 	    }
 8968: 	}
 8969:     }
 8970:     
 8971:     sub reset_hosts_info {
 8972: 	&purge_remembered();
 8973: 	&reset_domain_info();
 8974: 	&reset_hosts_ip_info();
 8975: 	undef(%name_to_host);
 8976: 	undef(%hostname);
 8977: 	undef(%hostdom);
 8978: 	undef(%libserv);
 8979: 	undef($loaded);
 8980:     }
 8981: 
 8982:     sub load_hosts_tab {
 8983: 	my ($ignore_cache) = @_;
 8984: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 8985: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8986: 	my @config = <$config>;
 8987: 	&parse_hosts_tab(\@config);
 8988: 	close($config);
 8989: 	$loaded=1;
 8990:     }
 8991: 
 8992:     sub hostname {
 8993: 	&load_hosts_tab() if (!$loaded);
 8994: 
 8995: 	my ($lonid) = @_;
 8996: 	return $hostname{$lonid};
 8997:     }
 8998: 
 8999:     sub all_hostnames {
 9000: 	&load_hosts_tab() if (!$loaded);
 9001: 
 9002: 	return %hostname;
 9003:     }
 9004: 
 9005:     sub all_names {
 9006: 	&load_hosts_tab() if (!$loaded);
 9007: 
 9008: 	return %name_to_host;
 9009:     }
 9010: 
 9011:     sub all_host_domain {
 9012:         &load_hosts_tab() if (!$loaded);
 9013:         return %hostdom;
 9014:     }
 9015: 
 9016:     sub is_library {
 9017: 	&load_hosts_tab() if (!$loaded);
 9018: 
 9019: 	return exists($libserv{$_[0]});
 9020:     }
 9021: 
 9022:     sub all_library {
 9023: 	&load_hosts_tab() if (!$loaded);
 9024: 
 9025: 	return %libserv;
 9026:     }
 9027: 
 9028:     sub get_servers {
 9029: 	&load_hosts_tab() if (!$loaded);
 9030: 
 9031: 	my ($domain,$type) = @_;
 9032: 	my %possible_hosts = ($type eq 'library') ? %libserv
 9033: 	                                          : %hostname;
 9034: 	my %result;
 9035: 	if (ref($domain) eq 'ARRAY') {
 9036: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9037: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 9038: 		    $result{$host} = $hostname;
 9039: 		}
 9040: 	    }
 9041: 	} else {
 9042: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9043: 		if ($hostdom{$host} eq $domain) {
 9044: 		    $result{$host} = $hostname;
 9045: 		}
 9046: 	    }
 9047: 	}
 9048: 	return %result;
 9049:     }
 9050: 
 9051:     sub host_domain {
 9052: 	&load_hosts_tab() if (!$loaded);
 9053: 
 9054: 	my ($lonid) = @_;
 9055: 	return $hostdom{$lonid};
 9056:     }
 9057: 
 9058:     sub all_domains {
 9059: 	&load_hosts_tab() if (!$loaded);
 9060: 
 9061: 	my %seen;
 9062: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 9063: 	return @uniq;
 9064:     }
 9065: }
 9066: 
 9067: { 
 9068:     my %iphost;
 9069:     my %name_to_ip;
 9070:     my %lonid_to_ip;
 9071: 
 9072:     sub get_hosts_from_ip {
 9073: 	my ($ip) = @_;
 9074: 	my %iphosts = &get_iphost();
 9075: 	if (ref($iphosts{$ip})) {
 9076: 	    return @{$iphosts{$ip}};
 9077: 	}
 9078: 	return;
 9079:     }
 9080:     
 9081:     sub reset_hosts_ip_info {
 9082: 	undef(%iphost);
 9083: 	undef(%name_to_ip);
 9084: 	undef(%lonid_to_ip);
 9085:     }
 9086: 
 9087:     sub get_host_ip {
 9088: 	my ($lonid) = @_;
 9089: 	if (exists($lonid_to_ip{$lonid})) {
 9090: 	    return $lonid_to_ip{$lonid};
 9091: 	}
 9092: 	my $name=&hostname($lonid);
 9093:    	my $ip = gethostbyname($name);
 9094: 	return if (!$ip || length($ip) ne 4);
 9095: 	$ip=inet_ntoa($ip);
 9096: 	$name_to_ip{$name}   = $ip;
 9097: 	$lonid_to_ip{$lonid} = $ip;
 9098: 	return $ip;
 9099:     }
 9100:     
 9101:     sub get_iphost {
 9102: 	my ($ignore_cache) = @_;
 9103: 
 9104: 	if (!$ignore_cache) {
 9105: 	    if (%iphost) {
 9106: 		return %iphost;
 9107: 	    }
 9108: 	    my ($ip_info,$cached)=
 9109: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 9110: 	    if ($cached) {
 9111: 		%iphost      = %{$ip_info->[0]};
 9112: 		%name_to_ip  = %{$ip_info->[1]};
 9113: 		%lonid_to_ip = %{$ip_info->[2]};
 9114: 		return %iphost;
 9115: 	    }
 9116: 	}
 9117: 
 9118: 	# get yesterday's info for fallback
 9119: 	my %old_name_to_ip;
 9120: 	my ($ip_info,$cached)=
 9121: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 9122: 	if ($cached) {
 9123: 	    %old_name_to_ip = %{$ip_info->[1]};
 9124: 	}
 9125: 
 9126: 	my %name_to_host = &all_names();
 9127: 	foreach my $name (keys(%name_to_host)) {
 9128: 	    my $ip;
 9129: 	    if (!exists($name_to_ip{$name})) {
 9130: 		$ip = gethostbyname($name);
 9131: 		if (!$ip || length($ip) ne 4) {
 9132: 		    if (defined($old_name_to_ip{$name})) {
 9133: 			$ip = $old_name_to_ip{$name};
 9134: 			&logthis("Can't find $name defaulting to old $ip");
 9135: 		    } else {
 9136: 			&logthis("Name $name no IP found");
 9137: 			next;
 9138: 		    }
 9139: 		} else {
 9140: 		    $ip=inet_ntoa($ip);
 9141: 		}
 9142: 		$name_to_ip{$name} = $ip;
 9143: 	    } else {
 9144: 		$ip = $name_to_ip{$name};
 9145: 	    }
 9146: 	    foreach my $id (@{ $name_to_host{$name} }) {
 9147: 		$lonid_to_ip{$id} = $ip;
 9148: 	    }
 9149: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 9150: 	}
 9151: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 9152: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 9153: 				      48*60*60);
 9154: 
 9155: 	return %iphost;
 9156:     }
 9157: 
 9158:     #
 9159:     #  Given a DNS returns the loncapa host name for that DNS 
 9160:     # 
 9161:     sub host_from_dns {
 9162:         my ($dns) = @_;
 9163:         my @hosts;
 9164:         my $ip;
 9165: 
 9166:         if (exists($name_to_ip{$dns})) {
 9167:             $ip = $name_to_ip{$dns};
 9168:         }
 9169:         if (!$ip) {
 9170:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
 9171:             if (length($ip) == 4) { 
 9172: 	        $ip   = &IO::Socket::inet_ntoa($ip);
 9173:             }
 9174:         }
 9175:         if ($ip) {
 9176: 	    @hosts = get_hosts_from_ip($ip);
 9177: 	    return $hosts[0];
 9178:         }
 9179:         return undef;
 9180:     }
 9181: 
 9182: }
 9183: 
 9184: BEGIN {
 9185: 
 9186: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 9187:     unless ($readit) {
 9188: {
 9189:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 9190:     %perlvar = (%perlvar,%{$configvars});
 9191: }
 9192: 
 9193: 
 9194: # ------------------------------------------------------ Read spare server file
 9195: {
 9196:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 9197: 
 9198:     while (my $configline=<$config>) {
 9199:        chomp($configline);
 9200:        if ($configline) {
 9201: 	   my ($host,$type) = split(':',$configline,2);
 9202: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 9203: 	   push(@{ $spareid{$type} }, $host);
 9204:        }
 9205:     }
 9206:     close($config);
 9207: }
 9208: # ------------------------------------------------------------ Read permissions
 9209: {
 9210:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 9211: 
 9212:     while (my $configline=<$config>) {
 9213: 	chomp($configline);
 9214: 	if ($configline) {
 9215: 	    my ($role,$perm)=split(/ /,$configline);
 9216: 	    if ($perm ne '') { $pr{$role}=$perm; }
 9217: 	}
 9218:     }
 9219:     close($config);
 9220: }
 9221: 
 9222: # -------------------------------------------- Read plain texts for permissions
 9223: {
 9224:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 9225: 
 9226:     while (my $configline=<$config>) {
 9227: 	chomp($configline);
 9228: 	if ($configline) {
 9229: 	    my ($short,@plain)=split(/:/,$configline);
 9230:             %{$prp{$short}} = ();
 9231: 	    if (@plain > 0) {
 9232:                 $prp{$short}{'std'} = $plain[0];
 9233:                 for (my $i=1; $i<@plain; $i++) {
 9234:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 9235:                 }
 9236:             }
 9237: 	}
 9238:     }
 9239:     close($config);
 9240: }
 9241: 
 9242: # ---------------------------------------------------------- Read package table
 9243: {
 9244:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 9245: 
 9246:     while (my $configline=<$config>) {
 9247: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 9248: 	chomp($configline);
 9249: 	my ($short,$plain)=split(/:/,$configline);
 9250: 	my ($pack,$name)=split(/\&/,$short);
 9251: 	if ($plain ne '') {
 9252: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 9253: 	    $packagetab{$short}=$plain; 
 9254: 	}
 9255:     }
 9256:     close($config);
 9257: }
 9258: 
 9259: # ------------- set up temporary directory
 9260: {
 9261:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 9262: 
 9263: }
 9264: 
 9265: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 9266: 				'compress_threshold'=> 20_000,
 9267:  			        });
 9268: 
 9269: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 9270: $dumpcount=0;
 9271: $locknum=0;
 9272: 
 9273: &logtouch();
 9274: &logthis('<font color="yellow">INFO: Read configuration</font>');
 9275: $readit=1;
 9276:     {
 9277: 	use integer;
 9278: 	my $test=(2**32)+1;
 9279: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 9280: 	&logthis(" Detected 64bit platform ($_64bit)");
 9281:     }
 9282: }
 9283: }
 9284: 
 9285: 1;
 9286: __END__
 9287: 
 9288: =pod
 9289: 
 9290: =head1 NAME
 9291: 
 9292: Apache::lonnet - Subroutines to ask questions about things in the network.
 9293: 
 9294: =head1 SYNOPSIS
 9295: 
 9296: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 9297: 
 9298:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 9299: 
 9300: Common parameters:
 9301: 
 9302: =over 4
 9303: 
 9304: =item *
 9305: 
 9306: $uname : an internal username (if $cname expecting a course Id specifically)
 9307: 
 9308: =item *
 9309: 
 9310: $udom : a domain (if $cdom expecting a course's domain specifically)
 9311: 
 9312: =item *
 9313: 
 9314: $symb : a resource instance identifier
 9315: 
 9316: =item *
 9317: 
 9318: $namespace : the name of a .db file that contains the data needed or
 9319: being set.
 9320: 
 9321: =back
 9322: 
 9323: =head1 OVERVIEW
 9324: 
 9325: lonnet provides subroutines which interact with the
 9326: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 9327: about classes, users, and resources.
 9328: 
 9329: For many of these objects you can also use this to store data about
 9330: them or modify them in various ways.
 9331: 
 9332: =head2 Symbs
 9333: 
 9334: To identify a specific instance of a resource, LON-CAPA uses symbols
 9335: or "symbs"X<symb>. These identifiers are built from the URL of the
 9336: map, the resource number of the resource in the map, and the URL of
 9337: the resource itself. The latter is somewhat redundant, but might help
 9338: if maps change.
 9339: 
 9340: An example is
 9341: 
 9342:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 9343: 
 9344: The respective map entry is
 9345: 
 9346:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 9347:   title="Problem 2">
 9348:  </resource>
 9349: 
 9350: Symbs are used by the random number generator, as well as to store and
 9351: restore data specific to a certain instance of for example a problem.
 9352: 
 9353: =head2 Storing And Retrieving Data
 9354: 
 9355: X<store()>X<cstore()>X<restore()>Three of the most important functions
 9356: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 9357: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 9358: is is the non-critical message twin of cstore. These functions are for
 9359: handlers to store a perl hash to a user's permanent data space in an
 9360: easy manner, and to retrieve it again on another call. It is expected
 9361: that a handler would use this once at the beginning to retrieve data,
 9362: and then again once at the end to send only the new data back.
 9363: 
 9364: The data is stored in the user's data directory on the user's
 9365: homeserver under the ID of the course.
 9366: 
 9367: The hash that is returned by restore will have all of the previous
 9368: value for all of the elements of the hash.
 9369: 
 9370: Example:
 9371: 
 9372:  #creating a hash
 9373:  my %hash;
 9374:  $hash{'foo'}='bar';
 9375: 
 9376:  #storing it
 9377:  &Apache::lonnet::cstore(\%hash);
 9378: 
 9379:  #changing a value
 9380:  $hash{'foo'}='notbar';
 9381: 
 9382:  #adding a new value
 9383:  $hash{'bar'}='foo';
 9384:  &Apache::lonnet::cstore(\%hash);
 9385: 
 9386:  #retrieving the hash
 9387:  my %history=&Apache::lonnet::restore();
 9388: 
 9389:  #print the hash
 9390:  foreach my $key (sort(keys(%history))) {
 9391:    print("\%history{$key} = $history{$key}");
 9392:  }
 9393: 
 9394: Will print out:
 9395: 
 9396:  %history{1:foo} = bar
 9397:  %history{1:keys} = foo:timestamp
 9398:  %history{1:timestamp} = 990455579
 9399:  %history{2:bar} = foo
 9400:  %history{2:foo} = notbar
 9401:  %history{2:keys} = foo:bar:timestamp
 9402:  %history{2:timestamp} = 990455580
 9403:  %history{bar} = foo
 9404:  %history{foo} = notbar
 9405:  %history{timestamp} = 990455580
 9406:  %history{version} = 2
 9407: 
 9408: Note that the special hash entries C<keys>, C<version> and
 9409: C<timestamp> were added to the hash. C<version> will be equal to the
 9410: total number of versions of the data that have been stored. The
 9411: C<timestamp> attribute will be the UNIX time the hash was
 9412: stored. C<keys> is available in every historical section to list which
 9413: keys were added or changed at a specific historical revision of a
 9414: hash.
 9415: 
 9416: B<Warning>: do not store the hash that restore returns directly. This
 9417: will cause a mess since it will restore the historical keys as if the
 9418: were new keys. I.E. 1:foo will become 1:1:foo etc.
 9419: 
 9420: Calling convention:
 9421: 
 9422:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 9423:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 9424: 
 9425: For more detailed information, see lonnet specific documentation.
 9426: 
 9427: =head1 RETURN MESSAGES
 9428: 
 9429: =over 4
 9430: 
 9431: =item * B<con_lost>: unable to contact remote host
 9432: 
 9433: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 9434: when the connection is brought back up
 9435: 
 9436: =item * B<con_failed>: unable to contact remote host and unable to save message
 9437: for later delivery
 9438: 
 9439: =item * B<error:>: an error a occurred, a description of the error follows the :
 9440: 
 9441: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 9442: that was requested
 9443: 
 9444: =back
 9445: 
 9446: =head1 PUBLIC SUBROUTINES
 9447: 
 9448: =head2 Session Environment Functions
 9449: 
 9450: =over 4
 9451: 
 9452: =item * 
 9453: X<appenv()>
 9454: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
 9455: the user envirnoment file, and will be restored for each access this
 9456: user makes during this session, also modifies the %env for the current
 9457: process. Optional rolesarrayref - if defined contains a reference to an array
 9458: of roles which are exempt from the restriction on modifying user.role entries 
 9459: in the user's environment.db and in %env.    
 9460: 
 9461: =item *
 9462: X<delenv()>
 9463: B<delenv($delthis,$regexp)>: removes all items from the session
 9464: environment file that begin with $delthis. If the 
 9465: optional second arg - $regexp - is true, $delthis is treated as a 
 9466: regular expression, otherwise \Q$delthis\E is used. 
 9467: The values are also deleted from the current processes %env.
 9468: 
 9469: =item * get_env_multiple($name) 
 9470: 
 9471: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9472: values may be defined and end up as an array ref.
 9473: 
 9474: returns an array of values
 9475: 
 9476: =back
 9477: 
 9478: =head2 User Information
 9479: 
 9480: =over 4
 9481: 
 9482: =item *
 9483: X<queryauthenticate()>
 9484: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 9485: authentication scheme
 9486: 
 9487: =item *
 9488: X<authenticate()>
 9489: B<authenticate($uname,$upass,$udom)>: try to
 9490: authenticate user from domain's lib servers (first use the current
 9491: one). C<$upass> should be the users password.
 9492: 
 9493: =item *
 9494: X<homeserver()>
 9495: B<homeserver($uname,$udom)>: find the server which has
 9496: the user's directory and files (there must be only one), this caches
 9497: the answer, and also caches if there is a borken connection.
 9498: 
 9499: =item *
 9500: X<idget()>
 9501: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 9502: (IDs are a unique resource in a domain, there must be only 1 ID per
 9503: username, and only 1 username per ID in a specific domain) (returns
 9504: hash: id=>name,id=>name)
 9505: 
 9506: =item *
 9507: X<idrget()>
 9508: B<idrget($udom,@unames)>: find the IDs behind a list of
 9509: usernames (returns hash: name=>id,name=>id)
 9510: 
 9511: =item *
 9512: X<idput()>
 9513: B<idput($udom,%ids)>: store away a list of names and associated IDs
 9514: 
 9515: =item *
 9516: X<rolesinit()>
 9517: B<rolesinit($udom,$username,$authhost)>: get user privileges
 9518: 
 9519: =item *
 9520: X<getsection()>
 9521: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 9522: course $cname, return section name/number or '' for "not in course"
 9523: and '-1' for "no section"
 9524: 
 9525: =item *
 9526: X<userenvironment()>
 9527: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 9528: passed in @what from the requested user's environment, returns a hash
 9529: 
 9530: =item * 
 9531: X<userlog_query()>
 9532: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 9533: activity.log file. %filters defines filters applied when parsing the
 9534: log file. These can be start or end timestamps, or the type of action
 9535: - log to look for Login or Logout events, check for Checkin or
 9536: Checkout, role for role selection. The response is in the form
 9537: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 9538: escaped strings of the action recorded in the activity.log file.
 9539: 
 9540: =back
 9541: 
 9542: =head2 User Roles
 9543: 
 9544: =over 4
 9545: 
 9546: =item *
 9547: 
 9548: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 9549:  F: full access
 9550:  U,I,K: authentication modes (cxx only)
 9551:  '': forbidden
 9552:  1: user needs to choose course
 9553:  2: browse allowed
 9554:  A: passphrase authentication needed
 9555: 
 9556: =item *
 9557: 
 9558: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 9559: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 9560: and course level
 9561: 
 9562: =item *
 9563: 
 9564: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
 9565: (rolesplain.tab); plain text explanation of a user role term.
 9566: $type is Course (default) or Group.
 9567: If $forcedefault evaluates to true, text returned will be default 
 9568: text for $type. Otherwise, if this is a course, the text returned 
 9569: will be a custom name for the role (if defined in the course's 
 9570: environment).  If no custom name is defined the default is returned.
 9571:    
 9572: =item *
 9573: 
 9574: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
 9575: All arguments are optional. Returns a hash of a roles, either for
 9576: co-author/assistant author roles for a user's Construction Space
 9577: (default), or if $context is 'userroles', roles for the user himself,
 9578: In the hash, keys are set to colon-separated $uname,$udom,$role, and
 9579: (optionally) if $withsec is true, a fourth colon-separated item - $section.
 9580: For each key, value is set to colon-separated start and end times for
 9581: the role.  If no username and domain are specified, will default to
 9582: current user/domain. Types, roles, and roledoms are references to arrays
 9583: of role statuses (active, future or previous), roles 
 9584: (e.g., cc,in, st etc.) and domains of the roles which can be used
 9585: to restrict the list of roles reported. If no array ref is 
 9586: provided for types, will default to return only active roles.
 9587: 
 9588: =back
 9589: 
 9590: =head2 User Modification
 9591: 
 9592: =over 4
 9593: 
 9594: =item *
 9595: 
 9596: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
 9597: user for the level given by URL.  Optional start and end dates (leave empty
 9598: string or zero for "no date")
 9599: 
 9600: =item *
 9601: 
 9602: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 9603: change a users, password, possible return values are: ok,
 9604: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 9605: refused
 9606: 
 9607: =item *
 9608: 
 9609: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 9610: 
 9611: =item *
 9612: 
 9613: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
 9614:            $forceid,$desiredhome,$email,$inststatus) : 
 9615: modify user
 9616: 
 9617: =item *
 9618: 
 9619: modifystudent
 9620: 
 9621: modify a student's enrollment and identification information.
 9622: The course id is resolved based on the current users environment.  
 9623: This means the envoking user must be a course coordinator or otherwise
 9624: associated with a course.
 9625: 
 9626: This call is essentially a wrapper for lonnet::modifyuser and
 9627: lonnet::modify_student_enrollment
 9628: 
 9629: Inputs: 
 9630: 
 9631: =over 4
 9632: 
 9633: =item B<$udom> Student's loncapa domain
 9634: 
 9635: =item B<$uname> Student's loncapa login name
 9636: 
 9637: =item B<$uid> Student/Employee ID
 9638: 
 9639: =item B<$umode> Student's authentication mode
 9640: 
 9641: =item B<$upass> Student's password
 9642: 
 9643: =item B<$first> Student's first name
 9644: 
 9645: =item B<$middle> Student's middle name
 9646: 
 9647: =item B<$last> Student's last name
 9648: 
 9649: =item B<$gene> Student's generation
 9650: 
 9651: =item B<$usec> Student's section in course
 9652: 
 9653: =item B<$end> Unix time of the roles expiration
 9654: 
 9655: =item B<$start> Unix time of the roles start date
 9656: 
 9657: =item B<$forceid> If defined, allow $uid to be changed
 9658: 
 9659: =item B<$desiredhome> server to use as home server for student
 9660: 
 9661: =item B<$email> Student's permanent e-mail address
 9662: 
 9663: =item B<$type> Type of enrollment (auto or manual)
 9664: 
 9665: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
 9666: 
 9667: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
 9668: 
 9669: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
 9670: 
 9671: =item B<$context> role change context (shown in User Management Logs display in a course)
 9672: 
 9673: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
 9674: 
 9675: =back
 9676: 
 9677: =item *
 9678: 
 9679: modify_student_enrollment
 9680: 
 9681: Change a students enrollment status in a class.  The environment variable
 9682: 'role.request.course' must be defined for this function to proceed.
 9683: 
 9684: Inputs:
 9685: 
 9686: =over 4
 9687: 
 9688: =item $udom, students domain
 9689: 
 9690: =item $uname, students name
 9691: 
 9692: =item $uid, students user id
 9693: 
 9694: =item $first, students first name
 9695: 
 9696: =item $middle
 9697: 
 9698: =item $last
 9699: 
 9700: =item $gene
 9701: 
 9702: =item $usec
 9703: 
 9704: =item $end
 9705: 
 9706: =item $start
 9707: 
 9708: =item $type
 9709: 
 9710: =item $locktype
 9711: 
 9712: =item $cid
 9713: 
 9714: =item $selfenroll
 9715: 
 9716: =item $context
 9717: 
 9718: =back
 9719: 
 9720: 
 9721: =item *
 9722: 
 9723: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 9724: custom role; give a custom role to a user for the level given by URL.  Specify
 9725: name and domain of role author, and role name
 9726: 
 9727: =item *
 9728: 
 9729: revokerole($udom,$uname,$url,$role) : revoke a role for url
 9730: 
 9731: =item *
 9732: 
 9733: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 9734: 
 9735: =back
 9736: 
 9737: =head2 Course Infomation
 9738: 
 9739: =over 4
 9740: 
 9741: =item *
 9742: 
 9743: coursedescription($courseid) : returns a hash of information about the
 9744: specified course id, including all environment settings for the
 9745: course, the description of the course will be in the hash under the
 9746: key 'description'
 9747: 
 9748: =item *
 9749: 
 9750: resdata($name,$domain,$type,@which) : request for current parameter
 9751: setting for a specific $type, where $type is either 'course' or 'user',
 9752: @what should be a list of parameters to ask about. This routine caches
 9753: answers for 5 minutes.
 9754: 
 9755: =item *
 9756: 
 9757: get_courseresdata($courseid, $domain) : dump the entire course resource
 9758: data base, returning a hash that is keyed by the resource name and has
 9759: values that are the resource value.  I believe that the timestamps and
 9760: versions are also returned.
 9761: 
 9762: 
 9763: =back
 9764: 
 9765: =head2 Course Modification
 9766: 
 9767: =over 4
 9768: 
 9769: =item *
 9770: 
 9771: writecoursepref($courseid,%prefs) : write preferences (environment
 9772: database) for a course
 9773: 
 9774: =item *
 9775: 
 9776: createcourse($udom,$description,$url) : make/modify course
 9777: 
 9778: =back
 9779: 
 9780: =head2 Resource Subroutines
 9781: 
 9782: =over 4
 9783: 
 9784: =item *
 9785: 
 9786: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 9787: 
 9788: =item *
 9789: 
 9790: repcopy($filename) : subscribes to the requested file, and attempts to
 9791: replicate from the owning library server, Might return
 9792: 'unavailable', 'not_found', 'forbidden', 'ok', or
 9793: 'bad_request', also attempts to grab the metadata for the
 9794: resource. Expects the local filesystem pathname
 9795: (/home/httpd/html/res/....)
 9796: 
 9797: =back
 9798: 
 9799: =head2 Resource Information
 9800: 
 9801: =over 4
 9802: 
 9803: =item *
 9804: 
 9805: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 9806: a vairety of different possible values, $varname should be a request
 9807: string, and the other parameters can be used to specify who and what
 9808: one is asking about.
 9809: 
 9810: Possible values for $varname are environment.lastname (or other item
 9811: from the envirnment hash), user.name (or someother aspect about the
 9812: user), resource.0.maxtries (or some other part and parameter of a
 9813: resource)
 9814: 
 9815: =item *
 9816: 
 9817: directcondval($number) : get current value of a condition; reads from a state
 9818: string
 9819: 
 9820: =item *
 9821: 
 9822: condval($condidx) : value of condition index based on state
 9823: 
 9824: =item *
 9825: 
 9826: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 9827: resource's metadata, $what should be either a specific key, or either
 9828: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 9829: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 9830: 
 9831: this function automatically caches all requests
 9832: 
 9833: =item *
 9834: 
 9835: metadata_query($query,$custom,$customshow) : make a metadata query against the
 9836: network of library servers; returns file handle of where SQL and regex results
 9837: will be stored for query
 9838: 
 9839: =item *
 9840: 
 9841: symbread($filename) : return symbolic list entry (filename argument optional);
 9842: returns the data handle
 9843: 
 9844: =item *
 9845: 
 9846: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 9847: a possible symb for the URL in $thisfn, and if is an encryypted
 9848: resource that the user accessed using /enc/ returns a 1 on success, 0
 9849: on failure, user must be in a course, as it assumes the existance of
 9850: the course initial hash, and uses $env('request.course.id'}
 9851: 
 9852: 
 9853: =item *
 9854: 
 9855: symbclean($symb) : removes versions numbers from a symb, returns the
 9856: cleaned symb
 9857: 
 9858: =item *
 9859: 
 9860: is_on_map($uri) : checks if the $uri is somewhere on the current
 9861: course map, user must be in a course for it to work.
 9862: 
 9863: =item *
 9864: 
 9865: numval($salt) : return random seed value (addend for rndseed)
 9866: 
 9867: =item *
 9868: 
 9869: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 9870: a random seed, all arguments are optional, if they aren't sent it uses the
 9871: environment to derive them. Note: if symb isn't sent and it can't get one
 9872: from &symbread it will use the current time as its return value
 9873: 
 9874: =item *
 9875: 
 9876: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 9877: unfakeable, receipt
 9878: 
 9879: =item *
 9880: 
 9881: receipt() : API to ireceipt working off of env values; given out to users
 9882: 
 9883: =item *
 9884: 
 9885: countacc($url) : count the number of accesses to a given URL
 9886: 
 9887: =item *
 9888: 
 9889: 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
 9890: 
 9891: =item *
 9892: 
 9893: 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)
 9894: 
 9895: =item *
 9896: 
 9897: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 9898: 
 9899: =item *
 9900: 
 9901: devalidate($symb) : devalidate temporary spreadsheet calculations,
 9902: forcing spreadsheet to reevaluate the resource scores next time.
 9903: 
 9904: =back
 9905: 
 9906: =head2 Storing/Retreiving Data
 9907: 
 9908: =over 4
 9909: 
 9910: =item *
 9911: 
 9912: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 9913: for this url; hashref needs to be given and should be a \%hashname; the
 9914: remaining args aren't required and if they aren't passed or are '' they will
 9915: be derived from the env
 9916: 
 9917: =item *
 9918: 
 9919: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 9920: uses critical subroutine
 9921: 
 9922: =item *
 9923: 
 9924: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 9925: all args are optional
 9926: 
 9927: =item *
 9928: 
 9929: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 9930: dumps the complete (or key matching regexp) namespace into a hash
 9931: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 9932: normally &store()ed into
 9933: 
 9934: $range should be either an integer '100' (give me the first 100
 9935:                                            matching records)
 9936:               or be  two integers sperated by a - with no spaces
 9937:                  '30-50' (give me the 30th through the 50th matching
 9938:                           records)
 9939: 
 9940: 
 9941: =item *
 9942: 
 9943: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 9944: replaces a &store() version of data with a replacement set of data
 9945: for a particular resource in a namespace passed in the $storehash hash 
 9946: reference
 9947: 
 9948: =item *
 9949: 
 9950: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 9951: works very similar to store/cstore, but all data is stored in a
 9952: temporary location and can be reset using tmpreset, $storehash should
 9953: be a hash reference, returns nothing on success
 9954: 
 9955: =item *
 9956: 
 9957: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 9958: similar to restore, but all data is stored in a temporary location and
 9959: can be reset using tmpreset. Returns a hash of values on success,
 9960: error string otherwise.
 9961: 
 9962: =item *
 9963: 
 9964: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 9965: deltes all keys for $symb form the temporary storage hash.
 9966: 
 9967: =item *
 9968: 
 9969: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9970: reference filled in from namesp ($udom and $uname are optional)
 9971: 
 9972: =item *
 9973: 
 9974: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 9975: namesp ($udom and $uname are optional)
 9976: 
 9977: =item *
 9978: 
 9979: dump($namespace,$udom,$uname,$regexp,$range) : 
 9980: dumps the complete (or key matching regexp) namespace into a hash
 9981: ($udom, $uname, $regexp, $range are optional)
 9982: 
 9983: $range should be either an integer '100' (give me the first 100
 9984:                                            matching records)
 9985:               or be  two integers sperated by a - with no spaces
 9986:                  '30-50' (give me the 30th through the 50th matching
 9987:                           records)
 9988: =item *
 9989: 
 9990: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 9991: $store can be a scalar, an array reference, or if the amount to be 
 9992: incremented is > 1, a hash reference.
 9993: 
 9994: ($udom and $uname are optional)
 9995: 
 9996: =item *
 9997: 
 9998: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 9999: ($udom and $uname are optional)
10000: 
10001: =item *
10002: 
10003: cput($namespace,$storehash,$udom,$uname) : critical put
10004: ($udom and $uname are optional)
10005: 
10006: =item *
10007: 
10008: newput($namespace,$storehash,$udom,$uname) :
10009: 
10010: Attempts to store the items in the $storehash, but only if they don't
10011: currently exist, if this succeeds you can be certain that you have 
10012: successfully created a new key value pair in the $namespace db.
10013: 
10014: 
10015: Args:
10016:  $namespace: name of database to store values to
10017:  $storehash: hashref to store to the db
10018:  $udom: (optional) domain of user containing the db
10019:  $uname: (optional) name of user caontaining the db
10020: 
10021: Returns:
10022:  'ok' -> succeeded in storing all keys of $storehash
10023:  'key_exists: <key>' -> failed to anything out of $storehash, as at
10024:                         least <key> already existed in the db (other
10025:                         requested keys may also already exist)
10026:  'error: <msg>' -> unable to tie the DB or other error occurred
10027:  'con_lost' -> unable to contact request server
10028:  'refused' -> action was not allowed by remote machine
10029: 
10030: 
10031: =item *
10032: 
10033: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10034: reference filled in from namesp (encrypts the return communication)
10035: ($udom and $uname are optional)
10036: 
10037: =item *
10038: 
10039: log($udom,$name,$home,$message) : write to permanent log for user; use
10040: critical subroutine
10041: 
10042: =item *
10043: 
10044: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
10045: array reference filled in from namespace found in domain level on either
10046: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
10047: 
10048: =item *
10049: 
10050: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
10051: domain level either on specified domain server ($uhome) or primary domain 
10052: server ($udom and $uhome are optional)
10053: 
10054: =item * 
10055: 
10056: get_domain_defaults($target_domain) : returns hash with defaults for
10057: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
10058: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
10059: or localauth), initial password or a kerberos realm, language (e.g., en-us).
10060: Values are retrieved from cache (if current), or from domain's configuration.db
10061: (if available), or lastly from values in lonTabs/dns_domain,tab, 
10062: or lonTabs/domain.tab. 
10063: 
10064: %domdefaults = &get_auth_defaults($target_domain);
10065: 
10066: =back
10067: 
10068: =head2 Network Status Functions
10069: 
10070: =over 4
10071: 
10072: =item *
10073: 
10074: dirlist($uri) : return directory list based on URI
10075: 
10076: =item *
10077: 
10078: spareserver() : find server with least workload from spare.tab
10079: 
10080: 
10081: =item *
10082: 
10083: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
10084: if there is no corresponding loncapa host.
10085: 
10086: =back
10087: 
10088: 
10089: =head2 Apache Request
10090: 
10091: =over 4
10092: 
10093: =item *
10094: 
10095: ssi($url,%hash) : server side include, does a complete request cycle on url to
10096: localhost, posts hash
10097: 
10098: =back
10099: 
10100: =head2 Data to String to Data
10101: 
10102: =over 4
10103: 
10104: =item *
10105: 
10106: hash2str(%hash) : convert a hash into a string complete with escaping and '='
10107: and '&' separators, supports elements that are arrayrefs and hashrefs
10108: 
10109: =item *
10110: 
10111: hashref2str($hashref) : convert a hashref into a string complete with
10112: escaping and '=' and '&' separators, supports elements that are
10113: arrayrefs and hashrefs
10114: 
10115: =item *
10116: 
10117: arrayref2str($arrayref) : convert an arrayref into a string complete
10118: with escaping and '&' separators, supports elements that are arrayrefs
10119: and hashrefs
10120: 
10121: =item *
10122: 
10123: str2hash($string) : convert string to hash using unescaping and
10124: splitting on '=' and '&', supports elements that are arrayrefs and
10125: hashrefs
10126: 
10127: =item *
10128: 
10129: str2array($string) : convert string to hash using unescaping and
10130: splitting on '&', supports elements that are arrayrefs and hashrefs
10131: 
10132: =back
10133: 
10134: =head2 Logging Routines
10135: 
10136: =over 4
10137: 
10138: These routines allow one to make log messages in the lonnet.log and
10139: lonnet.perm logfiles.
10140: 
10141: =item *
10142: 
10143: logtouch() : make sure the logfile, lonnet.log, exists
10144: 
10145: =item *
10146: 
10147: logthis() : append message to the normal lonnet.log file, it gets
10148: preiodically rolled over and deleted.
10149: 
10150: =item *
10151: 
10152: logperm() : append a permanent message to lonnet.perm.log, this log
10153: file never gets deleted by any automated portion of the system, only
10154: messages of critical importance should go in here.
10155: 
10156: =back
10157: 
10158: =head2 General File Helper Routines
10159: 
10160: =over 4
10161: 
10162: =item *
10163: 
10164: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10165: (a) files in /uploaded
10166:   (i) If a local copy of the file exists - 
10167:       compares modification date of local copy with last-modified date for 
10168:       definitive version stored on home server for course. If local copy is 
10169:       stale, requests a new version from the home server and stores it. 
10170:       If the original has been removed from the home server, then local copy 
10171:       is unlinked.
10172:   (ii) If local copy does not exist -
10173:       requests the file from the home server and stores it. 
10174:   
10175:   If $caller is 'uploadrep':  
10176:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10177:     for request for files originally uploaded via DOCS. 
10178:      - returns 'ok' if fresh local copy now available, -1 otherwise.
10179:   
10180:   Otherwise:
10181:      This indicates a call from the content generation phase of the request.
10182:      -  returns the entire contents of the file or -1.
10183:      
10184: (b) files in /res
10185:    - returns the entire contents of a file or -1; 
10186:    it properly subscribes to and replicates the file if neccessary.
10187: 
10188: 
10189: =item *
10190: 
10191: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10192:                   reference
10193: 
10194: returns either a stat() list of data about the file or an empty list
10195: if the file doesn't exist or couldn't find out about it (connection
10196: problems or user unknown)
10197: 
10198: =item *
10199: 
10200: filelocation($dir,$file) : returns file system location of a file
10201: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10202: directory that relative $file lookups are to looked in ($dir of /a/dir
10203: and a file of ../bob will become /a/bob)
10204: 
10205: =item *
10206: 
10207: hreflocation($dir,$file) : returns file system location or a URL; same as
10208: filelocation except for hrefs
10209: 
10210: =item *
10211: 
10212: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10213: 
10214: =back
10215: 
10216: =head2 Usererfile file routines (/uploaded*)
10217: 
10218: =over 4
10219: 
10220: =item *
10221: 
10222: userfileupload(): main rotine for putting a file in a user or course's
10223:                   filespace, arguments are,
10224: 
10225:  formname - required - this is the name of the element in $env where the
10226:            filename, and the contents of the file to create/modifed exist
10227:            the filename is in $env{'form.'.$formname.'.filename'} and the
10228:            contents of the file is located in $env{'form.'.$formname}
10229:  coursedoc - if true, store the file in the course of the active role
10230:              of the current user
10231:  subdir - required - subdirectory to put the file in under ../userfiles/
10232:          if undefined, it will be placed in "unknown"
10233: 
10234:  (This routine calls clean_filename() to remove any dangerous
10235:  characters from the filename, and then calls finuserfileupload() to
10236:  complete the transaction)
10237: 
10238:  returns either the url of the uploaded file (/uploaded/....) if successful
10239:  and /adm/notfound.html if unsuccessful
10240: 
10241: =item *
10242: 
10243: clean_filename(): routine for cleaing a filename up for storage in
10244:                  userfile space, argument is:
10245: 
10246:  filename - proposed filename
10247: 
10248: returns: the new clean filename
10249: 
10250: =item *
10251: 
10252: finishuserfileupload(): routine that creaes and sends the file to
10253: userspace, probably shouldn't be called directly
10254: 
10255:   docuname: username or courseid of destination for the file
10256:   docudom: domain of user/course of destination for the file
10257:   formname: same as for userfileupload()
10258:   fname: filename (inculding subdirectories) for the file
10259: 
10260:  returns either the url of the uploaded file (/uploaded/....) if successful
10261:  and /adm/notfound.html if unsuccessful
10262: 
10263: =item *
10264: 
10265: renameuserfile(): renames an existing userfile to a new name
10266: 
10267:   Args:
10268:    docuname: username or courseid of destination for the file
10269:    docudom: domain of user/course of destination for the file
10270:    old: current file name (including any subdirs under userfiles)
10271:    new: desired file name (including any subdirs under userfiles)
10272: 
10273: =item *
10274: 
10275: mkdiruserfile(): creates a directory is a userfiles dir
10276: 
10277:   Args:
10278:    docuname: username or courseid of destination for the file
10279:    docudom: domain of user/course of destination for the file
10280:    dir: dir to create (including any subdirs under userfiles)
10281: 
10282: =item *
10283: 
10284: removeuserfile(): removes a file that exists in userfiles
10285: 
10286:   Args:
10287:    docuname: username or courseid of destination for the file
10288:    docudom: domain of user/course of destination for the file
10289:    fname: filname to delete (including any subdirs under userfiles)
10290: 
10291: =item *
10292: 
10293: removeuploadedurl(): convience function for removeuserfile()
10294: 
10295:   Args:
10296:    url:  a full /uploaded/... url to delete
10297: 
10298: =item * 
10299: 
10300: get_portfile_permissions():
10301:   Args:
10302:     domain: domain of user or course contain the portfolio files
10303:     user: name of user or num of course contain the portfolio files
10304:   Returns:
10305:     hashref of a dump of the proper file_permissions.db
10306:    
10307: 
10308: =item * 
10309: 
10310: get_access_controls():
10311: 
10312: Args:
10313:   current_permissions: the hash ref returned from get_portfile_permissions()
10314:   group: (optional) the group you want the files associated with
10315:   file: (optional) the file you want access info on
10316: 
10317: Returns:
10318:     a hash (keys are file names) of hashes containing
10319:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10320:         values are XML containing access control settings (see below) 
10321: 
10322: Internal notes:
10323: 
10324:  access controls are stored in file_permissions.db as key=value pairs.
10325:     key -> path to file/file_name\0uniqueID:scope_end_start
10326:         where scope -> public,guest,course,group,domains or users.
10327:               end -> UNIX time for end of access (0 -> no end date)
10328:               start -> UNIX time for start of access
10329: 
10330:     value -> XML description of access control
10331:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10332:             <start></start>
10333:             <end></end>
10334: 
10335:             <password></password>  for scope type = guest
10336: 
10337:             <domain></domain>     for scope type = course or group
10338:             <number></number>
10339:             <roles id="">
10340:              <role></role>
10341:              <access></access>
10342:              <section></section>
10343:              <group></group>
10344:             </roles>
10345: 
10346:             <dom></dom>         for scope type = domains
10347: 
10348:             <users>             for scope type = users
10349:              <user>
10350:               <uname></uname>
10351:               <udom></udom>
10352:              </user>
10353:             </users>
10354:            </scope> 
10355:               
10356:  Access data is also aggregated for each file in an additional key=value pair:
10357:  key -> path to file/file_name\0accesscontrol 
10358:  value -> reference to hash
10359:           hash contains key = value pairs
10360:           where key = uniqueID:scope_end_start
10361:                 value = UNIX time record was last updated
10362: 
10363:           Used to improve speed of look-ups of access controls for each file.  
10364:  
10365:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10366: 
10367: modify_access_controls():
10368: 
10369: Modifies access controls for a portfolio file
10370: Args
10371: 1. file name
10372: 2. reference to hash of required changes,
10373: 3. domain
10374: 4. username
10375:   where domain,username are the domain of the portfolio owner 
10376:   (either a user or a course) 
10377: 
10378: Returns:
10379: 1. result of additions or updates ('ok' or 'error', with error message). 
10380: 2. result of deletions ('ok' or 'error', with error message).
10381: 3. reference to hash of any new or updated access controls.
10382: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10383:    key = integer (inbound ID)
10384:    value = uniqueID  
10385: 
10386: =back
10387: 
10388: =head2 HTTP Helper Routines
10389: 
10390: =over 4
10391: 
10392: =item *
10393: 
10394: escape() : unpack non-word characters into CGI-compatible hex codes
10395: 
10396: =item *
10397: 
10398: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10399: 
10400: =back
10401: 
10402: =head1 PRIVATE SUBROUTINES
10403: 
10404: =head2 Underlying communication routines (Shouldn't call)
10405: 
10406: =over 4
10407: 
10408: =item *
10409: 
10410: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10411: 
10412: =item *
10413: 
10414: reply() : uses subreply to send a message to remote machine, logs all failures
10415: 
10416: =item *
10417: 
10418: critical() : passes a critical message to another server; if cannot
10419: get through then place message in connection buffer directory and
10420: returns con_delayed, if incapable of saving message, returns
10421: con_failed
10422: 
10423: =item *
10424: 
10425: reconlonc() : tries to reconnect lonc client processes.
10426: 
10427: =back
10428: 
10429: =head2 Resource Access Logging
10430: 
10431: =over 4
10432: 
10433: =item *
10434: 
10435: flushcourselogs() : flush (save) buffer logs and access logs
10436: 
10437: =item *
10438: 
10439: courselog($what) : save message for course in hash
10440: 
10441: =item *
10442: 
10443: courseacclog($what) : save message for course using &courselog().  Perform
10444: special processing for specific resource types (problems, exams, quizzes, etc).
10445: 
10446: =item *
10447: 
10448: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10449: as a PerlChildExitHandler
10450: 
10451: =back
10452: 
10453: =head2 Other
10454: 
10455: =over 4
10456: 
10457: =item *
10458: 
10459: symblist($mapname,%newhash) : update symbolic storage links
10460: 
10461: =back
10462: 
10463: =cut
10464: 

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