File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1011: download - view: text, annotated - select for diffs
Sat Aug 8 19:55:24 2009 UTC (15 years ago) by raeburn
Branches: MAIN
CVS tags: bz2851, HEAD
Course Requests
- lonnet.pm
  - generation of unique coursenum move to own routine: &generate_coursenum()
  - prefacing of coursenum with number then letter added to second attempt
      to generate an ID (to duplicate change in first attempt in rev 1.674).
  - additional optional argument to &createcourse() - can use a previously
      generated, but unused, coursenum (will be hashkey in a queued course request).

- loncommon.pm
  - additional optional argument to &construct_course() - $cnum, previously
      generated, but unused, coursenum.
  - check_clone() - unrestricted cloning in course's in role's domain now
                    requires creator has ccc privilege in role's domain.

- batchcreatecourse.pm
  - &build_course() - update documentation, and new optional arg
                      previously generated, but unused, coursenum

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1011 2009/08/08 19:55:24 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:         if (defined($spare_server)) {
  722:             my $hostname = &hostname($spare_server);
  723:             if (defined($hostname)) {  
  724: 	        $spare_server = $protocol.'://'.$hostname;
  725:             }
  726:         }
  727:     }
  728:     return $spare_server;
  729: }
  730: 
  731: sub compare_server_load {
  732:     my ($try_server, $spare_server, $lowest_load) = @_;
  733: 
  734:     my $loadans     = &reply('load',    $try_server);
  735:     my $userloadans = &reply('userload',$try_server);
  736: 
  737:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  738: 	next; #didn't get a number from the server
  739:     }
  740: 
  741:     my $load;
  742:     if ($loadans =~ /\d/) {
  743: 	if ($userloadans =~ /\d/) {
  744: 	    #both are numbers, pick the bigger one
  745: 	    $load = ($loadans > $userloadans) ? $loadans 
  746: 		                              : $userloadans;
  747: 	} else {
  748: 	    $load = $loadans;
  749: 	}
  750:     } else {
  751: 	$load = $userloadans;
  752:     }
  753: 
  754:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  755: 	$spare_server = $try_server;
  756: 	$lowest_load  = $load;
  757:     }
  758:     return ($spare_server,$lowest_load);
  759: }
  760: 
  761: # --------------------------- ask offload servers if user already has a session
  762: sub find_existing_session {
  763:     my ($udom,$uname) = @_;
  764:     foreach my $try_server (@{ $spareid{'primary'} },
  765: 			    @{ $spareid{'default'} }) {
  766: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
  767:     }
  768:     return;
  769: }
  770: 
  771: # -------------------------------- ask if server already has a session for user
  772: sub has_user_session {
  773:     my ($lonid,$udom,$uname) = @_;
  774:     my $result = &reply(join(':','userhassession',
  775: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  776:     return 1 if ($result eq 'ok');
  777: 
  778:     return 0;
  779: }
  780: 
  781: # --------------------------------------------- Try to change a user's password
  782: 
  783: sub changepass {
  784:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  785:     $currentpass = &escape($currentpass);
  786:     $newpass     = &escape($newpass);
  787:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  788: 		       $server);
  789:     if (! $answer) {
  790: 	&logthis("No reply on password change request to $server ".
  791: 		 "by $uname in domain $udom.");
  792:     } elsif ($answer =~ "^ok") {
  793:         &logthis("$uname in $udom successfully changed their password ".
  794: 		 "on $server.");
  795:     } elsif ($answer =~ "^pwchange_failure") {
  796: 	&logthis("$uname in $udom was unable to change their password ".
  797: 		 "on $server.  The action was blocked by either lcpasswd ".
  798: 		 "or pwchange");
  799:     } elsif ($answer =~ "^non_authorized") {
  800:         &logthis("$uname in $udom did not get their password correct when ".
  801: 		 "attempting to change it on $server.");
  802:     } elsif ($answer =~ "^auth_mode_error") {
  803:         &logthis("$uname in $udom attempted to change their password despite ".
  804: 		 "not being locally or internally authenticated on $server.");
  805:     } elsif ($answer =~ "^unknown_user") {
  806:         &logthis("$uname in $udom attempted to change their password ".
  807: 		 "on $server but were unable to because $server is not ".
  808: 		 "their home server.");
  809:     } elsif ($answer =~ "^refused") {
  810: 	&logthis("$server refused to change $uname in $udom password because ".
  811: 		 "it was sent an unencrypted request to change the password.");
  812:     }
  813:     return $answer;
  814: }
  815: 
  816: # ----------------------- Try to determine user's current authentication scheme
  817: 
  818: sub queryauthenticate {
  819:     my ($uname,$udom)=@_;
  820:     my $uhome=&homeserver($uname,$udom);
  821:     if (!$uhome) {
  822: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  823: 	return 'no_host';
  824:     }
  825:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  826:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  827: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  828:     }
  829:     return $answer;
  830: }
  831: 
  832: # --------- Try to authenticate user from domain's lib servers (first this one)
  833: 
  834: sub authenticate {
  835:     my ($uname,$upass,$udom,$checkdefauth)=@_;
  836:     $upass=&escape($upass);
  837:     $uname= &LONCAPA::clean_username($uname);
  838:     my $uhome=&homeserver($uname,$udom,1);
  839:     my $newhome;
  840:     if ((!$uhome) || ($uhome eq 'no_host')) {
  841: # Maybe the machine was offline and only re-appeared again recently?
  842:         &reconlonc();
  843: # One more
  844: 	$uhome=&homeserver($uname,$udom,1);
  845:         if (($uhome eq 'no_host') && $checkdefauth) {
  846:             if (defined(&domain($udom,'primary'))) {
  847:                 $newhome=&domain($udom,'primary');
  848:             }
  849:             if ($newhome ne '') {
  850:                 $uhome = $newhome;
  851:             }
  852:         }
  853: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  854: 	    &logthis("User $uname at $udom is unknown in authenticate");
  855: 	    return 'no_host';
  856:         }
  857:     }
  858:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
  859:     if ($answer eq 'authorized') {
  860:         if ($newhome) {
  861:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
  862:             return 'no_account_on_host'; 
  863:         } else {
  864:             &logthis("User $uname at $udom authorized by $uhome");
  865:             return $uhome;
  866:         }
  867:     }
  868:     if ($answer eq 'non_authorized') {
  869: 	&logthis("User $uname at $udom rejected by $uhome");
  870: 	return 'no_host'; 
  871:     }
  872:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  873:     return 'no_host';
  874: }
  875: 
  876: # ---------------------- Find the homebase for a user from domain's lib servers
  877: 
  878: my %homecache;
  879: sub homeserver {
  880:     my ($uname,$udom,$ignoreBadCache)=@_;
  881:     my $index="$uname:$udom";
  882: 
  883:     if (exists($homecache{$index})) { return $homecache{$index}; }
  884: 
  885:     my %servers = &get_servers($udom,'library');
  886:     foreach my $tryserver (keys(%servers)) {
  887:         next if ($ignoreBadCache ne 'true' && 
  888: 		 exists($badServerCache{$tryserver}));
  889: 
  890: 	my $answer=reply("home:$udom:$uname",$tryserver);
  891: 	if ($answer eq 'found') {
  892: 	    delete($badServerCache{$tryserver}); 
  893: 	    return $homecache{$index}=$tryserver;
  894: 	} elsif ($answer eq 'no_host') {
  895: 	    $badServerCache{$tryserver}=1;
  896: 	}
  897:     }    
  898:     return 'no_host';
  899: }
  900: 
  901: # ------------------------------------- Find the usernames behind a list of IDs
  902: 
  903: sub idget {
  904:     my ($udom,@ids)=@_;
  905:     my %returnhash=();
  906:     
  907:     my %servers = &get_servers($udom,'library');
  908:     foreach my $tryserver (keys(%servers)) {
  909: 	my $idlist=join('&',@ids);
  910: 	$idlist=~tr/A-Z/a-z/; 
  911: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  912: 	my @answer=();
  913: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  914: 	    @answer=split(/\&/,$reply);
  915: 	}                    ;
  916: 	my $i;
  917: 	for ($i=0;$i<=$#ids;$i++) {
  918: 	    if ($answer[$i]) {
  919: 		$returnhash{$ids[$i]}=$answer[$i];
  920: 	    } 
  921: 	}
  922:     } 
  923:     return %returnhash;
  924: }
  925: 
  926: # ------------------------------------- Find the IDs behind a list of usernames
  927: 
  928: sub idrget {
  929:     my ($udom,@unames)=@_;
  930:     my %returnhash=();
  931:     foreach my $uname (@unames) {
  932:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  933:     }
  934:     return %returnhash;
  935: }
  936: 
  937: # ------------------------------- Store away a list of names and associated IDs
  938: 
  939: sub idput {
  940:     my ($udom,%ids)=@_;
  941:     my %servers=();
  942:     foreach my $uname (keys(%ids)) {
  943: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  944:         my $uhom=&homeserver($uname,$udom);
  945:         if ($uhom ne 'no_host') {
  946:             my $id=&escape($ids{$uname});
  947:             $id=~tr/A-Z/a-z/;
  948:             my $esc_unam=&escape($uname);
  949: 	    if ($servers{$uhom}) {
  950: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  951:             } else {
  952:                 $servers{$uhom}=$id.'='.$esc_unam;
  953:             }
  954:         }
  955:     }
  956:     foreach my $server (keys(%servers)) {
  957:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  958:     }
  959: }
  960: 
  961: # ------------------------------------------- get items from domain db files   
  962: 
  963: sub get_dom {
  964:     my ($namespace,$storearr,$udom,$uhome)=@_;
  965:     my $items='';
  966:     foreach my $item (@$storearr) {
  967:         $items.=&escape($item).'&';
  968:     }
  969:     $items=~s/\&$//;
  970:     if (!$udom) {
  971:         $udom=$env{'user.domain'};
  972:         if (defined(&domain($udom,'primary'))) {
  973:             $uhome=&domain($udom,'primary');
  974:         } else {
  975:             undef($uhome);
  976:         }
  977:     } else {
  978:         if (!$uhome) {
  979:             if (defined(&domain($udom,'primary'))) {
  980:                 $uhome=&domain($udom,'primary');
  981:             }
  982:         }
  983:     }
  984:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  985:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  986:         my %returnhash;
  987:         if ($rep eq '' || $rep =~ /^error: 2 /) {
  988:             return %returnhash;
  989:         }
  990:         my @pairs=split(/\&/,$rep);
  991:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  992:             return @pairs;
  993:         }
  994:         my $i=0;
  995:         foreach my $item (@$storearr) {
  996:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  997:             $i++;
  998:         }
  999:         return %returnhash;
 1000:     } else {
 1001:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1002:     }
 1003: }
 1004: 
 1005: # -------------------------------------------- put items in domain db files 
 1006: 
 1007: sub put_dom {
 1008:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1009:     if (!$udom) {
 1010:         $udom=$env{'user.domain'};
 1011:         if (defined(&domain($udom,'primary'))) {
 1012:             $uhome=&domain($udom,'primary');
 1013:         } else {
 1014:             undef($uhome);
 1015:         }
 1016:     } else {
 1017:         if (!$uhome) {
 1018:             if (defined(&domain($udom,'primary'))) {
 1019:                 $uhome=&domain($udom,'primary');
 1020:             }
 1021:         }
 1022:     } 
 1023:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1024:         my $items='';
 1025:         foreach my $item (keys(%$storehash)) {
 1026:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1027:         }
 1028:         $items=~s/\&$//;
 1029:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1030:     } else {
 1031:         &logthis("put_dom failed - no homeserver and/or domain");
 1032:     }
 1033: }
 1034: 
 1035: sub retrieve_inst_usertypes {
 1036:     my ($udom) = @_;
 1037:     my (%returnhash,@order);
 1038:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1039:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1040:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1041:         %returnhash = %{$domdefs{'inststatustypes'}};
 1042:         @order = @{$domdefs{'inststatusorder'}};
 1043:     } else {
 1044:         if (defined(&domain($udom,'primary'))) {
 1045:             my $uhome=&domain($udom,'primary');
 1046:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1047:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1048:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1049:                 return (\%returnhash,\@order);
 1050:             }
 1051:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1052:             my @pairs=split(/\&/,$hashitems);
 1053:             foreach my $item (@pairs) {
 1054:                 my ($key,$value)=split(/=/,$item,2);
 1055:                 $key = &unescape($key);
 1056:                 next if ($key =~ /^error: 2 /);
 1057:                 $returnhash{$key}=&thaw_unescape($value);
 1058:             }
 1059:             my @esc_order = split(/\&/,$orderitems);
 1060:             foreach my $item (@esc_order) {
 1061:                 push(@order,&unescape($item));
 1062:             }
 1063:         } else {
 1064:             &logthis("get_dom failed - no primary domain server for $udom");
 1065:         }
 1066:     }
 1067:     return (\%returnhash,\@order);
 1068: }
 1069: 
 1070: sub is_domainimage {
 1071:     my ($url) = @_;
 1072:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1073:         if (&domain($1) ne '') {
 1074:             return '1';
 1075:         }
 1076:     }
 1077:     return;
 1078: }
 1079: 
 1080: sub inst_directory_query {
 1081:     my ($srch) = @_;
 1082:     my $udom = $srch->{'srchdomain'};
 1083:     my %results;
 1084:     my $homeserver = &domain($udom,'primary');
 1085:     my $outcome;
 1086:     if ($homeserver ne '') {
 1087: 	my $queryid=&reply("querysend:instdirsearch:".
 1088: 			   &escape($srch->{'srchby'}).':'.
 1089: 			   &escape($srch->{'srchterm'}).':'.
 1090: 			   &escape($srch->{'srchtype'}),$homeserver);
 1091: 	my $host=&hostname($homeserver);
 1092: 	if ($queryid !~/^\Q$host\E\_/) {
 1093: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1094: 	    return;
 1095: 	}
 1096: 	my $response = &get_query_reply($queryid);
 1097: 	my $maxtries = 5;
 1098: 	my $tries = 1;
 1099: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1100: 	    $response = &get_query_reply($queryid);
 1101: 	    $tries ++;
 1102: 	}
 1103: 
 1104:         if (!&error($response) && $response ne 'refused') {
 1105:             if ($response eq 'unavailable') {
 1106:                 $outcome = $response;
 1107:             } else {
 1108:                 $outcome = 'ok';
 1109:                 my @matches = split(/\n/,$response);
 1110:                 foreach my $match (@matches) {
 1111:                     my ($key,$value) = split(/=/,$match);
 1112:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1113:                 }
 1114:             }
 1115:         }
 1116:     }
 1117:     return ($outcome,%results);
 1118: }
 1119: 
 1120: sub usersearch {
 1121:     my ($srch) = @_;
 1122:     my $dom = $srch->{'srchdomain'};
 1123:     my %results;
 1124:     my %libserv = &all_library();
 1125:     my $query = 'usersearch';
 1126:     foreach my $tryserver (keys(%libserv)) {
 1127:         if (&host_domain($tryserver) eq $dom) {
 1128:             my $host=&hostname($tryserver);
 1129:             my $queryid=
 1130:                 &reply("querysend:".&escape($query).':'.
 1131:                        &escape($srch->{'srchby'}).':'.
 1132:                        &escape($srch->{'srchtype'}).':'.
 1133:                        &escape($srch->{'srchterm'}),$tryserver);
 1134:             if ($queryid !~/^\Q$host\E\_/) {
 1135:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1136:                 next;
 1137:             }
 1138:             my $reply = &get_query_reply($queryid);
 1139:             my $maxtries = 1;
 1140:             my $tries = 1;
 1141:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1142:                 $reply = &get_query_reply($queryid);
 1143:                 $tries ++;
 1144:             }
 1145:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1146:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1147:             } else {
 1148:                 my @matches;
 1149:                 if ($reply =~ /\n/) {
 1150:                     @matches = split(/\n/,$reply);
 1151:                 } else {
 1152:                     @matches = split(/\&/,$reply);
 1153:                 }
 1154:                 foreach my $match (@matches) {
 1155:                     my ($uname,$udom,%userhash);
 1156:                     foreach my $entry (split(/:/,$match)) {
 1157:                         my ($key,$value) =
 1158:                             map {&unescape($_);} split(/=/,$entry);
 1159:                         $userhash{$key} = $value;
 1160:                         if ($key eq 'username') {
 1161:                             $uname = $value;
 1162:                         } elsif ($key eq 'domain') {
 1163:                             $udom = $value;
 1164:                         }
 1165:                     }
 1166:                     $results{$uname.':'.$udom} = \%userhash;
 1167:                 }
 1168:             }
 1169:         }
 1170:     }
 1171:     return %results;
 1172: }
 1173: 
 1174: sub get_instuser {
 1175:     my ($udom,$uname,$id) = @_;
 1176:     my $homeserver = &domain($udom,'primary');
 1177:     my ($outcome,%results);
 1178:     if ($homeserver ne '') {
 1179:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1180:                            &escape($id).':'.&escape($udom),$homeserver);
 1181:         my $host=&hostname($homeserver);
 1182:         if ($queryid !~/^\Q$host\E\_/) {
 1183:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1184:             return;
 1185:         }
 1186:         my $response = &get_query_reply($queryid);
 1187:         my $maxtries = 5;
 1188:         my $tries = 1;
 1189:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1190:             $response = &get_query_reply($queryid);
 1191:             $tries ++;
 1192:         }
 1193:         if (!&error($response) && $response ne 'refused') {
 1194:             if ($response eq 'unavailable') {
 1195:                 $outcome = $response;
 1196:             } else {
 1197:                 $outcome = 'ok';
 1198:                 my @matches = split(/\n/,$response);
 1199:                 foreach my $match (@matches) {
 1200:                     my ($key,$value) = split(/=/,$match);
 1201:                     $results{&unescape($key)} = &thaw_unescape($value);
 1202:                 }
 1203:             }
 1204:         }
 1205:     }
 1206:     my %userinfo;
 1207:     if (ref($results{$uname}) eq 'HASH') {
 1208:         %userinfo = %{$results{$uname}};
 1209:     } 
 1210:     return ($outcome,%userinfo);
 1211: }
 1212: 
 1213: sub inst_rulecheck {
 1214:     my ($udom,$uname,$id,$item,$rules) = @_;
 1215:     my %returnhash;
 1216:     if ($udom ne '') {
 1217:         if (ref($rules) eq 'ARRAY') {
 1218:             @{$rules} = map {&escape($_);} (@{$rules});
 1219:             my $rulestr = join(':',@{$rules});
 1220:             my $homeserver=&domain($udom,'primary');
 1221:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1222:                 my $response;
 1223:                 if ($item eq 'username') {                
 1224:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1225:                                               ':'.&escape($uname).':'.$rulestr,
 1226:                                               $homeserver));
 1227:                 } elsif ($item eq 'id') {
 1228:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1229:                                               ':'.&escape($id).':'.$rulestr,
 1230:                                               $homeserver));
 1231:                 } elsif ($item eq 'selfcreate') {
 1232:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1233:                                                &escape($udom).':'.&escape($uname).
 1234:                                               ':'.$rulestr,$homeserver));
 1235:                 }
 1236:                 if ($response ne 'refused') {
 1237:                     my @pairs=split(/\&/,$response);
 1238:                     foreach my $item (@pairs) {
 1239:                         my ($key,$value)=split(/=/,$item,2);
 1240:                         $key = &unescape($key);
 1241:                         next if ($key =~ /^error: 2 /);
 1242:                         $returnhash{$key}=&thaw_unescape($value);
 1243:                     }
 1244:                 }
 1245:             }
 1246:         }
 1247:     }
 1248:     return %returnhash;
 1249: }
 1250: 
 1251: sub inst_userrules {
 1252:     my ($udom,$check) = @_;
 1253:     my (%ruleshash,@ruleorder);
 1254:     if ($udom ne '') {
 1255:         my $homeserver=&domain($udom,'primary');
 1256:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1257:             my $response;
 1258:             if ($check eq 'id') {
 1259:                 $response=&reply('instidrules:'.&escape($udom),
 1260:                                  $homeserver);
 1261:             } elsif ($check eq 'email') {
 1262:                 $response=&reply('instemailrules:'.&escape($udom),
 1263:                                  $homeserver);
 1264:             } else {
 1265:                 $response=&reply('instuserrules:'.&escape($udom),
 1266:                                  $homeserver);
 1267:             }
 1268:             if (($response ne 'refused') && ($response ne 'error') && 
 1269:                 ($response ne 'unknown_cmd') && 
 1270:                 ($response ne 'no_such_host')) {
 1271:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1272:                 my @pairs=split(/\&/,$hashitems);
 1273:                 foreach my $item (@pairs) {
 1274:                     my ($key,$value)=split(/=/,$item,2);
 1275:                     $key = &unescape($key);
 1276:                     next if ($key =~ /^error: 2 /);
 1277:                     $ruleshash{$key}=&thaw_unescape($value);
 1278:                 }
 1279:                 my @esc_order = split(/\&/,$orderitems);
 1280:                 foreach my $item (@esc_order) {
 1281:                     push(@ruleorder,&unescape($item));
 1282:                 }
 1283:             }
 1284:         }
 1285:     }
 1286:     return (\%ruleshash,\@ruleorder);
 1287: }
 1288: 
 1289: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1290: 
 1291: sub get_domain_defaults {
 1292:     my ($domain) = @_;
 1293:     my $cachetime = 60*60*24;
 1294:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1295:     if (defined($cached)) {
 1296:         if (ref($result) eq 'HASH') {
 1297:             return %{$result};
 1298:         }
 1299:     }
 1300:     my %domdefaults;
 1301:     my %domconfig =
 1302:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1303:                                   'requestcourses','inststatus'],$domain);
 1304:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1305:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1306:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1307:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1308:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1309:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1310:     } else {
 1311:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1312:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1313:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1314:     }
 1315:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1316:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1317:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1318:         } else {
 1319:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1320:         } 
 1321:         my @usertools = ('aboutme','blog','portfolio');
 1322:         foreach my $item (@usertools) {
 1323:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1324:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1325:             }
 1326:         }
 1327:     }
 1328:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1329:         foreach my $item ('official','unofficial','community') {
 1330:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1331:         }
 1332:     }
 1333:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 1334:         foreach my $item ('inststatustypes','inststatusorder') {
 1335:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 1336:         }
 1337:     }
 1338:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1339:                                   $cachetime);
 1340:     return %domdefaults;
 1341: }
 1342: 
 1343: # --------------------------------------------------- Assign a key to a student
 1344: 
 1345: sub assign_access_key {
 1346: #
 1347: # a valid key looks like uname:udom#comments
 1348: # comments are being appended
 1349: #
 1350:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1351:     $kdom=
 1352:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1353:     $knum=
 1354:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1355:     $cdom=
 1356:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1357:     $cnum=
 1358:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1359:     $udom=$env{'user.name'} unless (defined($udom));
 1360:     $uname=$env{'user.domain'} unless (defined($uname));
 1361:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1362:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1363:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1364:                                                   # assigned to this person
 1365:                                                   # - this should not happen,
 1366:                                                   # unless something went wrong
 1367:                                                   # the first time around
 1368: # ready to assign
 1369:         $logentry=$1.'; '.$logentry;
 1370:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1371:                                                  $kdom,$knum) eq 'ok') {
 1372: # key now belongs to user
 1373: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1374:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1375:                 &appenv({'environment.'.$envkey => $ckey});
 1376:                 return 'ok';
 1377:             } else {
 1378:                 return 
 1379:   'error: Count not permanently assign key, will need to be re-entered later.';
 1380: 	    }
 1381:         } else {
 1382:             return 'error: Could not assign key, try again later.';
 1383:         }
 1384:     } elsif (!$existing{$ckey}) {
 1385: # the key does not exist
 1386: 	return 'error: The key does not exist';
 1387:     } else {
 1388: # the key is somebody else's
 1389: 	return 'error: The key is already in use';
 1390:     }
 1391: }
 1392: 
 1393: # ------------------------------------------ put an additional comment on a key
 1394: 
 1395: sub comment_access_key {
 1396: #
 1397: # a valid key looks like uname:udom#comments
 1398: # comments are being appended
 1399: #
 1400:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1401:     $cdom=
 1402:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1403:     $cnum=
 1404:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1405:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1406:     if ($existing{$ckey}) {
 1407:         $existing{$ckey}.='; '.$logentry;
 1408: # ready to assign
 1409:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1410:                                                  $cdom,$cnum) eq 'ok') {
 1411: 	    return 'ok';
 1412:         } else {
 1413: 	    return 'error: Count not store comment.';
 1414:         }
 1415:     } else {
 1416: # the key does not exist
 1417: 	return 'error: The key does not exist';
 1418:     }
 1419: }
 1420: 
 1421: # ------------------------------------------------------ Generate a set of keys
 1422: 
 1423: sub generate_access_keys {
 1424:     my ($number,$cdom,$cnum,$logentry)=@_;
 1425:     $cdom=
 1426:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1427:     $cnum=
 1428:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1429:     unless (&allowed('mky',$cdom)) { return 0; }
 1430:     unless (($cdom) && ($cnum)) { return 0; }
 1431:     if ($number>10000) { return 0; }
 1432:     sleep(2); # make sure don't get same seed twice
 1433:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1434:     my $total=0;
 1435:     for (my $i=1;$i<=$number;$i++) {
 1436:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1437:                   sprintf("%lx",int(100000*rand)).'-'.
 1438:                   sprintf("%lx",int(100000*rand));
 1439:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1440:        $newkey=~s/0/h/g; # and also 0 and O
 1441:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1442:        if ($existing{$newkey}) {
 1443:            $i--;
 1444:        } else {
 1445: 	  if (&put('accesskeys',
 1446:               { $newkey => '# generated '.localtime().
 1447:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1448:                            '; '.$logentry },
 1449: 		   $cdom,$cnum) eq 'ok') {
 1450:               $total++;
 1451: 	  }
 1452:        }
 1453:     }
 1454:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1455:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1456:     return $total;
 1457: }
 1458: 
 1459: # ------------------------------------------------------- Validate an accesskey
 1460: 
 1461: sub validate_access_key {
 1462:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1463:     $cdom=
 1464:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1465:     $cnum=
 1466:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1467:     $udom=$env{'user.domain'} unless (defined($udom));
 1468:     $uname=$env{'user.name'} unless (defined($uname));
 1469:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1470:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1471: }
 1472: 
 1473: # ------------------------------------- Find the section of student in a course
 1474: sub devalidate_getsection_cache {
 1475:     my ($udom,$unam,$courseid)=@_;
 1476:     my $hashid="$udom:$unam:$courseid";
 1477:     &devalidate_cache_new('getsection',$hashid);
 1478: }
 1479: 
 1480: sub courseid_to_courseurl {
 1481:     my ($courseid) = @_;
 1482:     #already url style courseid
 1483:     return $courseid if ($courseid =~ m{^/});
 1484: 
 1485:     if (exists($env{'course.'.$courseid.'.num'})) {
 1486: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1487: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1488: 	return "/$cdom/$cnum";
 1489:     }
 1490: 
 1491:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1492:     if (exists($courseinfo{'num'})) {
 1493: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1494:     }
 1495: 
 1496:     return undef;
 1497: }
 1498: 
 1499: sub getsection {
 1500:     my ($udom,$unam,$courseid)=@_;
 1501:     my $cachetime=1800;
 1502: 
 1503:     my $hashid="$udom:$unam:$courseid";
 1504:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1505:     if (defined($cached)) { return $result; }
 1506: 
 1507:     my %Pending; 
 1508:     my %Expired;
 1509:     #
 1510:     # Each role can either have not started yet (pending), be active, 
 1511:     #    or have expired.
 1512:     #
 1513:     # If there is an active role, we are done.
 1514:     #
 1515:     # If there is more than one role which has not started yet, 
 1516:     #     choose the one which will start sooner
 1517:     # If there is one role which has not started yet, return it.
 1518:     #
 1519:     # If there is more than one expired role, choose the one which ended last.
 1520:     # If there is a role which has expired, return it.
 1521:     #
 1522:     $courseid = &courseid_to_courseurl($courseid);
 1523:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1524:     foreach my $key (keys(%roleshash)) {
 1525:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1526:         my $section=$1;
 1527:         if ($key eq $courseid.'_st') { $section=''; }
 1528:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1529:         my $now=time;
 1530:         if (defined($end) && $end && ($now > $end)) {
 1531:             $Expired{$end}=$section;
 1532:             next;
 1533:         }
 1534:         if (defined($start) && $start && ($now < $start)) {
 1535:             $Pending{$start}=$section;
 1536:             next;
 1537:         }
 1538:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1539:     }
 1540:     #
 1541:     # Presumedly there will be few matching roles from the above
 1542:     # loop and the sorting time will be negligible.
 1543:     if (scalar(keys(%Pending))) {
 1544:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1545:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1546:     } 
 1547:     if (scalar(keys(%Expired))) {
 1548:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1549:         my $time = pop(@sorted);
 1550:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1551:     }
 1552:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1553: }
 1554: 
 1555: sub save_cache {
 1556:     &purge_remembered();
 1557:     #&Apache::loncommon::validate_page();
 1558:     undef(%env);
 1559:     undef($env_loaded);
 1560: }
 1561: 
 1562: my $to_remember=-1;
 1563: my %remembered;
 1564: my %accessed;
 1565: my $kicks=0;
 1566: my $hits=0;
 1567: sub make_key {
 1568:     my ($name,$id) = @_;
 1569:     if (length($id) > 65 
 1570: 	&& length(&escape($id)) > 200) {
 1571: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1572:     }
 1573:     return &escape($name.':'.$id);
 1574: }
 1575: 
 1576: sub devalidate_cache_new {
 1577:     my ($name,$id,$debug) = @_;
 1578:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1579:     $id=&make_key($name,$id);
 1580:     $memcache->delete($id);
 1581:     delete($remembered{$id});
 1582:     delete($accessed{$id});
 1583: }
 1584: 
 1585: sub is_cached_new {
 1586:     my ($name,$id,$debug) = @_;
 1587:     $id=&make_key($name,$id);
 1588:     if (exists($remembered{$id})) {
 1589: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1590: 	$accessed{$id}=[&gettimeofday()];
 1591: 	$hits++;
 1592: 	return ($remembered{$id},1);
 1593:     }
 1594:     my $value = $memcache->get($id);
 1595:     if (!(defined($value))) {
 1596: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1597: 	return (undef,undef);
 1598:     }
 1599:     if ($value eq '__undef__') {
 1600: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1601: 	$value=undef;
 1602:     }
 1603:     &make_room($id,$value,$debug);
 1604:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1605:     return ($value,1);
 1606: }
 1607: 
 1608: sub do_cache_new {
 1609:     my ($name,$id,$value,$time,$debug) = @_;
 1610:     $id=&make_key($name,$id);
 1611:     my $setvalue=$value;
 1612:     if (!defined($setvalue)) {
 1613: 	$setvalue='__undef__';
 1614:     }
 1615:     if (!defined($time) ) {
 1616: 	$time=600;
 1617:     }
 1618:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1619:     my $result = $memcache->set($id,$setvalue,$time);
 1620:     if (! $result) {
 1621: 	&logthis("caching of id -> $id  failed");
 1622: 	$memcache->disconnect_all();
 1623:     }
 1624:     # need to make a copy of $value
 1625:     &make_room($id,$value,$debug);
 1626:     return $value;
 1627: }
 1628: 
 1629: sub make_room {
 1630:     my ($id,$value,$debug)=@_;
 1631: 
 1632:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1633:                                     : $value;
 1634:     if ($to_remember<0) { return; }
 1635:     $accessed{$id}=[&gettimeofday()];
 1636:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1637:     my $to_kick;
 1638:     my $max_time=0;
 1639:     foreach my $other (keys(%accessed)) {
 1640: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1641: 	    $to_kick=$other;
 1642: 	    $max_time=&tv_interval($accessed{$other});
 1643: 	}
 1644:     }
 1645:     delete($remembered{$to_kick});
 1646:     delete($accessed{$to_kick});
 1647:     $kicks++;
 1648:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1649:     return;
 1650: }
 1651: 
 1652: sub purge_remembered {
 1653:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1654:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1655:     undef(%remembered);
 1656:     undef(%accessed);
 1657: }
 1658: # ------------------------------------- Read an entry from a user's environment
 1659: 
 1660: sub userenvironment {
 1661:     my ($udom,$unam,@what)=@_;
 1662:     my $items;
 1663:     foreach my $item (@what) {
 1664:         $items.=&escape($item).'&';
 1665:     }
 1666:     $items=~s/\&$//;
 1667:     my %returnhash=();
 1668:     my $uhome = &homeserver($unam,$udom);
 1669:     unless ($uhome eq 'no_host') {
 1670:         my @answer=split(/\&/, 
 1671:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 1672:         my $i;
 1673:         for ($i=0;$i<=$#what;$i++) {
 1674: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 1675:         }
 1676:     }
 1677:     return %returnhash;
 1678: }
 1679: 
 1680: # ---------------------------------------------------------- Get a studentphoto
 1681: sub studentphoto {
 1682:     my ($udom,$unam,$ext) = @_;
 1683:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1684:     if (defined($env{'request.course.id'})) {
 1685:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1686:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1687:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1688:             } else {
 1689:                 my ($result,$perm_reqd)=
 1690: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1691:                 if ($result eq 'ok') {
 1692:                     if (!($perm_reqd eq 'yes')) {
 1693:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1694:                     }
 1695:                 }
 1696:             }
 1697:         }
 1698:     } else {
 1699:         my ($result,$perm_reqd) = 
 1700: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1701:         if ($result eq 'ok') {
 1702:             if (!($perm_reqd eq 'yes')) {
 1703:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1704:             }
 1705:         }
 1706:     }
 1707:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1708: }
 1709: 
 1710: sub retrievestudentphoto {
 1711:     my ($udom,$unam,$ext,$type) = @_;
 1712:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1713:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1714:     if ($ret eq 'ok') {
 1715:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1716:         if ($type eq 'thumbnail') {
 1717:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1718:         }
 1719:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1720:         return $tokenurl;
 1721:     } else {
 1722:         if ($type eq 'thumbnail') {
 1723:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1724:         } else { 
 1725:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1726:         }
 1727:     }
 1728: }
 1729: 
 1730: # -------------------------------------------------------------------- New chat
 1731: 
 1732: sub chatsend {
 1733:     my ($newentry,$anon,$group)=@_;
 1734:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1735:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1736:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1737:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1738: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1739: 		   &escape($newentry)).':'.$group,$chome);
 1740: }
 1741: 
 1742: # ------------------------------------------ Find current version of a resource
 1743: 
 1744: sub getversion {
 1745:     my $fname=&clutter(shift);
 1746:     unless ($fname=~/^\/res\//) { return -1; }
 1747:     return &currentversion(&filelocation('',$fname));
 1748: }
 1749: 
 1750: sub currentversion {
 1751:     my $fname=shift;
 1752:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1753:     if (defined($cached)) { return $result; }
 1754:     my $author=$fname;
 1755:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1756:     my ($udom,$uname)=split(/\//,$author);
 1757:     my $home=homeserver($uname,$udom);
 1758:     if ($home eq 'no_host') { 
 1759:         return -1; 
 1760:     }
 1761:     my $answer=reply("currentversion:$fname",$home);
 1762:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1763: 	return -1;
 1764:     }
 1765:     return &do_cache_new('resversion',$fname,$answer,600);
 1766: }
 1767: 
 1768: # ----------------------------- Subscribe to a resource, return URL if possible
 1769: 
 1770: sub subscribe {
 1771:     my $fname=shift;
 1772:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1773:     $fname=~s/[\n\r]//g;
 1774:     my $author=$fname;
 1775:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1776:     my ($udom,$uname)=split(/\//,$author);
 1777:     my $home=homeserver($uname,$udom);
 1778:     if ($home eq 'no_host') {
 1779:         return 'not_found';
 1780:     }
 1781:     my $answer=reply("sub:$fname",$home);
 1782:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1783: 	$answer.=' by '.$home;
 1784:     }
 1785:     return $answer;
 1786: }
 1787:     
 1788: # -------------------------------------------------------------- Replicate file
 1789: 
 1790: sub repcopy {
 1791:     my $filename=shift;
 1792:     $filename=~s/\/+/\//g;
 1793:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1794:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1795:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1796: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1797: 	return &repcopy_userfile($filename);
 1798:     }
 1799:     $filename=~s/[\n\r]//g;
 1800:     my $transname="$filename.in.transfer";
 1801: # FIXME: this should flock
 1802:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1803:     my $remoteurl=subscribe($filename);
 1804:     if ($remoteurl =~ /^con_lost by/) {
 1805: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1806:            return 'unavailable';
 1807:     } elsif ($remoteurl eq 'not_found') {
 1808: 	   #&logthis("Subscribe returned not_found: $filename");
 1809: 	   return 'not_found';
 1810:     } elsif ($remoteurl =~ /^rejected by/) {
 1811: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1812:            return 'forbidden';
 1813:     } elsif ($remoteurl eq 'directory') {
 1814:            return 'ok';
 1815:     } else {
 1816:         my $author=$filename;
 1817:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1818:         my ($udom,$uname)=split(/\//,$author);
 1819:         my $home=homeserver($uname,$udom);
 1820:         unless ($home eq $perlvar{'lonHostID'}) {
 1821:            my @parts=split(/\//,$filename);
 1822:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1823:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1824:                &logthis("Malconfiguration for replication: $filename");
 1825: 	       return 'bad_request';
 1826:            }
 1827:            my $count;
 1828:            for ($count=5;$count<$#parts;$count++) {
 1829:                $path.="/$parts[$count]";
 1830:                if ((-e $path)!=1) {
 1831: 		   mkdir($path,0777);
 1832:                }
 1833:            }
 1834:            my $ua=new LWP::UserAgent;
 1835:            my $request=new HTTP::Request('GET',"$remoteurl");
 1836:            my $response=$ua->request($request,$transname);
 1837:            if ($response->is_error()) {
 1838: 	       unlink($transname);
 1839:                my $message=$response->status_line;
 1840:                &logthis("<font color=\"blue\">WARNING:"
 1841:                        ." LWP get: $message: $filename</font>");
 1842:                return 'unavailable';
 1843:            } else {
 1844: 	       if ($remoteurl!~/\.meta$/) {
 1845:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1846:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1847:                   if ($mresponse->is_error()) {
 1848: 		      unlink($filename.'.meta');
 1849:                       &logthis(
 1850:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1851:                   }
 1852: 	       }
 1853:                rename($transname,$filename);
 1854:                return 'ok';
 1855:            }
 1856:        }
 1857:     }
 1858: }
 1859: 
 1860: # ------------------------------------------------ Get server side include body
 1861: sub ssi_body {
 1862:     my ($filelink,%form)=@_;
 1863:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1864:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1865:     }
 1866:     my $output='';
 1867:     my $response;
 1868:     if ($filelink=~/^https?\:/) {
 1869:        ($output,$response)=&externalssi($filelink);
 1870:     } else {
 1871:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 1872:        $filelink .= 'inhibitmenu=yes';
 1873:        ($output,$response)=&ssi($filelink,%form);
 1874:     }
 1875:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1876:     $output=~s/^.*?\<body[^\>]*\>//si;
 1877:     $output=~s/\<\/body\s*\>.*?$//si;
 1878:     if (wantarray) {
 1879:         return ($output, $response);
 1880:     } else {
 1881:         return $output;
 1882:     }
 1883: }
 1884: 
 1885: # --------------------------------------------------------- Server Side Include
 1886: 
 1887: sub absolute_url {
 1888:     my ($host_name) = @_;
 1889:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1890:     if ($host_name eq '') {
 1891: 	$host_name = $ENV{'SERVER_NAME'};
 1892:     }
 1893:     return $protocol.$host_name;
 1894: }
 1895: 
 1896: #
 1897: #   Server side include.
 1898: # Parameters:
 1899: #  fn     Possibly encrypted resource name/id.
 1900: #  form   Hash that describes how the rendering should be done
 1901: #         and other things.
 1902: # Returns:
 1903: #   Scalar context: The content of the response.
 1904: #   Array context:  2 element list of the content and the full response object.
 1905: #     
 1906: sub ssi {
 1907: 
 1908:     my ($fn,%form)=@_;
 1909:     my $ua=new LWP::UserAgent;
 1910:     my $request;
 1911: 
 1912:     $form{'no_update_last_known'}=1;
 1913:     &Apache::lonenc::check_encrypt(\$fn);
 1914:     if (%form) {
 1915:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1916:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 1917:     } else {
 1918:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1919:     }
 1920: 
 1921:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1922:     my $response=$ua->request($request);
 1923: 
 1924:     if (wantarray) {
 1925: 	return ($response->content, $response);
 1926:     } else {
 1927: 	return $response->content;
 1928:     }
 1929: }
 1930: 
 1931: sub externalssi {
 1932:     my ($url)=@_;
 1933:     my $ua=new LWP::UserAgent;
 1934:     my $request=new HTTP::Request('GET',$url);
 1935:     my $response=$ua->request($request);
 1936:     if (wantarray) {
 1937:         return ($response->content, $response);
 1938:     } else {
 1939:         return $response->content;
 1940:     }
 1941: }
 1942: 
 1943: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1944: 
 1945: sub allowuploaded {
 1946:     my ($srcurl,$url)=@_;
 1947:     $url=&clutter(&declutter($url));
 1948:     my $dir=$url;
 1949:     $dir=~s/\/[^\/]+$//;
 1950:     my %httpref=();
 1951:     my $httpurl=&hreflocation('',$url);
 1952:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1953:     &Apache::lonnet::appenv(\%httpref);
 1954: }
 1955: 
 1956: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1957: # input: action, courseID, current domain, intended
 1958: #        path to file, source of file, instruction to parse file for objects,
 1959: #        ref to hash for embedded objects,
 1960: #        ref to hash for codebase of java objects.
 1961: #
 1962: # output: url to file (if action was uploaddoc), 
 1963: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1964: #
 1965: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1966: # course.
 1967: #
 1968: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1969: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1970: #          course's home server.
 1971: #
 1972: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1973: #          be copied from $source (current location) to 
 1974: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1975: #         and will then be copied to
 1976: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1977: #         course's home server.
 1978: #
 1979: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1980: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1981: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1982: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1983: #         in course's home server.
 1984: #
 1985: 
 1986: sub process_coursefile {
 1987:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1988:     my $fetchresult;
 1989:     my $home=&homeserver($docuname,$docudom);
 1990:     if ($action eq 'propagate') {
 1991:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1992: 			     $home);
 1993:     } else {
 1994:         my $fpath = '';
 1995:         my $fname = $file;
 1996:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1997:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1998:         my $filepath = &build_filepath($fpath);
 1999:         if ($action eq 'copy') {
 2000:             if ($source eq '') {
 2001:                 $fetchresult = 'no source file';
 2002:                 return $fetchresult;
 2003:             } else {
 2004:                 my $destination = $filepath.'/'.$fname;
 2005:                 rename($source,$destination);
 2006:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2007:                                  $home);
 2008:             }
 2009:         } elsif ($action eq 'uploaddoc') {
 2010:             open(my $fh,'>'.$filepath.'/'.$fname);
 2011:             print $fh $env{'form.'.$source};
 2012:             close($fh);
 2013:             if ($parser eq 'parse') {
 2014:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2015:                 unless ($parse_result eq 'ok') {
 2016:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2017:                 }
 2018:             }
 2019:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2020:                                  $home);
 2021:             if ($fetchresult eq 'ok') {
 2022:                 return '/uploaded/'.$fpath.'/'.$fname;
 2023:             } else {
 2024:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2025:                         ' to host '.$home.': '.$fetchresult);
 2026:                 return '/adm/notfound.html';
 2027:             }
 2028:         }
 2029:     }
 2030:     unless ( $fetchresult eq 'ok') {
 2031:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2032:              ' to host '.$home.': '.$fetchresult);
 2033:     }
 2034:     return $fetchresult;
 2035: }
 2036: 
 2037: sub build_filepath {
 2038:     my ($fpath) = @_;
 2039:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2040:     unless ($fpath eq '') {
 2041:         my @parts=split('/',$fpath);
 2042:         foreach my $part (@parts) {
 2043:             $filepath.= '/'.$part;
 2044:             if ((-e $filepath)!=1) {
 2045:                 mkdir($filepath,0777);
 2046:             }
 2047:         }
 2048:     }
 2049:     return $filepath;
 2050: }
 2051: 
 2052: sub store_edited_file {
 2053:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2054:     my $file = $primary_url;
 2055:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2056:     my $fpath = '';
 2057:     my $fname = $file;
 2058:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2059:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2060:     my $filepath = &build_filepath($fpath);
 2061:     open(my $fh,'>'.$filepath.'/'.$fname);
 2062:     print $fh $content;
 2063:     close($fh);
 2064:     my $home=&homeserver($docuname,$docudom);
 2065:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2066: 			  $home);
 2067:     if ($$fetchresult eq 'ok') {
 2068:         return '/uploaded/'.$fpath.'/'.$fname;
 2069:     } else {
 2070:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2071: 		 ' to host '.$home.': '.$$fetchresult);
 2072:         return '/adm/notfound.html';
 2073:     }
 2074: }
 2075: 
 2076: sub clean_filename {
 2077:     my ($fname,$args)=@_;
 2078: # Replace Windows backslashes by forward slashes
 2079:     $fname=~s/\\/\//g;
 2080:     if (!$args->{'keep_path'}) {
 2081:         # Get rid of everything but the actual filename
 2082: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2083:     }
 2084: # Replace spaces by underscores
 2085:     $fname=~s/\s+/\_/g;
 2086: # Replace all other weird characters by nothing
 2087:     $fname=~s{[^/\w\.\-]}{}g;
 2088: # Replace all .\d. sequences with _\d. so they no longer look like version
 2089: # numbers
 2090:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2091:     return $fname;
 2092: }
 2093: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
 2094: sub resizeImage {
 2095: 	my($img_url) = @_;	
 2096: 	my $ima = Image::Magick->new;                       
 2097:         $ima->Read($img_url);
 2098: 	if($ima->Get('width') > 400)
 2099: 	{
 2100: 		my $factor = $ima->Get('width')/400;
 2101:              	$ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
 2102: 	}
 2103: 	if($ima->Get('height') > 500)
 2104:         {
 2105:         	my $factor = $ima->Get('height')/500;
 2106:                 $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
 2107:         } 
 2108: 		
 2109: 	$ima->Write($img_url);
 2110: }
 2111: 
 2112: #Wrapper function for userphotoupload
 2113: sub userphotoupload
 2114: {
 2115: 	my($formname,$subdir) = @_;
 2116: 	$upload_photo_form = 1;
 2117: 	return &userfileupload($formname,undef,$subdir);
 2118: }
 2119: 
 2120: # --------------- Take an uploaded file and put it into the userfiles directory
 2121: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2122: #                    the desired filenam is in $env{"form.$formname.filename"}
 2123: #        $coursedoc - if true up to the current course
 2124: #                     if false
 2125: #        $subdir - directory in userfile to store the file into
 2126: #        $parser - instruction to parse file for objects ($parser = parse)    
 2127: #        $allfiles - reference to hash for embedded objects
 2128: #        $codebase - reference to hash for codebase of java objects
 2129: #        $desuname - username for permanent storage of uploaded file
 2130: #        $dsetudom - domain for permanaent storage of uploaded file
 2131: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2132: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2133: # 
 2134: # output: url of file in userspace, or error: <message> 
 2135: #             or /adm/notfound.html if failure to upload occurse
 2136: 
 2137: 
 2138: sub userfileupload {
 2139:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 2140:         $destudom,$thumbwidth,$thumbheight)=@_;
 2141:     if (!defined($subdir)) { $subdir='unknown'; }
 2142:     my $fname=$env{'form.'.$formname.'.filename'};
 2143:     $fname=&clean_filename($fname);
 2144: # See if there is anything left
 2145:     unless ($fname) { return 'error: no uploaded file'; }
 2146:     chop($env{'form.'.$formname});
 2147:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 2148:         my $now = time;
 2149:         my $filepath = 'tmp/helprequests/'.$now;
 2150:         my @parts=split(/\//,$filepath);
 2151:         my $fullpath = $perlvar{'lonDaemons'};
 2152:         for (my $i=0;$i<@parts;$i++) {
 2153:             $fullpath .= '/'.$parts[$i];
 2154:             if ((-e $fullpath)!=1) {
 2155:                 mkdir($fullpath,0777);
 2156:             }
 2157:         }
 2158:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2159:         print $fh $env{'form.'.$formname};
 2160:         close($fh);
 2161:         return $fullpath.'/'.$fname;
 2162:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 2163:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2164:                        '_'.$env{'user.domain'}.'/pending';
 2165:         my @parts=split(/\//,$filepath);
 2166:         my $fullpath = $perlvar{'lonDaemons'};
 2167:         for (my $i=0;$i<@parts;$i++) {
 2168:             $fullpath .= '/'.$parts[$i];
 2169:             if ((-e $fullpath)!=1) {
 2170:                 mkdir($fullpath,0777);
 2171:             }
 2172:         }
 2173:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2174:         print $fh $env{'form.'.$formname};
 2175:         close($fh);
 2176:         return $fullpath.'/'.$fname;
 2177:     }
 2178:     if ($subdir eq 'scantron') {
 2179:         $fname = 'scantron_orig_'.$fname;
 2180:     } else {   
 2181: # Create the directory if not present
 2182:         $fname="$subdir/$fname";
 2183:     }
 2184:     if ($coursedoc) {
 2185: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2186: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2187:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2188:             return &finishuserfileupload($docuname,$docudom,
 2189: 					 $formname,$fname,$parser,$allfiles,
 2190: 					 $codebase,$thumbwidth,$thumbheight);
 2191:         } else {
 2192:             $fname=$env{'form.folder'}.'/'.$fname;
 2193:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2194: 				       $fname,$formname,$parser,
 2195: 				       $allfiles,$codebase);
 2196:         }
 2197:     } elsif (defined($destuname)) {
 2198:         my $docuname=$destuname;
 2199:         my $docudom=$destudom;
 2200: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2201: 				     $parser,$allfiles,$codebase,
 2202:                                      $thumbwidth,$thumbheight);
 2203:         
 2204:     } else {
 2205:         my $docuname=$env{'user.name'};
 2206:         my $docudom=$env{'user.domain'};
 2207:         if (exists($env{'form.group'})) {
 2208:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2209:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2210:         }
 2211: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2212: 				     $parser,$allfiles,$codebase,
 2213:                                      $thumbwidth,$thumbheight);
 2214:     }
 2215: }
 2216: 
 2217: sub finishuserfileupload {
 2218:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2219:         $thumbwidth,$thumbheight) = @_;
 2220:     my $path=$docudom.'/'.$docuname.'/';
 2221:     my $filepath=$perlvar{'lonDocRoot'};
 2222:   
 2223:     my ($fnamepath,$file,$fetchthumb);
 2224:     $file=$fname;
 2225:     if ($fname=~m|/|) {
 2226:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2227: 	$path.=$fnamepath.'/';
 2228:     }
 2229:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2230:     my $count;
 2231:     for ($count=4;$count<=$#parts;$count++) {
 2232:         $filepath.="/$parts[$count]";
 2233:         if ((-e $filepath)!=1) {
 2234: 	    mkdir($filepath,0777);
 2235:         }
 2236:     }
 2237: 
 2238: # Save the file
 2239:     {
 2240: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2241: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2242: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2243: 	    return '/adm/notfound.html';
 2244: 	}
 2245: 	if (!print FH ($env{'form.'.$formname})) {
 2246: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2247: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2248: 	    return '/adm/notfound.html';
 2249: 	}
 2250: 	close(FH);
 2251: 	if($upload_photo_form==1)
 2252: 	{
 2253: 		resizeImage($filepath.'/'.$file);		
 2254: 		$upload_photo_form = 0;
 2255: 	}
 2256:     }
 2257:     if ($parser eq 'parse') {
 2258:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
 2259: 						   $codebase);
 2260:         unless ($parse_result eq 'ok') {
 2261:             &logthis('Failed to parse '.$filepath.$file.
 2262: 		     ' for embedded media: '.$parse_result); 
 2263:         }
 2264:     }
 2265:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2266:         my $input = $filepath.'/'.$file;
 2267:         my $output = $filepath.'/'.'tn-'.$file;
 2268:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2269:         system("convert -sample $thumbsize $input $output");
 2270:         if (-e $filepath.'/'.'tn-'.$file) {
 2271:             $fetchthumb  = 1; 
 2272:         }
 2273:     }
 2274:  
 2275: # Notify homeserver to grep it
 2276: #
 2277:     my $docuhome=&homeserver($docuname,$docudom);	
 2278:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2279:     if ($fetchresult eq 'ok') {
 2280:         if ($fetchthumb) {
 2281:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2282:             if ($thumbresult ne 'ok') {
 2283:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2284:                          $docuhome.': '.$thumbresult);
 2285:             }
 2286:         }
 2287: #
 2288: # Return the URL to it
 2289:         return '/uploaded/'.$path.$file;
 2290:     } else {
 2291:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2292: 		 ': '.$fetchresult);
 2293:         return '/adm/notfound.html';
 2294:     }
 2295: }
 2296: 
 2297: sub extract_embedded_items {
 2298:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 2299:     my @state = ();
 2300:     my %javafiles = (
 2301:                       codebase => '',
 2302:                       code => '',
 2303:                       archive => ''
 2304:                     );
 2305:     my %mediafiles = (
 2306:                       src => '',
 2307:                       movie => '',
 2308:                      );
 2309:     my $p;
 2310:     if ($content) {
 2311:         $p = HTML::LCParser->new($content);
 2312:     } else {
 2313:         $p = HTML::LCParser->new($fullpath);
 2314:     }
 2315:     while (my $t=$p->get_token()) {
 2316: 	if ($t->[0] eq 'S') {
 2317: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2318: 	    push(@state, $tagname);
 2319:             if (lc($tagname) eq 'allow') {
 2320:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2321:             }
 2322: 	    if (lc($tagname) eq 'img') {
 2323: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2324: 	    }
 2325: 	    if (lc($tagname) eq 'a') {
 2326: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2327: 	    }
 2328:             if (lc($tagname) eq 'script') {
 2329:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2330:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2331:                 } else {
 2332:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2333:                 }
 2334:             }
 2335:             if (lc($tagname) eq 'link') {
 2336:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2337:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2338:                 }
 2339:             }
 2340: 	    if (lc($tagname) eq 'object' ||
 2341: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2342: 		foreach my $item (keys(%javafiles)) {
 2343: 		    $javafiles{$item} = '';
 2344: 		}
 2345: 	    }
 2346: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2347: 		my $name = lc($attr->{'name'});
 2348: 		foreach my $item (keys(%javafiles)) {
 2349: 		    if ($name eq $item) {
 2350: 			$javafiles{$item} = $attr->{'value'};
 2351: 			last;
 2352: 		    }
 2353: 		}
 2354: 		foreach my $item (keys(%mediafiles)) {
 2355: 		    if ($name eq $item) {
 2356: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2357: 			last;
 2358: 		    }
 2359: 		}
 2360: 	    }
 2361: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2362: 		foreach my $item (keys(%javafiles)) {
 2363: 		    if ($attr->{$item}) {
 2364: 			$javafiles{$item} = $attr->{$item};
 2365: 			last;
 2366: 		    }
 2367: 		}
 2368: 		foreach my $item (keys(%mediafiles)) {
 2369: 		    if ($attr->{$item}) {
 2370: 			&add_filetype($allfiles,$attr->{$item},$item);
 2371: 			last;
 2372: 		    }
 2373: 		}
 2374: 	    }
 2375: 	} elsif ($t->[0] eq 'E') {
 2376: 	    my ($tagname) = ($t->[1]);
 2377: 	    if ($javafiles{'codebase'} ne '') {
 2378: 		$javafiles{'codebase'} .= '/';
 2379: 	    }  
 2380: 	    if (lc($tagname) eq 'applet' ||
 2381: 		lc($tagname) eq 'object' ||
 2382: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2383: 		) {
 2384: 		foreach my $item (keys(%javafiles)) {
 2385: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2386: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2387: 			&add_filetype($allfiles,$file,$item);
 2388: 		    }
 2389: 		}
 2390: 	    } 
 2391: 	    pop @state;
 2392: 	}
 2393:     }
 2394:     return 'ok';
 2395: }
 2396: 
 2397: sub add_filetype {
 2398:     my ($allfiles,$file,$type)=@_;
 2399:     if (exists($allfiles->{$file})) {
 2400: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2401: 	    push(@{$allfiles->{$file}}, &escape($type));
 2402: 	}
 2403:     } else {
 2404: 	@{$allfiles->{$file}} = (&escape($type));
 2405:     }
 2406: }
 2407: 
 2408: sub removeuploadedurl {
 2409:     my ($url)=@_;	
 2410:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 2411:     return &removeuserfile($uname,$udom,$fname);
 2412: }
 2413: 
 2414: sub removeuserfile {
 2415:     my ($docuname,$docudom,$fname)=@_;
 2416:     my $home=&homeserver($docuname,$docudom);    
 2417:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2418:     if ($result eq 'ok') {	
 2419:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2420:             my $metafile = $fname.'.meta';
 2421:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2422: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2423:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 2424:             my $sqlresult = 
 2425:                 &update_portfolio_table($docuname,$docudom,$file,
 2426:                                         'portfolio_metadata',$group,
 2427:                                         'delete');
 2428:         }
 2429:     }
 2430:     return $result;
 2431: }
 2432: 
 2433: sub mkdiruserfile {
 2434:     my ($docuname,$docudom,$dir)=@_;
 2435:     my $home=&homeserver($docuname,$docudom);
 2436:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2437: }
 2438: 
 2439: sub renameuserfile {
 2440:     my ($docuname,$docudom,$old,$new)=@_;
 2441:     my $home=&homeserver($docuname,$docudom);
 2442:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2443:                         &escape("$old").':'.&escape("$new"),$home);
 2444:     if ($result eq 'ok') {
 2445:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2446:             my $oldmeta = $old.'.meta';
 2447:             my $newmeta = $new.'.meta';
 2448:             my $metaresult = 
 2449:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2450: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2451:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2452:             my $sqlresult = 
 2453:                 &update_portfolio_table($docuname,$docudom,$file,
 2454:                                         'portfolio_metadata',$group,
 2455:                                         'delete');
 2456:         }
 2457:     }
 2458:     return $result;
 2459: }
 2460: 
 2461: # ------------------------------------------------------------------------- Log
 2462: 
 2463: sub log {
 2464:     my ($dom,$nam,$hom,$what)=@_;
 2465:     return critical("log:$dom:$nam:$what",$hom);
 2466: }
 2467: 
 2468: # ------------------------------------------------------------------ Course Log
 2469: #
 2470: # This routine flushes several buffers of non-mission-critical nature
 2471: #
 2472: 
 2473: sub flushcourselogs {
 2474:     &logthis('Flushing log buffers');
 2475: #
 2476: # course logs
 2477: # This is a log of all transactions in a course, which can be used
 2478: # for data mining purposes
 2479: #
 2480: # It also collects the courseid database, which lists last transaction
 2481: # times and course titles for all courseids
 2482: #
 2483:     my %courseidbuffer=();
 2484:     foreach my $crsid (keys(%courselogs)) {
 2485:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2486: 		          &escape($courselogs{$crsid}),
 2487: 		          $coursehombuf{$crsid}) eq 'ok') {
 2488: 	    delete $courselogs{$crsid};
 2489:         } else {
 2490:             &logthis('Failed to flush log buffer for '.$crsid);
 2491:             if (length($courselogs{$crsid})>40000) {
 2492:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2493:                         " exceeded maximum size, deleting.</font>");
 2494:                delete $courselogs{$crsid};
 2495:             }
 2496:         }
 2497:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2498:             'description' => $coursedescrbuf{$crsid},
 2499:             'inst_code'    => $courseinstcodebuf{$crsid},
 2500:             'type'        => $coursetypebuf{$crsid},
 2501:             'owner'       => $courseownerbuf{$crsid},
 2502:         };
 2503:     }
 2504: #
 2505: # Write course id database (reverse lookup) to homeserver of courses 
 2506: # Is used in pickcourse
 2507: #
 2508:     foreach my $crs_home (keys(%courseidbuffer)) {
 2509:         my $response = &courseidput(&host_domain($crs_home),
 2510:                                     $courseidbuffer{$crs_home},
 2511:                                     $crs_home,'timeonly');
 2512:     }
 2513: #
 2514: # File accesses
 2515: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2516: #
 2517:     foreach my $entry (keys(%accesshash)) {
 2518:         if ($entry =~ /___count$/) {
 2519:             my ($dom,$name);
 2520:             ($dom,$name,undef)=
 2521: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2522:             if (! defined($dom) || $dom eq '' || 
 2523:                 ! defined($name) || $name eq '') {
 2524:                 my $cid = $env{'request.course.id'};
 2525:                 $dom  = $env{'request.'.$cid.'.domain'};
 2526:                 $name = $env{'request.'.$cid.'.num'};
 2527:             }
 2528:             my $value = $accesshash{$entry};
 2529:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2530:             my %temphash=($url => $value);
 2531:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2532:             if ($result eq 'ok') {
 2533:                 delete $accesshash{$entry};
 2534:             } elsif ($result eq 'unknown_cmd') {
 2535:                 # Target server has old code running on it.
 2536:                 my %temphash=($entry => $value);
 2537:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2538:                     delete $accesshash{$entry};
 2539:                 }
 2540:             }
 2541:         } else {
 2542:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2543:             my %temphash=($entry => $accesshash{$entry});
 2544:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2545:                 delete $accesshash{$entry};
 2546:             }
 2547:         }
 2548:     }
 2549: #
 2550: # Roles
 2551: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2552: #
 2553:     foreach my $entry (keys(%userrolehash)) {
 2554:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2555: 	    split(/\:/,$entry);
 2556:         if (&Apache::lonnet::put('nohist_userroles',
 2557:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2558:                 $rudom,$runame) eq 'ok') {
 2559: 	    delete $userrolehash{$entry};
 2560:         }
 2561:     }
 2562: #
 2563: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2564: #
 2565:     my %domrolebuffer = ();
 2566:     foreach my $entry (keys(%domainrolehash)) {
 2567:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2568:         if ($domrolebuffer{$rudom}) {
 2569:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2570:                       '='.&escape($domainrolehash{$entry});
 2571:         } else {
 2572:             $domrolebuffer{$rudom}.=&escape($entry).
 2573:                       '='.&escape($domainrolehash{$entry});
 2574:         }
 2575:         delete $domainrolehash{$entry};
 2576:     }
 2577:     foreach my $dom (keys(%domrolebuffer)) {
 2578: 	my %servers = &get_servers($dom,'library');
 2579: 	foreach my $tryserver (keys(%servers)) {
 2580: 	    unless (&reply('domroleput:'.$dom.':'.
 2581: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2582: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2583: 	    }
 2584:         }
 2585:     }
 2586:     $dumpcount++;
 2587: }
 2588: 
 2589: sub courselog {
 2590:     my $what=shift;
 2591:     $what=time.':'.$what;
 2592:     unless ($env{'request.course.id'}) { return ''; }
 2593:     $coursedombuf{$env{'request.course.id'}}=
 2594:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2595:     $coursenumbuf{$env{'request.course.id'}}=
 2596:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2597:     $coursehombuf{$env{'request.course.id'}}=
 2598:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2599:     $coursedescrbuf{$env{'request.course.id'}}=
 2600:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2601:     $courseinstcodebuf{$env{'request.course.id'}}=
 2602:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2603:     $courseownerbuf{$env{'request.course.id'}}=
 2604:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2605:     $coursetypebuf{$env{'request.course.id'}}=
 2606:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2607:     if (defined $courselogs{$env{'request.course.id'}}) {
 2608: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2609:     } else {
 2610: 	$courselogs{$env{'request.course.id'}}.=$what;
 2611:     }
 2612:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2613: 	&flushcourselogs();
 2614:     }
 2615: }
 2616: 
 2617: sub courseacclog {
 2618:     my $fnsymb=shift;
 2619:     unless ($env{'request.course.id'}) { return ''; }
 2620:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2621:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2622:         $what.=':POST';
 2623:         # FIXME: Probably ought to escape things....
 2624: 	foreach my $key (keys(%env)) {
 2625:             if ($key=~/^form\.(.*)/) {
 2626:                 my $formitem = $1;
 2627:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 2628:                     $what.=':'.$formitem.'='.$env{$key};
 2629:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 2630:                     $what.=':'.$formitem.'='.$env{$key};
 2631:                 }
 2632:             }
 2633:         }
 2634:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2635:         # FIXME: We should not be depending on a form parameter that someone
 2636:         # editing lonsearchcat.pm might change in the future.
 2637:         if ($env{'form.phase'} eq 'course_search') {
 2638:             $what.= ':POST';
 2639:             # FIXME: Probably ought to escape things....
 2640:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2641:                                  'crsdiscuss') {
 2642:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2643:             }
 2644:         }
 2645:     }
 2646:     &courselog($what);
 2647: }
 2648: 
 2649: sub countacc {
 2650:     my $url=&declutter(shift);
 2651:     return if (! defined($url) || $url eq '');
 2652:     unless ($env{'request.course.id'}) { return ''; }
 2653:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2654:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2655:     $accesshash{$key}++;
 2656: }
 2657: 
 2658: sub linklog {
 2659:     my ($from,$to)=@_;
 2660:     $from=&declutter($from);
 2661:     $to=&declutter($to);
 2662:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2663:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2664: }
 2665:   
 2666: sub userrolelog {
 2667:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2668:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2669:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2670:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2671:         ($trole=~/^ta/)) {
 2672:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2673:        $userrolehash
 2674:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2675:                     =$tend.':'.$tstart;
 2676:     }
 2677:     if (($env{'request.role'} =~ /dc\./) &&
 2678: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2679: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2680: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
 2681:        $userrolehash
 2682:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2683:                     =$tend.':'.$tstart;
 2684:     }
 2685:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2686:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2687:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2688:         ($trole=~/^sc/)) {
 2689:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2690:        $domainrolehash
 2691:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2692:                     = $tend.':'.$tstart;
 2693:     }
 2694: }
 2695: 
 2696: sub courserolelog {
 2697:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 2698:     if (($trole eq 'cc') || ($trole eq 'in') ||
 2699:         ($trole eq 'ep') || ($trole eq 'ad') ||
 2700:         ($trole eq 'ta') || ($trole eq 'st') ||
 2701:         ($trole=~/^cr/) || ($trole eq 'gr')) {
 2702:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 2703:             my $cdom = $1;
 2704:             my $cnum = $2;
 2705:             my $sec = $3;
 2706:             my $namespace = 'rolelog';
 2707:             my %storehash = (
 2708:                                role    => $trole,
 2709:                                start   => $tstart,
 2710:                                end     => $tend,
 2711:                                selfenroll => $selfenroll,
 2712:                                context    => $context,
 2713:                             );
 2714:             if ($trole eq 'gr') {
 2715:                 $namespace = 'groupslog';
 2716:                 $storehash{'group'} = $sec;
 2717:             } else {
 2718:                 $storehash{'section'} = $sec;
 2719:             }
 2720:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 2721:             if (($trole ne 'st') || ($sec ne '')) {
 2722:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 2723:             }
 2724:         }
 2725:     }
 2726:     return;
 2727: }
 2728: 
 2729: sub get_course_adv_roles {
 2730:     my ($cid,$codes) = @_;
 2731:     $cid=$env{'request.course.id'} unless (defined($cid));
 2732:     my %coursehash=&coursedescription($cid);
 2733:     my $crstype = &Apache::loncommon::course_type($cid);
 2734:     my %nothide=();
 2735:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2736:         if ($user !~ /:/) {
 2737: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2738:         } else {
 2739:             $nothide{$user}=1;
 2740:         }
 2741:     }
 2742:     my %returnhash=();
 2743:     my %dumphash=
 2744:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2745:     my $now=time;
 2746:     my %privileged;
 2747:     foreach my $entry (keys(%dumphash)) {
 2748: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2749:         if (($tstart) && ($tstart<0)) { next; }
 2750:         if (($tend) && ($tend<$now)) { next; }
 2751:         if (($tstart) && ($now<$tstart)) { next; }
 2752:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2753: 	if ($username eq '' || $domain eq '') { next; }
 2754:         unless (ref($privileged{$domain}) eq 'HASH') {
 2755:             my %dompersonnel =
 2756:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 2757:             $privileged{$domain} = {};
 2758:             foreach my $server (keys(%dompersonnel)) {
 2759:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 2760:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 2761:                         my ($trole,$uname,$udom) = split(/:/,$user);
 2762:                         $privileged{$udom}{$uname} = 1;
 2763:                     }
 2764:                 }
 2765:             }
 2766:         }
 2767:         if ((exists($privileged{$domain}{$username})) && 
 2768:             (!$nothide{$username.':'.$domain})) { next; }
 2769: 	if ($role eq 'cr') { next; }
 2770:         if ($codes) {
 2771:             if ($section) { $role .= ':'.$section; }
 2772:             if ($returnhash{$role}) {
 2773:                 $returnhash{$role}.=','.$username.':'.$domain;
 2774:             } else {
 2775:                 $returnhash{$role}=$username.':'.$domain;
 2776:             }
 2777:         } else {
 2778:             my $key=&plaintext($role,$crstype);
 2779:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 2780:             if ($returnhash{$key}) {
 2781: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2782:             } else {
 2783:                 $returnhash{$key}=$username.':'.$domain;
 2784:             }
 2785:         }
 2786:     }
 2787:     return %returnhash;
 2788: }
 2789: 
 2790: sub get_my_roles {
 2791:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2792:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2793:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2794:     my (%dumphash,%nothide);
 2795:     if ($context eq 'userroles') { 
 2796:         %dumphash = &dump('roles',$udom,$uname);
 2797:     } else {
 2798:         %dumphash=
 2799:             &dump('nohist_userroles',$udom,$uname);
 2800:         if ($hidepriv) {
 2801:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2802:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2803:                 if ($user !~ /:/) {
 2804:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2805:                 } else {
 2806:                     $nothide{$user} = 1;
 2807:                 }
 2808:             }
 2809:         }
 2810:     }
 2811:     my %returnhash=();
 2812:     my $now=time;
 2813:     my %privileged;
 2814:     foreach my $entry (keys(%dumphash)) {
 2815:         my ($role,$tend,$tstart);
 2816:         if ($context eq 'userroles') {
 2817: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2818:         } else {
 2819:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2820:         }
 2821:         if (($tstart) && ($tstart<0)) { next; }
 2822:         my $status = 'active';
 2823:         if (($tend) && ($tend<=$now)) {
 2824:             $status = 'previous';
 2825:         } 
 2826:         if (($tstart) && ($now<$tstart)) {
 2827:             $status = 'future';
 2828:         }
 2829:         if (ref($types) eq 'ARRAY') {
 2830:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2831:                 next;
 2832:             } 
 2833:         } else {
 2834:             if ($status ne 'active') {
 2835:                 next;
 2836:             }
 2837:         }
 2838:         my ($rolecode,$username,$domain,$section,$area);
 2839:         if ($context eq 'userroles') {
 2840:             ($area,$rolecode) = split(/_/,$entry);
 2841:             (undef,$domain,$username,$section) = split(/\//,$area);
 2842:         } else {
 2843:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2844:         }
 2845:         if (ref($roledoms) eq 'ARRAY') {
 2846:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2847:                 next;
 2848:             }
 2849:         }
 2850:         if (ref($roles) eq 'ARRAY') {
 2851:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2852:                 if ($role =~ /^cr\//) {
 2853:                     if (!grep(/^cr$/,@{$roles})) {
 2854:                         next;
 2855:                     }
 2856:                 } else {
 2857:                     next;
 2858:                 }
 2859:             }
 2860:         }
 2861:         if ($hidepriv) {
 2862:             if ($context eq 'userroles') {
 2863:                 if ((&privileged($username,$domain)) &&
 2864:                     (!$nothide{$username.':'.$domain})) {
 2865:                     next;
 2866:                 }
 2867:             } else {
 2868:                 unless (ref($privileged{$domain}) eq 'HASH') {
 2869:                     my %dompersonnel =
 2870:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 2871:                     $privileged{$domain} = {};
 2872:                     if (keys(%dompersonnel)) {
 2873:                         foreach my $server (keys(%dompersonnel)) {
 2874:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 2875:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 2876:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 2877:                                     $privileged{$udom}{$uname} = $trole;
 2878:                                 }
 2879:                             }
 2880:                         }
 2881:                     }
 2882:                 }
 2883:                 if (exists($privileged{$domain}{$username})) {
 2884:                     if (!$nothide{$username.':'.$domain}) {
 2885:                         next;
 2886:                     }
 2887:                 }
 2888:             }
 2889:         }
 2890:         if ($withsec) {
 2891:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2892:                 $tstart.':'.$tend;
 2893:         } else {
 2894:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2895:         }
 2896:     }
 2897:     return %returnhash;
 2898: }
 2899: 
 2900: # ----------------------------------------------------- Frontpage Announcements
 2901: #
 2902: #
 2903: 
 2904: sub postannounce {
 2905:     my ($server,$text)=@_;
 2906:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2907:     unless ($text=~/\w/) { $text=''; }
 2908:     return &reply('setannounce:'.&escape($text),$server);
 2909: }
 2910: 
 2911: sub getannounce {
 2912: 
 2913:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2914: 	my $announcement='';
 2915: 	while (my $line = <$fh>) { $announcement .= $line; }
 2916: 	close($fh);
 2917: 	if ($announcement=~/\w/) { 
 2918: 	    return 
 2919:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2920:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2921: 	} else {
 2922: 	    return '';
 2923: 	}
 2924:     } else {
 2925: 	return '';
 2926:     }
 2927: }
 2928: 
 2929: # ---------------------------------------------------------- Course ID routines
 2930: # Deal with domain's nohist_courseid.db files
 2931: #
 2932: 
 2933: sub courseidput {
 2934:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2935:     my $outcome;
 2936:     if ($caller eq 'timeonly') {
 2937:         my $cids = '';
 2938:         foreach my $item (keys(%$storehash)) {
 2939:             $cids.=&escape($item).'&';
 2940:         }
 2941:         $cids=~s/\&$//;
 2942:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 2943:                           $coursehome);       
 2944:     } else {
 2945:         my $items = '';
 2946:         foreach my $item (keys(%$storehash)) {
 2947:             $items.= &escape($item).'='.
 2948:                      &freeze_escape($$storehash{$item}).'&';
 2949:         }
 2950:         $items=~s/\&$//;
 2951:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 2952:                           $coursehome);
 2953:     }
 2954:     if ($outcome eq 'unknown_cmd') {
 2955:         my $what;
 2956:         foreach my $cid (keys(%$storehash)) {
 2957:             $what .= &escape($cid).'=';
 2958:             foreach my $item ('description','inst_code','owner','type') {
 2959:                 $what .= &escape($storehash->{$cid}{$item}).':';
 2960:             }
 2961:             $what =~ s/\:$/&/;
 2962:         }
 2963:         $what =~ s/\&$//;  
 2964:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2965:     } else {
 2966:         return $outcome;
 2967:     }
 2968: }
 2969: 
 2970: sub courseiddump {
 2971:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 2972:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 2973:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,$cloneonly)=@_;
 2974:     my $as_hash = 1;
 2975:     my %returnhash;
 2976:     if (!$domfilter) { $domfilter=''; }
 2977:     my %libserv = &all_library();
 2978:     foreach my $tryserver (keys(%libserv)) {
 2979:         if ( (  $hostidflag == 1 
 2980: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2981: 	     || (!defined($hostidflag)) ) {
 2982: 
 2983: 	    if (($domfilter eq '') ||
 2984: 		(&host_domain($tryserver) eq $domfilter)) {
 2985:                 my $rep = 
 2986:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 2987:                          $sincefilter.':'.&escape($descfilter).':'.
 2988:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 2989:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 2990:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 2991:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 2992:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
 2993:                          &escape($cc_clone).':'.$cloneonly,$tryserver);
 2994:                 my @pairs=split(/\&/,$rep);
 2995:                 foreach my $item (@pairs) {
 2996:                     my ($key,$value)=split(/\=/,$item,2);
 2997:                     $key = &unescape($key);
 2998:                     next if ($key =~ /^error: 2 /);
 2999:                     my $result = &thaw_unescape($value);
 3000:                     if (ref($result) eq 'HASH') {
 3001:                         $returnhash{$key}=$result;
 3002:                     } else {
 3003:                         my @responses = split(/:/,$value);
 3004:                         my @items = ('description','inst_code','owner','type');
 3005:                         for (my $i=0; $i<@responses; $i++) {
 3006:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 3007:                         }
 3008:                     }
 3009:                 }
 3010:             }
 3011:         }
 3012:     }
 3013:     return %returnhash;
 3014: }
 3015: 
 3016: # ---------------------------------------------------------- DC e-mail
 3017: 
 3018: sub dcmailput {
 3019:     my ($domain,$msgid,$message,$server)=@_;
 3020:     my $status = &Apache::lonnet::critical(
 3021:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 3022:        &escape($message),$server);
 3023:     return $status;
 3024: }
 3025: 
 3026: sub dcmaildump {
 3027:     my ($dom,$startdate,$enddate,$senders) = @_;
 3028:     my %returnhash=();
 3029: 
 3030:     if (defined(&domain($dom,'primary'))) {
 3031:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 3032:                                                          &escape($enddate).':';
 3033: 	my @esc_senders=map { &escape($_)} @$senders;
 3034: 	$cmd.=&escape(join('&',@esc_senders));
 3035: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 3036:             my ($key,$value) = split(/\=/,$line,2);
 3037:             if (($key) && ($value)) {
 3038:                 $returnhash{&unescape($key)} = &unescape($value);
 3039:             }
 3040:         }
 3041:     }
 3042:     return %returnhash;
 3043: }
 3044: # ---------------------------------------------------------- Domain roles
 3045: 
 3046: sub get_domain_roles {
 3047:     my ($dom,$roles,$startdate,$enddate)=@_;
 3048:     if (undef($startdate) || $startdate eq '') {
 3049:         $startdate = '.';
 3050:     }
 3051:     if (undef($enddate) || $enddate eq '') {
 3052:         $enddate = '.';
 3053:     }
 3054:     my $rolelist;
 3055:     if (ref($roles) eq 'ARRAY') {
 3056:         $rolelist = join(':',@{$roles});
 3057:     }
 3058:     my %personnel = ();
 3059: 
 3060:     my %servers = &get_servers($dom,'library');
 3061:     foreach my $tryserver (keys(%servers)) {
 3062: 	%{$personnel{$tryserver}}=();
 3063: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 3064: 					    &escape($startdate).':'.
 3065: 					    &escape($enddate).':'.
 3066: 					    &escape($rolelist), $tryserver))) {
 3067: 	    my ($key,$value) = split(/\=/,$line,2);
 3068: 	    if (($key) && ($value)) {
 3069: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 3070: 	    }
 3071: 	}
 3072:     }
 3073:     return %personnel;
 3074: }
 3075: 
 3076: # ----------------------------------------------------------- Check out an item
 3077: 
 3078: sub get_first_access {
 3079:     my ($type,$argsymb)=@_;
 3080:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3081:     if ($argsymb) { $symb=$argsymb; }
 3082:     my ($map,$id,$res)=&decode_symb($symb);
 3083:     if ($type eq 'course') {
 3084: 	$res='course';
 3085:     } elsif ($type eq 'map') {
 3086: 	$res=&symbread($map);
 3087:     } else {
 3088: 	$res=$symb;
 3089:     }
 3090:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 3091:     return $times{"$courseid\0$res"};
 3092: }
 3093: 
 3094: sub set_first_access {
 3095:     my ($type)=@_;
 3096:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3097:     my ($map,$id,$res)=&decode_symb($symb);
 3098:     if ($type eq 'course') {
 3099: 	$res='course';
 3100:     } elsif ($type eq 'map') {
 3101: 	$res=&symbread($map);
 3102:     } else {
 3103: 	$res=$symb;
 3104:     }
 3105:     my $firstaccess=&get_first_access($type,$symb);
 3106:     if (!$firstaccess) {
 3107: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 3108:     }
 3109:     return 'already_set';
 3110: }
 3111: 
 3112: sub checkout {
 3113:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 3114:     my $now=time;
 3115:     my $lonhost=$perlvar{'lonHostID'};
 3116:     my $infostr=&escape(
 3117:                  'CHECKOUTTOKEN&'.
 3118:                  $tuname.'&'.
 3119:                  $tudom.'&'.
 3120:                  $tcrsid.'&'.
 3121:                  $symb.'&'.
 3122: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 3123:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 3124:     if ($token=~/^error\:/) { 
 3125:         &logthis("<font color=\"blue\">WARNING: ".
 3126:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 3127:                  "</font>");
 3128:         return ''; 
 3129:     }
 3130: 
 3131:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 3132:     $token=~tr/a-z/A-Z/;
 3133: 
 3134:     my %infohash=('resource.0.outtoken' => $token,
 3135:                   'resource.0.checkouttime' => $now,
 3136:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 3137: 
 3138:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3139:        return '';
 3140:     } else {
 3141:         &logthis("<font color=\"blue\">WARNING: ".
 3142:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 3143:                  "</font>");
 3144:     }    
 3145: 
 3146:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3147:                          &escape('Checkout '.$infostr.' - '.
 3148:                                                  $token)) ne 'ok') {
 3149: 	return '';
 3150:     } else {
 3151:         &logthis("<font color=\"blue\">WARNING: ".
 3152:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 3153:                  "</font>");
 3154:     }
 3155:     return $token;
 3156: }
 3157: 
 3158: # ------------------------------------------------------------ Check in an item
 3159: 
 3160: sub checkin {
 3161:     my $token=shift;
 3162:     my $now=time;
 3163:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 3164:     $lonhost=~tr/A-Z/a-z/;
 3165:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 3166:     $dtoken=~s/\W/\_/g;
 3167:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 3168:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 3169: 
 3170:     unless (($tuname) && ($tudom)) {
 3171:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 3172:         return '';
 3173:     }
 3174:     
 3175:     unless (&allowed('mgr',$tcrsid)) {
 3176:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 3177:                  $env{'user.name'}.' - '.$env{'user.domain'});
 3178:         return '';
 3179:     }
 3180: 
 3181:     my %infohash=('resource.0.intoken' => $token,
 3182:                   'resource.0.checkintime' => $now,
 3183:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 3184: 
 3185:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3186:        return '';
 3187:     }    
 3188: 
 3189:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3190:                          &escape('Checkin - '.$token)) ne 'ok') {
 3191: 	return '';
 3192:     }
 3193: 
 3194:     return ($symb,$tuname,$tudom,$tcrsid);    
 3195: }
 3196: 
 3197: # --------------------------------------------- Set Expire Date for Spreadsheet
 3198: 
 3199: sub expirespread {
 3200:     my ($uname,$udom,$stype,$usymb)=@_;
 3201:     my $cid=$env{'request.course.id'}; 
 3202:     if ($cid) {
 3203:        my $now=time;
 3204:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3205:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3206:                             $env{'course.'.$cid.'.num'}.
 3207: 	        	    ':nohist_expirationdates:'.
 3208:                             &escape($key).'='.$now,
 3209:                             $env{'course.'.$cid.'.home'})
 3210:     }
 3211:     return 'ok';
 3212: }
 3213: 
 3214: # ----------------------------------------------------- Devalidate Spreadsheets
 3215: 
 3216: sub devalidate {
 3217:     my ($symb,$uname,$udom)=@_;
 3218:     my $cid=$env{'request.course.id'}; 
 3219:     if ($cid) {
 3220:         # delete the stored spreadsheets for
 3221:         # - the student level sheet of this user in course's homespace
 3222:         # - the assessment level sheet for this resource 
 3223:         #   for this user in user's homespace
 3224: 	# - current conditional state info
 3225: 	my $key=$uname.':'.$udom.':';
 3226:         my $status=
 3227: 	    &del('nohist_calculatedsheets',
 3228: 		 [$key.'studentcalc:'],
 3229: 		 $env{'course.'.$cid.'.domain'},
 3230: 		 $env{'course.'.$cid.'.num'})
 3231: 		.' '.
 3232: 	    &del('nohist_calculatedsheets_'.$cid,
 3233: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3234:         unless ($status eq 'ok ok') {
 3235:            &logthis('Could not devalidate spreadsheet '.
 3236:                     $uname.' at '.$udom.' for '.
 3237: 		    $symb.': '.$status);
 3238:         }
 3239: 	&delenv('user.state.'.$cid);
 3240:     }
 3241: }
 3242: 
 3243: sub get_scalar {
 3244:     my ($string,$end) = @_;
 3245:     my $value;
 3246:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3247: 	$value = $1;
 3248:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3249: 	$value = $1;
 3250:     }
 3251:     return &unescape($value);
 3252: }
 3253: 
 3254: sub array2str {
 3255:   my (@array) = @_;
 3256:   my $result=&arrayref2str(\@array);
 3257:   $result=~s/^__ARRAY_REF__//;
 3258:   $result=~s/__END_ARRAY_REF__$//;
 3259:   return $result;
 3260: }
 3261: 
 3262: sub arrayref2str {
 3263:   my ($arrayref) = @_;
 3264:   my $result='__ARRAY_REF__';
 3265:   foreach my $elem (@$arrayref) {
 3266:     if(ref($elem) eq 'ARRAY') {
 3267:       $result.=&arrayref2str($elem).'&';
 3268:     } elsif(ref($elem) eq 'HASH') {
 3269:       $result.=&hashref2str($elem).'&';
 3270:     } elsif(ref($elem)) {
 3271:       #print("Got a ref of ".(ref($elem))." skipping.");
 3272:     } else {
 3273:       $result.=&escape($elem).'&';
 3274:     }
 3275:   }
 3276:   $result=~s/\&$//;
 3277:   $result .= '__END_ARRAY_REF__';
 3278:   return $result;
 3279: }
 3280: 
 3281: sub hash2str {
 3282:   my (%hash) = @_;
 3283:   my $result=&hashref2str(\%hash);
 3284:   $result=~s/^__HASH_REF__//;
 3285:   $result=~s/__END_HASH_REF__$//;
 3286:   return $result;
 3287: }
 3288: 
 3289: sub hashref2str {
 3290:   my ($hashref)=@_;
 3291:   my $result='__HASH_REF__';
 3292:   foreach my $key (sort(keys(%$hashref))) {
 3293:     if (ref($key) eq 'ARRAY') {
 3294:       $result.=&arrayref2str($key).'=';
 3295:     } elsif (ref($key) eq 'HASH') {
 3296:       $result.=&hashref2str($key).'=';
 3297:     } elsif (ref($key)) {
 3298:       $result.='=';
 3299:       #print("Got a ref of ".(ref($key))." skipping.");
 3300:     } else {
 3301: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3302:     }
 3303: 
 3304:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3305:       $result.=&arrayref2str($hashref->{$key}).'&';
 3306:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3307:       $result.=&hashref2str($hashref->{$key}).'&';
 3308:     } elsif(ref($hashref->{$key})) {
 3309:        $result.='&';
 3310:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3311:     } else {
 3312:       $result.=&escape($hashref->{$key}).'&';
 3313:     }
 3314:   }
 3315:   $result=~s/\&$//;
 3316:   $result .= '__END_HASH_REF__';
 3317:   return $result;
 3318: }
 3319: 
 3320: sub str2hash {
 3321:     my ($string)=@_;
 3322:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3323:     return %$hash;
 3324: }
 3325: 
 3326: sub str2hashref {
 3327:   my ($string) = @_;
 3328: 
 3329:   my %hash;
 3330: 
 3331:   if($string !~ /^__HASH_REF__/) {
 3332:       if (! ($string eq '' || !defined($string))) {
 3333: 	  $hash{'error'}='Not hash reference';
 3334:       }
 3335:       return (\%hash, $string);
 3336:   }
 3337: 
 3338:   $string =~ s/^__HASH_REF__//;
 3339: 
 3340:   while($string !~ /^__END_HASH_REF__/) {
 3341:       #key
 3342:       my $key='';
 3343:       if($string =~ /^__HASH_REF__/) {
 3344:           ($key, $string)=&str2hashref($string);
 3345:           if(defined($key->{'error'})) {
 3346:               $hash{'error'}='Bad data';
 3347:               return (\%hash, $string);
 3348:           }
 3349:       } elsif($string =~ /^__ARRAY_REF__/) {
 3350:           ($key, $string)=&str2arrayref($string);
 3351:           if($key->[0] eq 'Array reference error') {
 3352:               $hash{'error'}='Bad data';
 3353:               return (\%hash, $string);
 3354:           }
 3355:       } else {
 3356:           $string =~ s/^(.*?)=//;
 3357: 	  $key=&unescape($1);
 3358:       }
 3359:       $string =~ s/^=//;
 3360: 
 3361:       #value
 3362:       my $value='';
 3363:       if($string =~ /^__HASH_REF__/) {
 3364:           ($value, $string)=&str2hashref($string);
 3365:           if(defined($value->{'error'})) {
 3366:               $hash{'error'}='Bad data';
 3367:               return (\%hash, $string);
 3368:           }
 3369:       } elsif($string =~ /^__ARRAY_REF__/) {
 3370:           ($value, $string)=&str2arrayref($string);
 3371:           if($value->[0] eq 'Array reference error') {
 3372:               $hash{'error'}='Bad data';
 3373:               return (\%hash, $string);
 3374:           }
 3375:       } else {
 3376: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3377:       }
 3378:       $string =~ s/^&//;
 3379: 
 3380:       $hash{$key}=$value;
 3381:   }
 3382: 
 3383:   $string =~ s/^__END_HASH_REF__//;
 3384: 
 3385:   return (\%hash, $string);
 3386: }
 3387: 
 3388: sub str2array {
 3389:     my ($string)=@_;
 3390:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3391:     return @$array;
 3392: }
 3393: 
 3394: sub str2arrayref {
 3395:   my ($string) = @_;
 3396:   my @array;
 3397: 
 3398:   if($string !~ /^__ARRAY_REF__/) {
 3399:       if (! ($string eq '' || !defined($string))) {
 3400: 	  $array[0]='Array reference error';
 3401:       }
 3402:       return (\@array, $string);
 3403:   }
 3404: 
 3405:   $string =~ s/^__ARRAY_REF__//;
 3406: 
 3407:   while($string !~ /^__END_ARRAY_REF__/) {
 3408:       my $value='';
 3409:       if($string =~ /^__HASH_REF__/) {
 3410:           ($value, $string)=&str2hashref($string);
 3411:           if(defined($value->{'error'})) {
 3412:               $array[0] ='Array reference error';
 3413:               return (\@array, $string);
 3414:           }
 3415:       } elsif($string =~ /^__ARRAY_REF__/) {
 3416:           ($value, $string)=&str2arrayref($string);
 3417:           if($value->[0] eq 'Array reference error') {
 3418:               $array[0] ='Array reference error';
 3419:               return (\@array, $string);
 3420:           }
 3421:       } else {
 3422: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3423:       }
 3424:       $string =~ s/^&//;
 3425: 
 3426:       push(@array, $value);
 3427:   }
 3428: 
 3429:   $string =~ s/^__END_ARRAY_REF__//;
 3430: 
 3431:   return (\@array, $string);
 3432: }
 3433: 
 3434: # -------------------------------------------------------------------Temp Store
 3435: 
 3436: sub tmpreset {
 3437:   my ($symb,$namespace,$domain,$stuname) = @_;
 3438:   if (!$symb) {
 3439:     $symb=&symbread();
 3440:     if (!$symb) { $symb= $env{'request.url'}; }
 3441:   }
 3442:   $symb=escape($symb);
 3443: 
 3444:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3445:   $namespace=~s/\//\_/g;
 3446:   $namespace=~s/\W//g;
 3447: 
 3448:   if (!$domain) { $domain=$env{'user.domain'}; }
 3449:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3450:   if ($domain eq 'public' && $stuname eq 'public') {
 3451:       $stuname=$ENV{'REMOTE_ADDR'};
 3452:   }
 3453:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3454:   my %hash;
 3455:   if (tie(%hash,'GDBM_File',
 3456: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3457: 	  &GDBM_WRCREAT(),0640)) {
 3458:     foreach my $key (keys(%hash)) {
 3459:       if ($key=~ /:$symb/) {
 3460: 	delete($hash{$key});
 3461:       }
 3462:     }
 3463:   }
 3464: }
 3465: 
 3466: sub tmpstore {
 3467:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3468: 
 3469:   if (!$symb) {
 3470:     $symb=&symbread();
 3471:     if (!$symb) { $symb= $env{'request.url'}; }
 3472:   }
 3473:   $symb=escape($symb);
 3474: 
 3475:   if (!$namespace) {
 3476:     # I don't think we would ever want to store this for a course.
 3477:     # it seems this will only be used if we don't have a course.
 3478:     #$namespace=$env{'request.course.id'};
 3479:     #if (!$namespace) {
 3480:       $namespace=$env{'request.state'};
 3481:     #}
 3482:   }
 3483:   $namespace=~s/\//\_/g;
 3484:   $namespace=~s/\W//g;
 3485:   if (!$domain) { $domain=$env{'user.domain'}; }
 3486:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3487:   if ($domain eq 'public' && $stuname eq 'public') {
 3488:       $stuname=$ENV{'REMOTE_ADDR'};
 3489:   }
 3490:   my $now=time;
 3491:   my %hash;
 3492:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3493:   if (tie(%hash,'GDBM_File',
 3494: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3495: 	  &GDBM_WRCREAT(),0640)) {
 3496:     $hash{"version:$symb"}++;
 3497:     my $version=$hash{"version:$symb"};
 3498:     my $allkeys=''; 
 3499:     foreach my $key (keys(%$storehash)) {
 3500:       $allkeys.=$key.':';
 3501:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3502:     }
 3503:     $hash{"$version:$symb:timestamp"}=$now;
 3504:     $allkeys.='timestamp';
 3505:     $hash{"$version:keys:$symb"}=$allkeys;
 3506:     if (untie(%hash)) {
 3507:       return 'ok';
 3508:     } else {
 3509:       return "error:$!";
 3510:     }
 3511:   } else {
 3512:     return "error:$!";
 3513:   }
 3514: }
 3515: 
 3516: # -----------------------------------------------------------------Temp Restore
 3517: 
 3518: sub tmprestore {
 3519:   my ($symb,$namespace,$domain,$stuname) = @_;
 3520: 
 3521:   if (!$symb) {
 3522:     $symb=&symbread();
 3523:     if (!$symb) { $symb= $env{'request.url'}; }
 3524:   }
 3525:   $symb=escape($symb);
 3526: 
 3527:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3528: 
 3529:   if (!$domain) { $domain=$env{'user.domain'}; }
 3530:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3531:   if ($domain eq 'public' && $stuname eq 'public') {
 3532:       $stuname=$ENV{'REMOTE_ADDR'};
 3533:   }
 3534:   my %returnhash;
 3535:   $namespace=~s/\//\_/g;
 3536:   $namespace=~s/\W//g;
 3537:   my %hash;
 3538:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3539:   if (tie(%hash,'GDBM_File',
 3540: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3541: 	  &GDBM_READER(),0640)) {
 3542:     my $version=$hash{"version:$symb"};
 3543:     $returnhash{'version'}=$version;
 3544:     my $scope;
 3545:     for ($scope=1;$scope<=$version;$scope++) {
 3546:       my $vkeys=$hash{"$scope:keys:$symb"};
 3547:       my @keys=split(/:/,$vkeys);
 3548:       my $key;
 3549:       $returnhash{"$scope:keys"}=$vkeys;
 3550:       foreach $key (@keys) {
 3551: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3552: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3553:       }
 3554:     }
 3555:     if (!(untie(%hash))) {
 3556:       return "error:$!";
 3557:     }
 3558:   } else {
 3559:     return "error:$!";
 3560:   }
 3561:   return %returnhash;
 3562: }
 3563: 
 3564: # ----------------------------------------------------------------------- Store
 3565: 
 3566: sub store {
 3567:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3568:     my $home='';
 3569: 
 3570:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3571: 
 3572:     $symb=&symbclean($symb);
 3573:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3574: 
 3575:     if (!$domain) { $domain=$env{'user.domain'}; }
 3576:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3577: 
 3578:     &devalidate($symb,$stuname,$domain);
 3579: 
 3580:     $symb=escape($symb);
 3581:     if (!$namespace) { 
 3582:        unless ($namespace=$env{'request.course.id'}) { 
 3583:           return ''; 
 3584:        } 
 3585:     }
 3586:     if (!$home) { $home=$env{'user.home'}; }
 3587: 
 3588:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3589:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3590: 
 3591:     my $namevalue='';
 3592:     foreach my $key (keys(%$storehash)) {
 3593:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3594:     }
 3595:     $namevalue=~s/\&$//;
 3596:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3597:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3598: }
 3599: 
 3600: # -------------------------------------------------------------- Critical Store
 3601: 
 3602: sub cstore {
 3603:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3604:     my $home='';
 3605: 
 3606:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3607: 
 3608:     $symb=&symbclean($symb);
 3609:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3610: 
 3611:     if (!$domain) { $domain=$env{'user.domain'}; }
 3612:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3613: 
 3614:     &devalidate($symb,$stuname,$domain);
 3615: 
 3616:     $symb=escape($symb);
 3617:     if (!$namespace) { 
 3618:        unless ($namespace=$env{'request.course.id'}) { 
 3619:           return ''; 
 3620:        } 
 3621:     }
 3622:     if (!$home) { $home=$env{'user.home'}; }
 3623: 
 3624:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3625:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3626: 
 3627:     my $namevalue='';
 3628:     foreach my $key (keys(%$storehash)) {
 3629:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3630:     }
 3631:     $namevalue=~s/\&$//;
 3632:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3633:     return critical
 3634:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3635: }
 3636: 
 3637: # --------------------------------------------------------------------- Restore
 3638: 
 3639: sub restore {
 3640:     my ($symb,$namespace,$domain,$stuname) = @_;
 3641:     my $home='';
 3642: 
 3643:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3644: 
 3645:     if (!$symb) {
 3646:       unless ($symb=escape(&symbread())) { return ''; }
 3647:     } else {
 3648:       $symb=&escape(&symbclean($symb));
 3649:     }
 3650:     if (!$namespace) { 
 3651:        unless ($namespace=$env{'request.course.id'}) { 
 3652:           return ''; 
 3653:        } 
 3654:     }
 3655:     if (!$domain) { $domain=$env{'user.domain'}; }
 3656:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3657:     if (!$home) { $home=$env{'user.home'}; }
 3658:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3659: 
 3660:     my %returnhash=();
 3661:     foreach my $line (split(/\&/,$answer)) {
 3662: 	my ($name,$value)=split(/\=/,$line);
 3663:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3664:     }
 3665:     my $version;
 3666:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3667:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3668:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3669:        }
 3670:     }
 3671:     return %returnhash;
 3672: }
 3673: 
 3674: # ---------------------------------------------------------- Course Description
 3675: 
 3676: sub coursedescription {
 3677:     my ($courseid,$args)=@_;
 3678:     $courseid=~s/^\///;
 3679:     $courseid=~s/\_/\//g;
 3680:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3681:     my $chome=&homeserver($cnum,$cdomain);
 3682:     my $normalid=$cdomain.'_'.$cnum;
 3683:     # need to always cache even if we get errors otherwise we keep 
 3684:     # trying and trying and trying to get the course description.
 3685:     my %envhash=();
 3686:     my %returnhash=();
 3687:     
 3688:     my $expiretime=600;
 3689:     if ($env{'request.course.id'} eq $normalid) {
 3690: 	$expiretime=120;
 3691:     }
 3692: 
 3693:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3694:     if (!$args->{'freshen_cache'}
 3695: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3696: 	foreach my $key (keys(%env)) {
 3697: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3698: 	    my ($setting) = $1;
 3699: 	    $returnhash{$setting} = $env{$key};
 3700: 	}
 3701: 	return %returnhash;
 3702:     }
 3703: 
 3704:     # get the data agin
 3705:     if (!$args->{'one_time'}) {
 3706: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3707:     }
 3708: 
 3709:     if ($chome ne 'no_host') {
 3710:        %returnhash=&dump('environment',$cdomain,$cnum);
 3711:        if (!exists($returnhash{'con_lost'})) {
 3712:            $returnhash{'home'}= $chome;
 3713: 	   $returnhash{'domain'} = $cdomain;
 3714: 	   $returnhash{'num'} = $cnum;
 3715:            if (!defined($returnhash{'type'})) {
 3716:                $returnhash{'type'} = 'Course';
 3717:            }
 3718:            while (my ($name,$value) = each %returnhash) {
 3719:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3720:            }
 3721:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3722:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3723: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3724:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3725:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3726:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3727:        }
 3728:     }
 3729:     if (!$args->{'one_time'}) {
 3730: 	&appenv(\%envhash);
 3731:     }
 3732:     return %returnhash;
 3733: }
 3734: 
 3735: # -------------------------------------------------See if a user is privileged
 3736: 
 3737: sub privileged {
 3738:     my ($username,$domain)=@_;
 3739:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3740: 			&homeserver($username,$domain));
 3741:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3742:     my $now=time;
 3743:     if ($rolesdump ne '') {
 3744:         foreach my $entry (split(/&/,$rolesdump)) {
 3745: 	    if ($entry!~/^rolesdef_/) {
 3746: 		my ($area,$role)=split(/=/,$entry);
 3747: 		$area=~s/\_\w\w$//;
 3748: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3749: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3750: 		    my $active=1;
 3751: 		    if ($tend) {
 3752: 			if ($tend<$now) { $active=0; }
 3753: 		    }
 3754: 		    if ($tstart) {
 3755: 			if ($tstart>$now) { $active=0; }
 3756: 		    }
 3757: 		    if ($active) { return 1; }
 3758: 		}
 3759: 	    }
 3760: 	}
 3761:     }
 3762:     return 0;
 3763: }
 3764: 
 3765: # -------------------------------------------------------- Get user privileges
 3766: 
 3767: sub rolesinit {
 3768:     my ($domain,$username,$authhost)=@_;
 3769:     my %userroles;
 3770:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3771:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
 3772:     my %allroles=();
 3773:     my %allgroups=();   
 3774:     my $now=time;
 3775:     %userroles = ('user.login.time' => $now);
 3776:     my $group_privs;
 3777: 
 3778:     if ($rolesdump ne '') {
 3779:         foreach my $entry (split(/&/,$rolesdump)) {
 3780: 	  if ($entry!~/^rolesdef_/) {
 3781:             my ($area,$role)=split(/=/,$entry);
 3782: 	    $area=~s/\_\w\w$//;
 3783:             my ($trole,$tend,$tstart,$group_privs);
 3784: 	    if ($role=~/^cr/) { 
 3785: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3786: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3787: 		    ($tend,$tstart)=split('_',$trest);
 3788: 		} else {
 3789: 		    $trole=$role;
 3790: 		}
 3791:             } elsif ($role =~ m|^gr/|) {
 3792:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3793:                 ($trole,$group_privs) = split(/\//,$trole);
 3794:                 $group_privs = &unescape($group_privs);
 3795: 	    } else {
 3796: 		($trole,$tend,$tstart)=split(/_/,$role);
 3797: 	    }
 3798: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3799: 					 $username);
 3800: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3801:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3802:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3803:             if (($area ne '') && ($trole ne '')) {
 3804: 		my $spec=$trole.'.'.$area;
 3805: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3806: 		if ($trole =~ /^cr\//) {
 3807:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3808:                 } elsif ($trole eq 'gr') {
 3809:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3810: 		} else {
 3811:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3812: 		}
 3813:             }
 3814:           }
 3815:         }
 3816:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3817:         $userroles{'user.adv'}    = $adv;
 3818: 	$userroles{'user.author'} = $author;
 3819:         $env{'user.adv'}=$adv;
 3820:     }
 3821:     return \%userroles;  
 3822: }
 3823: 
 3824: sub set_arearole {
 3825:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3826: # log the associated role with the area
 3827:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3828:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3829: }
 3830: 
 3831: sub custom_roleprivs {
 3832:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3833:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3834:     my $homsvr=homeserver($rauthor,$rdomain);
 3835:     if (&hostname($homsvr) ne '') {
 3836:         my ($rdummy,$roledef)=
 3837:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3838:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3839:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3840:             if (defined($syspriv)) {
 3841:                 $$allroles{'cm./'}.=':'.$syspriv;
 3842:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3843:             }
 3844:             if ($tdomain ne '') {
 3845:                 if (defined($dompriv)) {
 3846:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3847:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3848:                 }
 3849:                 if (($trest ne '') && (defined($coursepriv))) {
 3850:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3851:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3852:                 }
 3853:             }
 3854:         }
 3855:     }
 3856: }
 3857: 
 3858: sub group_roleprivs {
 3859:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3860:     my $access = 1;
 3861:     my $now = time;
 3862:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3863:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3864:     if ($access) {
 3865:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3866:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3867:     }
 3868: }
 3869: 
 3870: sub standard_roleprivs {
 3871:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3872:     if (defined($pr{$trole.':s'})) {
 3873:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3874:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3875:     }
 3876:     if ($tdomain ne '') {
 3877:         if (defined($pr{$trole.':d'})) {
 3878:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3879:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3880:         }
 3881:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3882:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3883:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3884:         }
 3885:     }
 3886: }
 3887: 
 3888: sub set_userprivs {
 3889:     my ($userroles,$allroles,$allgroups) = @_; 
 3890:     my $author=0;
 3891:     my $adv=0;
 3892:     my %grouproles = ();
 3893:     if (keys(%{$allgroups}) > 0) {
 3894:         foreach my $role (keys(%{$allroles})) {
 3895:             my ($trole,$area,$sec,$extendedarea);
 3896:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3897:                 $trole = $1;
 3898:                 $area = $2;
 3899:                 $sec = $3;
 3900:                 $extendedarea = $area.$sec;
 3901:                 if (exists($$allgroups{$area})) {
 3902:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3903:                         my $spec = $trole.'.'.$extendedarea;
 3904:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3905:                                                 $$allgroups{$area}{$group};
 3906:                     }
 3907:                 }
 3908:             }
 3909:         }
 3910:     }
 3911:     foreach my $group (keys(%grouproles)) {
 3912:         $$allroles{$group} = $grouproles{$group};
 3913:     }
 3914:     foreach my $role (keys(%{$allroles})) {
 3915:         my %thesepriv;
 3916:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3917:         foreach my $item (split(/:/,$$allroles{$role})) {
 3918:             if ($item ne '') {
 3919:                 my ($privilege,$restrictions)=split(/&/,$item);
 3920:                 if ($restrictions eq '') {
 3921:                     $thesepriv{$privilege}='F';
 3922:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3923:                     $thesepriv{$privilege}.=$restrictions;
 3924:                 }
 3925:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3926:             }
 3927:         }
 3928:         my $thesestr='';
 3929:         foreach my $priv (keys(%thesepriv)) {
 3930: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3931: 	}
 3932:         $userroles->{'user.priv.'.$role} = $thesestr;
 3933:     }
 3934:     return ($author,$adv);
 3935: }
 3936: 
 3937: sub role_status {
 3938:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 3939:     my @pwhere = ();
 3940:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 3941:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 3942:         unless (!defined($$role) || $$role eq '') {
 3943:             $$where=join('.',@pwhere);
 3944:             $$trolecode=$$role.'.'.$$where;
 3945:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 3946:             $$tstatus='is';
 3947:             if ($$tstart && $$tstart>$then) {
 3948:                 $$tstatus='future';
 3949:                 if ($$tstart && $$tstart>$refresh) {
 3950:                     if ($$tstart<$now) {
 3951:                         if (($$where ne '') && ($$role ne '')) {
 3952:                             my (%allroles,%allgroups,$group_privs);
 3953:                             my %userroles = (
 3954:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 3955:                             );
 3956:                             my $spec=$$role.'.'.$$where;
 3957:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 3958:                             if ($$role eq 'gr') {
 3959:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 3960:                                                     $env{'user.name'})=@_;
 3961:                                 my ($trole) = split('_',$role,1);
 3962:                                 (undef,my $group_privs) = split(/\//,$trole);
 3963:                                 $group_privs = &unescape($group_privs);
 3964:                             }
 3965:                             if ($$role =~ /^cr\//) {
 3966:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 3967:                             } elsif ($$role eq 'gr') {
 3968:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 3969:                                                     $env{'user.name'});
 3970:                                 my $trole = split('_',$rolehash{$$where.'_'.$$role},1);
 3971:                                 (undef,my $group_privs) = split(/\//,$trole);
 3972:                                 $group_privs = &unescape($group_privs);
 3973:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 3974:                             } else {
 3975:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 3976:                             }
 3977:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3978:                             &appenv(\%userroles,[$$role,'cm']);
 3979:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 3980:                             $$tstatus = 'is';
 3981:                         }
 3982:                     }
 3983:                 }
 3984:             }
 3985:             if ($$tend) {
 3986:                 if ($$tend<$then) {
 3987:                     $$tstatus='expired';
 3988:                 } elsif ($$tend<$now) {
 3989:                     $$tstatus='will_not';
 3990:                 }
 3991:             }
 3992:         }
 3993:     }
 3994: }
 3995: 
 3996: sub check_adhoc_privs {
 3997:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
 3998:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 3999:     if ($env{$cckey}) {
 4000:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 4001:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 4002:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 4003:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
 4004:         }
 4005:     } else {
 4006:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
 4007:     }
 4008: }
 4009: 
 4010: sub set_adhoc_privileges {
 4011: # role can be cc or ca
 4012:     my ($dcdom,$pickedcourse,$role) = @_;
 4013:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 4014:     my $spec = $role.'.'.$area;
 4015:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 4016:                                   $env{'user.name'});
 4017:     my %ccrole = ();
 4018:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 4019:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 4020:     &appenv(\%userroles,[$role,'cm']);
 4021:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4022:     &appenv( {'request.role'        => $spec,
 4023:               'request.role.domain' => $dcdom,
 4024:               'request.course.sec'  => ''
 4025:              }
 4026:            );
 4027:     my $tadv=0;
 4028:     if (&allowed('adv') eq 'F') { $tadv=1; }
 4029:     &appenv({'request.role.adv'    => $tadv});
 4030: }
 4031: 
 4032: # --------------------------------------------------------------- get interface
 4033: 
 4034: sub get {
 4035:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4036:    my $items='';
 4037:    foreach my $item (@$storearr) {
 4038:        $items.=&escape($item).'&';
 4039:    }
 4040:    $items=~s/\&$//;
 4041:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4042:    if (!$uname) { $uname=$env{'user.name'}; }
 4043:    my $uhome=&homeserver($uname,$udomain);
 4044: 
 4045:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 4046:    my @pairs=split(/\&/,$rep);
 4047:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 4048:      return @pairs;
 4049:    }
 4050:    my %returnhash=();
 4051:    my $i=0;
 4052:    foreach my $item (@$storearr) {
 4053:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4054:       $i++;
 4055:    }
 4056:    return %returnhash;
 4057: }
 4058: 
 4059: # --------------------------------------------------------------- del interface
 4060: 
 4061: sub del {
 4062:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4063:    my $items='';
 4064:    foreach my $item (@$storearr) {
 4065:        $items.=&escape($item).'&';
 4066:    }
 4067: 
 4068:    $items=~s/\&$//;
 4069:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4070:    if (!$uname) { $uname=$env{'user.name'}; }
 4071:    my $uhome=&homeserver($uname,$udomain);
 4072:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 4073: }
 4074: 
 4075: # -------------------------------------------------------------- dump interface
 4076: 
 4077: sub dump {
 4078:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4079:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4080:     if (!$uname) { $uname=$env{'user.name'}; }
 4081:     my $uhome=&homeserver($uname,$udomain);
 4082:     if ($regexp) {
 4083: 	$regexp=&escape($regexp);
 4084:     } else {
 4085: 	$regexp='.';
 4086:     }
 4087:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4088:     my @pairs=split(/\&/,$rep);
 4089:     my %returnhash=();
 4090:     foreach my $item (@pairs) {
 4091: 	my ($key,$value)=split(/=/,$item,2);
 4092: 	$key = &unescape($key);
 4093: 	next if ($key =~ /^error: 2 /);
 4094: 	$returnhash{$key}=&thaw_unescape($value);
 4095:     }
 4096:     return %returnhash;
 4097: }
 4098: 
 4099: # --------------------------------------------------------- dumpstore interface
 4100: 
 4101: sub dumpstore {
 4102:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4103:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4104:    if (!$uname) { $uname=$env{'user.name'}; }
 4105:    my $uhome=&homeserver($uname,$udomain);
 4106:    if ($regexp) {
 4107:        $regexp=&escape($regexp);
 4108:    } else {
 4109:        $regexp='.';
 4110:    }
 4111:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4112:    my @pairs=split(/\&/,$rep);
 4113:    my %returnhash=();
 4114:    foreach my $item (@pairs) {
 4115:        my ($key,$value)=split(/=/,$item,2);
 4116:        next if ($key =~ /^error: 2 /);
 4117:        $returnhash{$key}=&thaw_unescape($value);
 4118:    }
 4119:    return %returnhash;
 4120: }
 4121: 
 4122: # -------------------------------------------------------------- keys interface
 4123: 
 4124: sub getkeys {
 4125:    my ($namespace,$udomain,$uname)=@_;
 4126:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4127:    if (!$uname) { $uname=$env{'user.name'}; }
 4128:    my $uhome=&homeserver($uname,$udomain);
 4129:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 4130:    my @keyarray=();
 4131:    foreach my $key (split(/\&/,$rep)) {
 4132:       next if ($key =~ /^error: 2 /);
 4133:       push(@keyarray,&unescape($key));
 4134:    }
 4135:    return @keyarray;
 4136: }
 4137: 
 4138: # --------------------------------------------------------------- currentdump
 4139: sub currentdump {
 4140:    my ($courseid,$sdom,$sname)=@_;
 4141:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 4142:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 4143:    $sname    = $env{'user.name'}         if (! defined($sname));
 4144:    my $uhome = &homeserver($sname,$sdom);
 4145:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 4146:    return if ($rep =~ /^(error:|no_such_host)/);
 4147:    #
 4148:    my %returnhash=();
 4149:    #
 4150:    if ($rep eq "unknown_cmd") { 
 4151:        # an old lond will not know currentdump
 4152:        # Do a dump and make it look like a currentdump
 4153:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 4154:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 4155:        my %hash = @tmp;
 4156:        @tmp=();
 4157:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 4158:    } else {
 4159:        my @pairs=split(/\&/,$rep);
 4160:        foreach my $pair (@pairs) {
 4161:            my ($key,$value)=split(/=/,$pair,2);
 4162:            my ($symb,$param) = split(/:/,$key);
 4163:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 4164:                                                         &thaw_unescape($value);
 4165:        }
 4166:    }
 4167:    return %returnhash;
 4168: }
 4169: 
 4170: sub convert_dump_to_currentdump{
 4171:     my %hash = %{shift()};
 4172:     my %returnhash;
 4173:     # Code ripped from lond, essentially.  The only difference
 4174:     # here is the unescaping done by lonnet::dump().  Conceivably
 4175:     # we might run in to problems with parameter names =~ /^v\./
 4176:     while (my ($key,$value) = each(%hash)) {
 4177:         my ($v,$symb,$param) = split(/:/,$key);
 4178: 	$symb  = &unescape($symb);
 4179: 	$param = &unescape($param);
 4180:         next if ($v eq 'version' || $symb eq 'keys');
 4181:         next if (exists($returnhash{$symb}) &&
 4182:                  exists($returnhash{$symb}->{$param}) &&
 4183:                  $returnhash{$symb}->{'v.'.$param} > $v);
 4184:         $returnhash{$symb}->{$param}=$value;
 4185:         $returnhash{$symb}->{'v.'.$param}=$v;
 4186:     }
 4187:     #
 4188:     # Remove all of the keys in the hashes which keep track of
 4189:     # the version of the parameter.
 4190:     while (my ($symb,$param_hash) = each(%returnhash)) {
 4191:         # use a foreach because we are going to delete from the hash.
 4192:         foreach my $key (keys(%$param_hash)) {
 4193:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 4194:         }
 4195:     }
 4196:     return \%returnhash;
 4197: }
 4198: 
 4199: # ------------------------------------------------------ critical inc interface
 4200: 
 4201: sub cinc {
 4202:     return &inc(@_,'critical');
 4203: }
 4204: 
 4205: # --------------------------------------------------------------- inc interface
 4206: 
 4207: sub inc {
 4208:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 4209:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4210:     if (!$uname) { $uname=$env{'user.name'}; }
 4211:     my $uhome=&homeserver($uname,$udomain);
 4212:     my $items='';
 4213:     if (! ref($store)) {
 4214:         # got a single value, so use that instead
 4215:         $items = &escape($store).'=&';
 4216:     } elsif (ref($store) eq 'SCALAR') {
 4217:         $items = &escape($$store).'=&';        
 4218:     } elsif (ref($store) eq 'ARRAY') {
 4219:         $items = join('=&',map {&escape($_);} @{$store});
 4220:     } elsif (ref($store) eq 'HASH') {
 4221:         while (my($key,$value) = each(%{$store})) {
 4222:             $items.= &escape($key).'='.&escape($value).'&';
 4223:         }
 4224:     }
 4225:     $items=~s/\&$//;
 4226:     if ($critical) {
 4227: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 4228:     } else {
 4229: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 4230:     }
 4231: }
 4232: 
 4233: # --------------------------------------------------------------- put interface
 4234: 
 4235: sub put {
 4236:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4237:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4238:    if (!$uname) { $uname=$env{'user.name'}; }
 4239:    my $uhome=&homeserver($uname,$udomain);
 4240:    my $items='';
 4241:    foreach my $item (keys(%$storehash)) {
 4242:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4243:    }
 4244:    $items=~s/\&$//;
 4245:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4246: }
 4247: 
 4248: # ------------------------------------------------------------ newput interface
 4249: 
 4250: sub newput {
 4251:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4252:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4253:    if (!$uname) { $uname=$env{'user.name'}; }
 4254:    my $uhome=&homeserver($uname,$udomain);
 4255:    my $items='';
 4256:    foreach my $key (keys(%$storehash)) {
 4257:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4258:    }
 4259:    $items=~s/\&$//;
 4260:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 4261: }
 4262: 
 4263: # ---------------------------------------------------------  putstore interface
 4264: 
 4265: sub putstore {
 4266:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4267:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4268:    if (!$uname) { $uname=$env{'user.name'}; }
 4269:    my $uhome=&homeserver($uname,$udomain);
 4270:    my $items='';
 4271:    foreach my $key (keys(%$storehash)) {
 4272:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 4273:    }
 4274:    $items=~s/\&$//;
 4275:    my $esc_symb=&escape($symb);
 4276:    my $esc_v=&escape($version);
 4277:    my $reply =
 4278:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 4279: 	      $uhome);
 4280:    if ($reply eq 'unknown_cmd') {
 4281:        # gfall back to way things use to be done
 4282:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 4283: 			    $uname);
 4284:    }
 4285:    return $reply;
 4286: }
 4287: 
 4288: sub old_putstore {
 4289:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4290:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4291:     if (!$uname) { $uname=$env{'user.name'}; }
 4292:     my $uhome=&homeserver($uname,$udomain);
 4293:     my %newstorehash;
 4294:     foreach my $item (keys(%$storehash)) {
 4295: 	my $key = $version.':'.&escape($symb).':'.$item;
 4296: 	$newstorehash{$key} = $storehash->{$item};
 4297:     }
 4298:     my $items='';
 4299:     my %allitems = ();
 4300:     foreach my $item (keys(%newstorehash)) {
 4301: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 4302: 	    my $key = $1.':keys:'.$2;
 4303: 	    $allitems{$key} .= $3.':';
 4304: 	}
 4305: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 4306:     }
 4307:     foreach my $item (keys(%allitems)) {
 4308: 	$allitems{$item} =~ s/\:$//;
 4309: 	$items.= $item.'='.$allitems{$item}.'&';
 4310:     }
 4311:     $items=~s/\&$//;
 4312:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4313: }
 4314: 
 4315: # ------------------------------------------------------ critical put interface
 4316: 
 4317: sub cput {
 4318:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4319:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4320:    if (!$uname) { $uname=$env{'user.name'}; }
 4321:    my $uhome=&homeserver($uname,$udomain);
 4322:    my $items='';
 4323:    foreach my $item (keys(%$storehash)) {
 4324:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4325:    }
 4326:    $items=~s/\&$//;
 4327:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 4328: }
 4329: 
 4330: # -------------------------------------------------------------- eget interface
 4331: 
 4332: sub eget {
 4333:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4334:    my $items='';
 4335:    foreach my $item (@$storearr) {
 4336:        $items.=&escape($item).'&';
 4337:    }
 4338:    $items=~s/\&$//;
 4339:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4340:    if (!$uname) { $uname=$env{'user.name'}; }
 4341:    my $uhome=&homeserver($uname,$udomain);
 4342:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 4343:    my @pairs=split(/\&/,$rep);
 4344:    my %returnhash=();
 4345:    my $i=0;
 4346:    foreach my $item (@$storearr) {
 4347:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4348:       $i++;
 4349:    }
 4350:    return %returnhash;
 4351: }
 4352: 
 4353: # ------------------------------------------------------------ tmpput interface
 4354: sub tmpput {
 4355:     my ($storehash,$server,$context)=@_;
 4356:     my $items='';
 4357:     foreach my $item (keys(%$storehash)) {
 4358: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4359:     }
 4360:     $items=~s/\&$//;
 4361:     if (defined($context)) {
 4362:         $items .= ':'.&escape($context);
 4363:     }
 4364:     return &reply("tmpput:$items",$server);
 4365: }
 4366: 
 4367: # ------------------------------------------------------------ tmpget interface
 4368: sub tmpget {
 4369:     my ($token,$server)=@_;
 4370:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4371:     my $rep=&reply("tmpget:$token",$server);
 4372:     my %returnhash;
 4373:     foreach my $item (split(/\&/,$rep)) {
 4374: 	my ($key,$value)=split(/=/,$item);
 4375:         next if ($key =~ /^error: 2 /);
 4376: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 4377:     }
 4378:     return %returnhash;
 4379: }
 4380: 
 4381: # ------------------------------------------------------------ tmpget interface
 4382: sub tmpdel {
 4383:     my ($token,$server)=@_;
 4384:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4385:     return &reply("tmpdel:$token",$server);
 4386: }
 4387: 
 4388: # -------------------------------------------------- portfolio access checking
 4389: 
 4390: sub portfolio_access {
 4391:     my ($requrl) = @_;
 4392:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4393:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4394:     if ($result) {
 4395:         my %setters;
 4396:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4397:             my ($startblock,$endblock) =
 4398:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4399:             if ($startblock && $endblock) {
 4400:                 return 'B';
 4401:             }
 4402:         } else {
 4403:             my ($startblock,$endblock) =
 4404:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4405:             if ($startblock && $endblock) {
 4406:                 return 'B';
 4407:             }
 4408:         }
 4409:     }
 4410:     if ($result eq 'ok') {
 4411:        return 'F';
 4412:     } elsif ($result =~ /^[^:]+:guest_/) {
 4413:        return 'A';
 4414:     }
 4415:     return '';
 4416: }
 4417: 
 4418: sub get_portfolio_access {
 4419:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4420: 
 4421:     if (!ref($access_hash)) {
 4422: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4423: 	my %access_controls = &get_access_controls($current_perms,$group,
 4424: 						   $file_name);
 4425: 	$access_hash = $access_controls{$file_name};
 4426:     }
 4427: 
 4428:     my ($public,$guest,@domains,@users,@courses,@groups);
 4429:     my $now = time;
 4430:     if (ref($access_hash) eq 'HASH') {
 4431:         foreach my $key (keys(%{$access_hash})) {
 4432:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4433:             if ($start > $now) {
 4434:                 next;
 4435:             }
 4436:             if ($end && $end<$now) {
 4437:                 next;
 4438:             }
 4439:             if ($scope eq 'public') {
 4440:                 $public = $key;
 4441:                 last;
 4442:             } elsif ($scope eq 'guest') {
 4443:                 $guest = $key;
 4444:             } elsif ($scope eq 'domains') {
 4445:                 push(@domains,$key);
 4446:             } elsif ($scope eq 'users') {
 4447:                 push(@users,$key);
 4448:             } elsif ($scope eq 'course') {
 4449:                 push(@courses,$key);
 4450:             } elsif ($scope eq 'group') {
 4451:                 push(@groups,$key);
 4452:             }
 4453:         }
 4454:         if ($public) {
 4455:             return 'ok';
 4456:         }
 4457:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4458:             if ($guest) {
 4459:                 return $guest;
 4460:             }
 4461:         } else {
 4462:             if (@domains > 0) {
 4463:                 foreach my $domkey (@domains) {
 4464:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4465:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4466:                             return 'ok';
 4467:                         }
 4468:                     }
 4469:                 }
 4470:             }
 4471:             if (@users > 0) {
 4472:                 foreach my $userkey (@users) {
 4473:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4474:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4475:                             if (ref($item) eq 'HASH') {
 4476:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4477:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4478:                                     return 'ok';
 4479:                                 }
 4480:                             }
 4481:                         }
 4482:                     } 
 4483:                 }
 4484:             }
 4485:             my %roleshash;
 4486:             my @courses_and_groups = @courses;
 4487:             push(@courses_and_groups,@groups); 
 4488:             if (@courses_and_groups > 0) {
 4489:                 my (%allgroups,%allroles); 
 4490:                 my ($start,$end,$role,$sec,$group);
 4491:                 foreach my $envkey (%env) {
 4492:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4493:                         my $cid = $2.'_'.$3; 
 4494:                         if ($1 eq 'gr') {
 4495:                             $group = $4;
 4496:                             $allgroups{$cid}{$group} = $env{$envkey};
 4497:                         } else {
 4498:                             if ($4 eq '') {
 4499:                                 $sec = 'none';
 4500:                             } else {
 4501:                                 $sec = $4;
 4502:                             }
 4503:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4504:                         }
 4505:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4506:                         my $cid = $2.'_'.$3;
 4507:                         if ($4 eq '') {
 4508:                             $sec = 'none';
 4509:                         } else {
 4510:                             $sec = $4;
 4511:                         }
 4512:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4513:                     }
 4514:                 }
 4515:                 if (keys(%allroles) == 0) {
 4516:                     return;
 4517:                 }
 4518:                 foreach my $key (@courses_and_groups) {
 4519:                     my %content = %{$$access_hash{$key}};
 4520:                     my $cnum = $content{'number'};
 4521:                     my $cdom = $content{'domain'};
 4522:                     my $cid = $cdom.'_'.$cnum;
 4523:                     if (!exists($allroles{$cid})) {
 4524:                         next;
 4525:                     }    
 4526:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4527:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4528:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4529:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4530:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4531:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4532:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4533:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4534:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4535:                                         if (grep/^all$/,@sections) {
 4536:                                             return 'ok';
 4537:                                         } else {
 4538:                                             if (grep/^$sec$/,@sections) {
 4539:                                                 return 'ok';
 4540:                                             }
 4541:                                         }
 4542:                                     }
 4543:                                 }
 4544:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4545:                                     if (grep/^none$/,@groups) {
 4546:                                         return 'ok';
 4547:                                     }
 4548:                                 } else {
 4549:                                     if (grep/^all$/,@groups) {
 4550:                                         return 'ok';
 4551:                                     } 
 4552:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4553:                                         if (grep/^$group$/,@groups) {
 4554:                                             return 'ok';
 4555:                                         }
 4556:                                     }
 4557:                                 } 
 4558:                             }
 4559:                         }
 4560:                     }
 4561:                 }
 4562:             }
 4563:             if ($guest) {
 4564:                 return $guest;
 4565:             }
 4566:         }
 4567:     }
 4568:     return;
 4569: }
 4570: 
 4571: sub course_group_datechecker {
 4572:     my ($dates,$now,$status) = @_;
 4573:     my ($start,$end) = split(/\./,$dates);
 4574:     if (!$start && !$end) {
 4575:         return 'ok';
 4576:     }
 4577:     if (grep/^active$/,@{$status}) {
 4578:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4579:             return 'ok';
 4580:         }
 4581:     }
 4582:     if (grep/^previous$/,@{$status}) {
 4583:         if ($end > $now ) {
 4584:             return 'ok';
 4585:         }
 4586:     }
 4587:     if (grep/^future$/,@{$status}) {
 4588:         if ($start > $now) {
 4589:             return 'ok';
 4590:         }
 4591:     }
 4592:     return; 
 4593: }
 4594: 
 4595: sub parse_portfolio_url {
 4596:     my ($url) = @_;
 4597: 
 4598:     my ($type,$udom,$unum,$group,$file_name);
 4599:     
 4600:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4601: 	$type = 1;
 4602:         $udom = $1;
 4603:         $unum = $2;
 4604:         $file_name = $3;
 4605:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4606: 	$type = 2;
 4607:         $udom = $1;
 4608:         $unum = $2;
 4609:         $group = $3;
 4610:         $file_name = $3.'/'.$4;
 4611:     }
 4612:     if (wantarray) {
 4613: 	return ($type,$udom,$unum,$file_name,$group);
 4614:     }
 4615:     return $type;
 4616: }
 4617: 
 4618: sub is_portfolio_url {
 4619:     my ($url) = @_;
 4620:     return scalar(&parse_portfolio_url($url));
 4621: }
 4622: 
 4623: sub is_portfolio_file {
 4624:     my ($file) = @_;
 4625:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4626:         return 1;
 4627:     }
 4628:     return;
 4629: }
 4630: 
 4631: sub usertools_access {
 4632:     my ($uname,$udom,$tool,$action,$context) = @_;
 4633:     my ($access,%tools);
 4634:     if ($context eq '') {
 4635:         $context = 'tools';
 4636:     }
 4637:     if ($context eq 'requestcourses') {
 4638:         %tools = (
 4639:                       official   => 1,
 4640:                       unofficial => 1,
 4641:                       community  => 1,
 4642:                  );
 4643:     } else {
 4644:         %tools = (
 4645:                       aboutme   => 1,
 4646:                       blog      => 1,
 4647:                       portfolio => 1,
 4648:                  );
 4649:     }
 4650:     return if (!defined($tools{$tool}));
 4651: 
 4652:     if ((!defined($udom)) || (!defined($uname))) {
 4653:         $udom = $env{'user.domain'};
 4654:         $uname = $env{'user.name'};
 4655:     }
 4656: 
 4657:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4658:         if ($action ne 'reload') {
 4659:             if ($context eq 'requestcourses') {
 4660:                 return $env{'environment.canrequest.'.$tool};
 4661:             } else {
 4662:                 return $env{'environment.availabletools.'.$tool};
 4663:             }
 4664:         }
 4665:     }
 4666: 
 4667:     my ($toolstatus,$inststatus);
 4668: 
 4669:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 4670:          ($action ne 'reload')) {
 4671:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 4672:         $inststatus = $env{'environment.inststatus'};
 4673:     } else {
 4674:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool);
 4675:         $toolstatus = $userenv{$context.'.'.$tool};
 4676:         $inststatus = $userenv{'inststatus'};
 4677:     }
 4678: 
 4679:     if ($toolstatus ne '') {
 4680:         if ($toolstatus) {
 4681:             $access = 1;
 4682:         } else {
 4683:             $access = 0;
 4684:         }
 4685:         return $access;
 4686:     }
 4687: 
 4688:     my $is_adv = &is_advanced_user($udom,$uname);
 4689:     my %domdef = &get_domain_defaults($udom);
 4690:     if (ref($domdef{$tool}) eq 'HASH') {
 4691:         if ($is_adv) {
 4692:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 4693:                 if ($domdef{$tool}{'_LC_adv'}) { 
 4694:                     $access = 1;
 4695:                 } else {
 4696:                     $access = 0;
 4697:                 }
 4698:                 return $access;
 4699:             }
 4700:         }
 4701:         if ($inststatus ne '') {
 4702:             my ($hasaccess,$hasnoaccess);
 4703:             foreach my $affiliation (split(/:/,$inststatus)) {
 4704:                 if ($domdef{$tool}{$affiliation} ne '') { 
 4705:                     if ($domdef{$tool}{$affiliation}) {
 4706:                         $hasaccess = 1;
 4707:                     } else {
 4708:                         $hasnoaccess = 1;
 4709:                     }
 4710:                 }
 4711:             }
 4712:             if ($hasaccess || $hasnoaccess) {
 4713:                 if ($hasaccess) {
 4714:                     $access = 1;
 4715:                 } elsif ($hasnoaccess) {
 4716:                     $access = 0; 
 4717:                 }
 4718:                 return $access;
 4719:             }
 4720:         } else {
 4721:             if ($domdef{$tool}{'default'} ne '') {
 4722:                 if ($domdef{$tool}{'default'}) {
 4723:                     $access = 1;
 4724:                 } elsif ($domdef{$tool}{'default'} == 0) {
 4725:                     $access = 0;
 4726:                 }
 4727:                 return $access;
 4728:             }
 4729:         }
 4730:     } else {
 4731:         if ($context eq 'tools') {
 4732:             $access = 1;
 4733:         } else {
 4734:             $access = 0;
 4735:         }
 4736:         return $access;
 4737:     }
 4738: }
 4739: 
 4740: sub is_advanced_user {
 4741:     my ($udom,$uname) = @_;
 4742:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 4743:     my %allroles;
 4744:     my $is_adv;
 4745:     foreach my $role (keys(%roleshash)) {
 4746:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 4747:         my $area = '/'.$tdomain.'/'.$trest;
 4748:         if ($sec ne '') {
 4749:             $area .= '/'.$sec;
 4750:         }
 4751:         if (($area ne '') && ($trole ne '')) {
 4752:             my $spec=$trole.'.'.$area;
 4753:             if ($trole =~ /^cr\//) {
 4754:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4755:             } elsif ($trole ne 'gr') {
 4756:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4757:             }
 4758:         }
 4759:     }
 4760:     foreach my $role (keys(%allroles)) {
 4761:         last if ($is_adv);
 4762:         foreach my $item (split(/:/,$allroles{$role})) {
 4763:             if ($item ne '') {
 4764:                 my ($privilege,$restrictions)=split(/&/,$item);
 4765:                 if ($privilege eq 'adv') {
 4766:                     $is_adv = 1;
 4767:                     last;
 4768:                 }
 4769:             }
 4770:         }
 4771:     }
 4772:     return $is_adv;
 4773: }
 4774: 
 4775: # ---------------------------------------------- Custom access rule evaluation
 4776: 
 4777: sub customaccess {
 4778:     my ($priv,$uri)=@_;
 4779:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4780:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4781:     $udom = &LONCAPA::clean_domain($udom);
 4782:     $ucrs = &LONCAPA::clean_username($ucrs);
 4783:     my $access=0;
 4784:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4785: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4786: 	if ($type eq 'user') {
 4787: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4788: 		my ($tdom,$tuname)=split(m{/},$scope);
 4789: 		if ($tdom) {
 4790: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4791: 		}
 4792: 		if ($tuname) {
 4793: 		    if ($tuname ne $env{'user.name'}) { next; }
 4794: 		}
 4795: 		$access=($effect eq 'allow');
 4796: 		last;
 4797: 	    }
 4798: 	} else {
 4799: 	    if ($role) {
 4800: 		if ($role ne $urole) { next; }
 4801: 	    }
 4802: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4803: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4804: 		if ($tdom) {
 4805: 		    if ($tdom ne $udom) { next; }
 4806: 		}
 4807: 		if ($tcrs) {
 4808: 		    if ($tcrs ne $ucrs) { next; }
 4809: 		}
 4810: 		if ($tsec) {
 4811: 		    if ($tsec ne $usec) { next; }
 4812: 		}
 4813: 		$access=($effect eq 'allow');
 4814: 		last;
 4815: 	    }
 4816: 	    if ($realm eq '' && $role eq '') {
 4817: 		$access=($effect eq 'allow');
 4818: 	    }
 4819: 	}
 4820:     }
 4821:     return $access;
 4822: }
 4823: 
 4824: # ------------------------------------------------- Check for a user privilege
 4825: 
 4826: sub allowed {
 4827:     my ($priv,$uri,$symb,$role)=@_;
 4828:     my $ver_orguri=$uri;
 4829:     $uri=&deversion($uri);
 4830:     my $orguri=$uri;
 4831:     $uri=&declutter($uri);
 4832: 
 4833:     if ($priv eq 'evb') {
 4834: # Evade communication block restrictions for specified role in a course
 4835:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4836:             return $1;
 4837:         } else {
 4838:             return;
 4839:         }
 4840:     }
 4841: 
 4842:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4843: # Free bre access to adm and meta resources
 4844:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4845: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4846: 	&& ($priv eq 'bre')) {
 4847: 	return 'F';
 4848:     }
 4849: 
 4850: # Free bre access to user's own portfolio contents
 4851:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4852:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4853: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4854:         my %setters;
 4855:         my ($startblock,$endblock) = 
 4856:             &Apache::loncommon::blockcheck(\%setters,'port');
 4857:         if ($startblock && $endblock) {
 4858:             return 'B';
 4859:         } else {
 4860:             return 'F';
 4861:         }
 4862:     }
 4863: 
 4864: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4865:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4866:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4867:         if (exists($env{'request.course.id'})) {
 4868:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4869:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4870:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4871:                 my $courseprivid=$env{'request.course.id'};
 4872:                 $courseprivid=~s/\_/\//;
 4873:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4874:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4875:                     return $1; 
 4876:                 } else {
 4877:                     if ($env{'request.course.sec'}) {
 4878:                         $courseprivid.='/'.$env{'request.course.sec'};
 4879:                     }
 4880:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4881:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4882:                         return $2;
 4883:                     }
 4884:                 }
 4885:             }
 4886:         }
 4887:     }
 4888: 
 4889: # Free bre to public access
 4890: 
 4891:     if ($priv eq 'bre') {
 4892:         my $copyright=&metadata($uri,'copyright');
 4893: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4894:            return 'F'; 
 4895:         }
 4896:         if ($copyright eq 'priv') {
 4897:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4898: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4899: 		return '';
 4900:             }
 4901:         }
 4902:         if ($copyright eq 'domain') {
 4903:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4904: 	    unless (($env{'user.domain'} eq $1) ||
 4905:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4906: 		return '';
 4907:             }
 4908:         }
 4909:         if ($env{'request.role'}=~ /li\.\//) {
 4910:             # Library role, so allow browsing of resources in this domain.
 4911:             return 'F';
 4912:         }
 4913:         if ($copyright eq 'custom') {
 4914: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4915:         }
 4916:     }
 4917:     # Domain coordinator is trying to create a course
 4918:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4919:         # uri is the requested domain in this case.
 4920:         # comparison to 'request.role.domain' shows if the user has selected
 4921:         # a role of dc for the domain in question.
 4922:         return 'F' if ($uri eq $env{'request.role.domain'});
 4923:     }
 4924: 
 4925:     my $thisallowed='';
 4926:     my $statecond=0;
 4927:     my $courseprivid='';
 4928: 
 4929: # Course
 4930: 
 4931:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4932:        $thisallowed.=$1;
 4933:     }
 4934: 
 4935: # Domain
 4936: 
 4937:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4938:        =~/\Q$priv\E\&([^\:]*)/) {
 4939:        $thisallowed.=$1;
 4940:     }
 4941: 
 4942: # Course: uri itself is a course
 4943:     my $courseuri=$uri;
 4944:     $courseuri=~s/\_(\d)/\/$1/;
 4945:     $courseuri=~s/^([^\/])/\/$1/;
 4946: 
 4947:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 4948:        =~/\Q$priv\E\&([^\:]*)/) {
 4949:        $thisallowed.=$1;
 4950:     }
 4951: 
 4952: # URI is an uploaded document for this course, default permissions don't matter
 4953: # not allowing 'edit' access (editupload) to uploaded course docs
 4954:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 4955: 	$thisallowed='';
 4956:         my ($match)=&is_on_map($uri);
 4957:         if ($match) {
 4958:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 4959:                   =~/\Q$priv\E\&([^\:]*)/) {
 4960:                 $thisallowed.=$1;
 4961:             }
 4962:         } else {
 4963:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 4964:             if ($refuri) {
 4965:                 if ($refuri =~ m|^/adm/|) {
 4966:                     $thisallowed='F';
 4967:                 } else {
 4968:                     $refuri=&declutter($refuri);
 4969:                     my ($match) = &is_on_map($refuri);
 4970:                     if ($match) {
 4971:                         $thisallowed='F';
 4972:                     }
 4973:                 }
 4974:             }
 4975:         }
 4976:     }
 4977: 
 4978:     if ($priv eq 'bre'
 4979: 	&& $thisallowed ne 'F' 
 4980: 	&& $thisallowed ne '2'
 4981: 	&& &is_portfolio_url($uri)) {
 4982: 	$thisallowed = &portfolio_access($uri);
 4983:     }
 4984:     
 4985: # Full access at system, domain or course-wide level? Exit.
 4986:     if ($thisallowed=~/F/) {
 4987: 	return 'F';
 4988:     }
 4989: 
 4990: # If this is generating or modifying users, exit with special codes
 4991: 
 4992:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4993: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4994: 	    my ($audom,$auname)=split('/',$uri);
 4995: # no author name given, so this just checks on the general right to make a co-author in this domain
 4996: 	    unless ($auname) { return $thisallowed; }
 4997: # an author name is given, so we are about to actually make a co-author for a certain account
 4998: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4999: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 5000: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 5001: 	}
 5002: 	return $thisallowed;
 5003:     }
 5004: #
 5005: # Gathered so far: system, domain and course wide privileges
 5006: #
 5007: # Course: See if uri or referer is an individual resource that is part of 
 5008: # the course
 5009: 
 5010:     if ($env{'request.course.id'}) {
 5011: 
 5012:        $courseprivid=$env{'request.course.id'};
 5013:        if ($env{'request.course.sec'}) {
 5014:           $courseprivid.='/'.$env{'request.course.sec'};
 5015:        }
 5016:        $courseprivid=~s/\_/\//;
 5017:        my $checkreferer=1;
 5018:        my ($match,$cond)=&is_on_map($uri);
 5019:        if ($match) {
 5020:            $statecond=$cond;
 5021:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 5022:                =~/\Q$priv\E\&([^\:]*)/) {
 5023:                $thisallowed.=$1;
 5024:                $checkreferer=0;
 5025:            }
 5026:        }
 5027:        
 5028:        if ($checkreferer) {
 5029: 	  my $refuri=$env{'httpref.'.$orguri};
 5030:             unless ($refuri) {
 5031:                 foreach my $key (keys(%env)) {
 5032: 		    if ($key=~/^httpref\..*\*/) {
 5033: 			my $pattern=$key;
 5034:                         $pattern=~s/^httpref\.\/res\///;
 5035:                         $pattern=~s/\*/\[\^\/\]\+/g;
 5036:                         $pattern=~s/\//\\\//g;
 5037:                         if ($orguri=~/$pattern/) {
 5038: 			    $refuri=$env{$key};
 5039:                         }
 5040:                     }
 5041:                 }
 5042:             }
 5043: 
 5044:          if ($refuri) { 
 5045: 	  $refuri=&declutter($refuri);
 5046:           my ($match,$cond)=&is_on_map($refuri);
 5047:             if ($match) {
 5048:               my $refstatecond=$cond;
 5049:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 5050:                   =~/\Q$priv\E\&([^\:]*)/) {
 5051:                   $thisallowed.=$1;
 5052:                   $uri=$refuri;
 5053:                   $statecond=$refstatecond;
 5054:               }
 5055:           }
 5056:         }
 5057:        }
 5058:    }
 5059: 
 5060: #
 5061: # Gathered now: all privileges that could apply, and condition number
 5062: # 
 5063: #
 5064: # Full or no access?
 5065: #
 5066: 
 5067:     if ($thisallowed=~/F/) {
 5068: 	return 'F';
 5069:     }
 5070: 
 5071:     unless ($thisallowed) {
 5072:         return '';
 5073:     }
 5074: 
 5075: # Restrictions exist, deal with them
 5076: #
 5077: #   C:according to course preferences
 5078: #   R:according to resource settings
 5079: #   L:unless locked
 5080: #   X:according to user session state
 5081: #
 5082: 
 5083: # Possibly locked functionality, check all courses
 5084: # Locks might take effect only after 10 minutes cache expiration for other
 5085: # courses, and 2 minutes for current course
 5086: 
 5087:     my $envkey;
 5088:     if ($thisallowed=~/L/) {
 5089:         foreach $envkey (keys(%env)) {
 5090:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 5091:                my $courseid=$2;
 5092:                my $roleid=$1.'.'.$2;
 5093:                $courseid=~s/^\///;
 5094:                my $expiretime=600;
 5095:                if ($env{'request.role'} eq $roleid) {
 5096: 		  $expiretime=120;
 5097:                }
 5098: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 5099:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 5100:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 5101: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 5102:                }
 5103:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5104:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 5105: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 5106:                        &log($env{'user.domain'},$env{'user.name'},
 5107:                             $env{'user.home'},
 5108:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 5109:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5110:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5111: 		       return '';
 5112:                    }
 5113:                }
 5114:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5115:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 5116: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 5117:                        &log($env{'user.domain'},$env{'user.name'},
 5118:                             $env{'user.home'},
 5119:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 5120:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5121:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5122: 		       return '';
 5123:                    }
 5124:                }
 5125: 	   }
 5126:        }
 5127:     }
 5128:    
 5129: #
 5130: # Rest of the restrictions depend on selected course
 5131: #
 5132: 
 5133:     unless ($env{'request.course.id'}) {
 5134: 	if ($thisallowed eq 'A') {
 5135: 	    return 'A';
 5136:         } elsif ($thisallowed eq 'B') {
 5137:             return 'B';
 5138: 	} else {
 5139: 	    return '1';
 5140: 	}
 5141:     }
 5142: 
 5143: #
 5144: # Now user is definitely in a course
 5145: #
 5146: 
 5147: 
 5148: # Course preferences
 5149: 
 5150:    if ($thisallowed=~/C/) {
 5151:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5152:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 5153:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 5154: 	   =~/\Q$rolecode\E/) {
 5155: 	   if ($priv ne 'pch') { 
 5156: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5157: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 5158: 			$env{'request.course.id'});
 5159: 	   }
 5160:            return '';
 5161:        }
 5162: 
 5163:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 5164: 	   =~/\Q$unamedom\E/) {
 5165: 	   if ($priv ne 'pch') { 
 5166: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 5167: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 5168: 			$env{'request.course.id'});
 5169: 	   }
 5170:            return '';
 5171:        }
 5172:    }
 5173: 
 5174: # Resource preferences
 5175: 
 5176:    if ($thisallowed=~/R/) {
 5177:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5178:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 5179: 	   if ($priv ne 'pch') { 
 5180: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5181: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 5182: 	   }
 5183: 	   return '';
 5184:        }
 5185:    }
 5186: 
 5187: # Restricted by state or randomout?
 5188: 
 5189:    if ($thisallowed=~/X/) {
 5190:       if ($env{'acc.randomout'}) {
 5191: 	 if (!$symb) { $symb=&symbread($uri,1); }
 5192:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 5193:             return ''; 
 5194:          }
 5195:       }
 5196:       if (&condval($statecond)) {
 5197: 	 return '2';
 5198:       } else {
 5199:          return '';
 5200:       }
 5201:    }
 5202: 
 5203:     if ($thisallowed eq 'A') {
 5204: 	return 'A';
 5205:     } elsif ($thisallowed eq 'B') {
 5206:         return 'B';
 5207:     }
 5208:    return 'F';
 5209: }
 5210: 
 5211: sub split_uri_for_cond {
 5212:     my $uri=&deversion(&declutter(shift));
 5213:     my @uriparts=split(/\//,$uri);
 5214:     my $filename=pop(@uriparts);
 5215:     my $pathname=join('/',@uriparts);
 5216:     return ($pathname,$filename);
 5217: }
 5218: # --------------------------------------------------- Is a resource on the map?
 5219: 
 5220: sub is_on_map {
 5221:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 5222:     #Trying to find the conditional for the file
 5223:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 5224: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 5225:     if ($match) {
 5226: 	return (1,$1);
 5227:     } else {
 5228: 	return (0,0);
 5229:     }
 5230: }
 5231: 
 5232: # --------------------------------------------------------- Get symb from alias
 5233: 
 5234: sub get_symb_from_alias {
 5235:     my $symb=shift;
 5236:     my ($map,$resid,$url)=&decode_symb($symb);
 5237: # Already is a symb
 5238:     if ($url) { return $symb; }
 5239: # Must be an alias
 5240:     my $aliassymb='';
 5241:     my %bighash;
 5242:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5243:                             &GDBM_READER(),0640)) {
 5244:         my $rid=$bighash{'mapalias_'.$symb};
 5245: 	if ($rid) {
 5246: 	    my ($mapid,$resid)=split(/\./,$rid);
 5247: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 5248: 				    $resid,$bighash{'src_'.$rid});
 5249: 	}
 5250:         untie %bighash;
 5251:     }
 5252:     return $aliassymb;
 5253: }
 5254: 
 5255: # ----------------------------------------------------------------- Define Role
 5256: 
 5257: sub definerole {
 5258:   if (allowed('mcr','/')) {
 5259:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 5260:     foreach my $role (split(':',$sysrole)) {
 5261: 	my ($crole,$cqual)=split(/\&/,$role);
 5262:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 5263:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 5264: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5265:                return "refused:s:$crole&$cqual"; 
 5266:             }
 5267:         }
 5268:     }
 5269:     foreach my $role (split(':',$domrole)) {
 5270: 	my ($crole,$cqual)=split(/\&/,$role);
 5271:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 5272:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 5273: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 5274:                return "refused:d:$crole&$cqual"; 
 5275:             }
 5276:         }
 5277:     }
 5278:     foreach my $role (split(':',$courole)) {
 5279: 	my ($crole,$cqual)=split(/\&/,$role);
 5280:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 5281:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 5282: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5283:                return "refused:c:$crole&$cqual"; 
 5284:             }
 5285:         }
 5286:     }
 5287:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5288:                 "$env{'user.domain'}:$env{'user.name'}:".
 5289: 	        "rolesdef_$rolename=".
 5290:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 5291:     return reply($command,$env{'user.home'});
 5292:   } else {
 5293:     return 'refused';
 5294:   }
 5295: }
 5296: 
 5297: # ---------------- Make a metadata query against the network of library servers
 5298: 
 5299: sub metadata_query {
 5300:     my ($query,$custom,$customshow,$server_array)=@_;
 5301:     my %rhash;
 5302:     my %libserv = &all_library();
 5303:     my @server_list = (defined($server_array) ? @$server_array
 5304:                                               : keys(%libserv) );
 5305:     for my $server (@server_list) {
 5306: 	unless ($custom or $customshow) {
 5307: 	    my $reply=&reply("querysend:".&escape($query),$server);
 5308: 	    $rhash{$server}=$reply;
 5309: 	}
 5310: 	else {
 5311: 	    my $reply=&reply("querysend:".&escape($query).':'.
 5312: 			     &escape($custom).':'.&escape($customshow),
 5313: 			     $server);
 5314: 	    $rhash{$server}=$reply;
 5315: 	}
 5316:     }
 5317:     return \%rhash;
 5318: }
 5319: 
 5320: # ----------------------------------------- Send log queries and wait for reply
 5321: 
 5322: sub log_query {
 5323:     my ($uname,$udom,$query,%filters)=@_;
 5324:     my $uhome=&homeserver($uname,$udom);
 5325:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 5326:     my $uhost=&hostname($uhome);
 5327:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 5328:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 5329:                        $uhome);
 5330:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 5331:     return get_query_reply($queryid);
 5332: }
 5333: 
 5334: # -------------------------- Update MySQL table for portfolio file
 5335: 
 5336: sub update_portfolio_table {
 5337:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 5338:     if ($group ne '') {
 5339:         $file_name =~s /^\Q$group\E//;
 5340:     }
 5341:     my $homeserver = &homeserver($uname,$udom);
 5342:     my $queryid=
 5343:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 5344:                ':'.&escape($file_name).':'.$action,$homeserver);
 5345:     my $reply = &get_query_reply($queryid);
 5346:     return $reply;
 5347: }
 5348: 
 5349: # -------------------------- Update MySQL allusers table
 5350: 
 5351: sub update_allusers_table {
 5352:     my ($uname,$udom,$names) = @_;
 5353:     my $homeserver = &homeserver($uname,$udom);
 5354:     my $queryid=
 5355:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 5356:                'lastname='.&escape($names->{'lastname'}).'%%'.
 5357:                'firstname='.&escape($names->{'firstname'}).'%%'.
 5358:                'middlename='.&escape($names->{'middlename'}).'%%'.
 5359:                'generation='.&escape($names->{'generation'}).'%%'.
 5360:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 5361:                'id='.&escape($names->{'id'}),$homeserver);
 5362:     my $reply = &get_query_reply($queryid);
 5363:     return $reply;
 5364: }
 5365: 
 5366: # ------- Request retrieval of institutional classlists for course(s)
 5367: 
 5368: sub fetch_enrollment_query {
 5369:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 5370:     my $homeserver;
 5371:     my $maxtries = 1;
 5372:     if ($context eq 'automated') {
 5373:         $homeserver = $perlvar{'lonHostID'};
 5374:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 5375:     } else {
 5376:         $homeserver = &homeserver($cnum,$dom);
 5377:     }
 5378:     my $host=&hostname($homeserver);
 5379:     my $cmd = '';
 5380:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5381:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5382:     }
 5383:     $cmd =~ s/%%$//;
 5384:     $cmd = &escape($cmd);
 5385:     my $query = 'fetchenrollment';
 5386:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 5387:     unless ($queryid=~/^\Q$host\E\_/) { 
 5388:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 5389:         return 'error: '.$queryid;
 5390:     }
 5391:     my $reply = &get_query_reply($queryid);
 5392:     my $tries = 1;
 5393:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5394:         $reply = &get_query_reply($queryid);
 5395:         $tries ++;
 5396:     }
 5397:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5398:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5399:     } else {
 5400:         my @responses = split(/:/,$reply);
 5401:         if ($homeserver eq $perlvar{'lonHostID'}) {
 5402:             foreach my $line (@responses) {
 5403:                 my ($key,$value) = split(/=/,$line,2);
 5404:                 $$replyref{$key} = $value;
 5405:             }
 5406:         } else {
 5407:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 5408:             foreach my $line (@responses) {
 5409:                 my ($key,$value) = split(/=/,$line);
 5410:                 $$replyref{$key} = $value;
 5411:                 if ($value > 0) {
 5412:                     foreach my $item (@{$$affiliatesref{$key}}) {
 5413:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 5414:                         my $destname = $pathname.'/'.$filename;
 5415:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 5416:                         if ($xml_classlist =~ /^error/) {
 5417:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 5418:                         } else {
 5419:                             if ( open(FILE,">$destname") ) {
 5420:                                 print FILE &unescape($xml_classlist);
 5421:                                 close(FILE);
 5422:                             } else {
 5423:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 5424:                             }
 5425:                         }
 5426:                     }
 5427:                 }
 5428:             }
 5429:         }
 5430:         return 'ok';
 5431:     }
 5432:     return 'error';
 5433: }
 5434: 
 5435: sub get_query_reply {
 5436:     my $queryid=shift;
 5437:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 5438:     my $reply='';
 5439:     for (1..100) {
 5440: 	sleep 2;
 5441:         if (-e $replyfile.'.end') {
 5442: 	    if (open(my $fh,$replyfile)) {
 5443: 		$reply = join('',<$fh>);
 5444: 		close($fh);
 5445: 	   } else { return 'error: reply_file_error'; }
 5446:            return &unescape($reply);
 5447: 	}
 5448:     }
 5449:     return 'timeout:'.$queryid;
 5450: }
 5451: 
 5452: sub courselog_query {
 5453: #
 5454: # possible filters:
 5455: # url: url or symb
 5456: # username
 5457: # domain
 5458: # action: view, submit, grade
 5459: # start: timestamp
 5460: # end: timestamp
 5461: #
 5462:     my (%filters)=@_;
 5463:     unless ($env{'request.course.id'}) { return 'no_course'; }
 5464:     if ($filters{'url'}) {
 5465: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 5466:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 5467:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 5468:     }
 5469:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5470:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5471:     return &log_query($cname,$cdom,'courselog',%filters);
 5472: }
 5473: 
 5474: sub userlog_query {
 5475: #
 5476: # possible filters:
 5477: # action: log check role
 5478: # start: timestamp
 5479: # end: timestamp
 5480: #
 5481:     my ($uname,$udom,%filters)=@_;
 5482:     return &log_query($uname,$udom,'userlog',%filters);
 5483: }
 5484: 
 5485: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 5486: 
 5487: sub auto_run {
 5488:     my ($cnum,$cdom) = @_;
 5489:     my $response = 0;
 5490:     my $settings;
 5491:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 5492:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5493:         $settings = $domconfig{'autoenroll'};
 5494:         if ($settings->{'run'} eq '1') {
 5495:             $response = 1;
 5496:         }
 5497:     } else {
 5498:         my $homeserver;
 5499:         if (&is_course($cdom,$cnum)) {
 5500:             $homeserver = &homeserver($cnum,$cdom);
 5501:         } else {
 5502:             $homeserver = &domain($cdom,'primary');
 5503:         }
 5504:         if ($homeserver ne 'no_host') {
 5505:             $response = &reply('autorun:'.$cdom,$homeserver);
 5506:         }
 5507:     }
 5508:     return $response;
 5509: }
 5510: 
 5511: sub auto_get_sections {
 5512:     my ($cnum,$cdom,$inst_coursecode) = @_;
 5513:     my $homeserver;
 5514:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 5515:         $homeserver = &homeserver($cnum,$cdom);
 5516:     }
 5517:     if (!defined($homeserver)) { 
 5518:         if ($cdom =~ /^$match_domain$/) {
 5519:             $homeserver = &domain($cdom,'primary');
 5520:         }
 5521:     }
 5522:     my @secs;
 5523:     if (defined($homeserver)) {
 5524:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 5525:         unless ($response eq 'refused') {
 5526:             @secs = split(/:/,$response);
 5527:         }
 5528:     }
 5529:     return @secs;
 5530: }
 5531: 
 5532: sub auto_new_course {
 5533:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 5534:     my $homeserver = &homeserver($cnum,$cdom);
 5535:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 5536:     return $response;
 5537: }
 5538: 
 5539: sub auto_validate_courseID {
 5540:     my ($cnum,$cdom,$inst_course_id) = @_;
 5541:     my $homeserver = &homeserver($cnum,$cdom);
 5542:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5543:     return $response;
 5544: }
 5545: 
 5546: sub auto_validate_instcode {
 5547:     my ($cnum,$cdom,$instcode,$owner) = @_;
 5548:     my ($homeserver,$response);
 5549:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5550:         $homeserver = &homeserver($cnum,$cdom);
 5551:     }
 5552:     if (!defined($homeserver)) {
 5553:         if ($cdom =~ /^$match_domain$/) {
 5554:             $homeserver = &domain($cdom,'primary');
 5555:         }
 5556:     }
 5557:     my $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 5558:                            &escape($instcode).':'.&escape($owner),$homeserver));
 5559:     return $response;
 5560: }
 5561: 
 5562: sub auto_create_password {
 5563:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5564:     my ($homeserver,$response);
 5565:     my $create_passwd = 0;
 5566:     my $authchk = '';
 5567:     if ($udom =~ /^$match_domain$/) {
 5568:         $homeserver = &domain($udom,'primary');
 5569:     }
 5570:     if ($homeserver eq '') {
 5571:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5572:             $homeserver = &homeserver($cnum,$cdom);
 5573:         }
 5574:     }
 5575:     if ($homeserver eq '') {
 5576:         $authchk = 'nodomain';
 5577:     } else {
 5578:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5579:         if ($response eq 'refused') {
 5580:             $authchk = 'refused';
 5581:         } else {
 5582:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5583:         }
 5584:     }
 5585:     return ($authparam,$create_passwd,$authchk);
 5586: }
 5587: 
 5588: sub auto_photo_permission {
 5589:     my ($cnum,$cdom,$students) = @_;
 5590:     my $homeserver = &homeserver($cnum,$cdom);
 5591:     my ($outcome,$perm_reqd,$conditions) = 
 5592: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5593:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5594: 	return (undef,undef);
 5595:     }
 5596:     return ($outcome,$perm_reqd,$conditions);
 5597: }
 5598: 
 5599: sub auto_checkphotos {
 5600:     my ($uname,$udom,$pid) = @_;
 5601:     my $homeserver = &homeserver($uname,$udom);
 5602:     my ($result,$resulttype);
 5603:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5604: 				   &escape($uname).':'.&escape($pid),
 5605: 				   $homeserver));
 5606:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5607: 	return (undef,undef);
 5608:     }
 5609:     if ($outcome) {
 5610:         ($result,$resulttype) = split(/:/,$outcome);
 5611:     } 
 5612:     return ($result,$resulttype);
 5613: }
 5614: 
 5615: sub auto_photochoice {
 5616:     my ($cnum,$cdom) = @_;
 5617:     my $homeserver = &homeserver($cnum,$cdom);
 5618:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5619: 						       &escape($cdom),
 5620: 						       $homeserver)));
 5621:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5622: 	return (undef,undef);
 5623:     }
 5624:     return ($update,$comment);
 5625: }
 5626: 
 5627: sub auto_photoupdate {
 5628:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5629:     my $homeserver = &homeserver($cnum,$dom);
 5630:     my $host=&hostname($homeserver);
 5631:     my $cmd = '';
 5632:     my $maxtries = 1;
 5633:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5634:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5635:     }
 5636:     $cmd =~ s/%%$//;
 5637:     $cmd = &escape($cmd);
 5638:     my $query = 'institutionalphotos';
 5639:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5640:     unless ($queryid=~/^\Q$host\E\_/) {
 5641:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5642:         return 'error: '.$queryid;
 5643:     }
 5644:     my $reply = &get_query_reply($queryid);
 5645:     my $tries = 1;
 5646:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5647:         $reply = &get_query_reply($queryid);
 5648:         $tries ++;
 5649:     }
 5650:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5651:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5652:     } else {
 5653:         my @responses = split(/:/,$reply);
 5654:         my $outcome = shift(@responses); 
 5655:         foreach my $item (@responses) {
 5656:             my ($key,$value) = split(/=/,$item);
 5657:             $$photo{$key} = $value;
 5658:         }
 5659:         return $outcome;
 5660:     }
 5661:     return 'error';
 5662: }
 5663: 
 5664: sub auto_instcode_format {
 5665:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5666: 	$cat_order) = @_;
 5667:     my $courses = '';
 5668:     my @homeservers;
 5669:     if ($caller eq 'global') {
 5670: 	my %servers = &get_servers($codedom,'library');
 5671: 	foreach my $tryserver (keys(%servers)) {
 5672: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5673: 		push(@homeservers,$tryserver);
 5674: 	    }
 5675:         }
 5676:     } else {
 5677:         push(@homeservers,&homeserver($caller,$codedom));
 5678:     }
 5679:     foreach my $code (keys(%{$instcodes})) {
 5680:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5681:     }
 5682:     chop($courses);
 5683:     my $ok_response = 0;
 5684:     my $response;
 5685:     while (@homeservers > 0 && $ok_response == 0) {
 5686:         my $server = shift(@homeservers); 
 5687:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5688:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5689:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5690: 		split(/:/,$response);
 5691:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5692:             push(@{$codetitles},&str2array($codetitles_str));
 5693:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5694:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5695:             $ok_response = 1;
 5696:         }
 5697:     }
 5698:     if ($ok_response) {
 5699:         return 'ok';
 5700:     } else {
 5701:         return $response;
 5702:     }
 5703: }
 5704: 
 5705: sub auto_instcode_defaults {
 5706:     my ($domain,$returnhash,$code_order) = @_;
 5707:     my @homeservers;
 5708: 
 5709:     my %servers = &get_servers($domain,'library');
 5710:     foreach my $tryserver (keys(%servers)) {
 5711: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5712: 	    push(@homeservers,$tryserver);
 5713: 	}
 5714:     }
 5715: 
 5716:     my $response;
 5717:     foreach my $server (@homeservers) {
 5718:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5719:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5720: 	
 5721: 	foreach my $pair (split(/\&/,$response)) {
 5722: 	    my ($name,$value)=split(/\=/,$pair);
 5723: 	    if ($name eq 'code_order') {
 5724: 		@{$code_order} = split(/\&/,&unescape($value));
 5725: 	    } else {
 5726: 		$returnhash->{&unescape($name)}=&unescape($value);
 5727: 	    }
 5728: 	}
 5729: 	return 'ok';
 5730:     }
 5731: 
 5732:     return $response;
 5733: }
 5734: 
 5735: sub auto_possible_instcodes {
 5736:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 5737:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 5738:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 5739:         return;
 5740:     }
 5741:     my (@homeservers,$uhome);
 5742:     if (defined(&domain($domain,'primary'))) {
 5743:         $uhome=&domain($domain,'primary');
 5744:         push(@homeservers,&domain($domain,'primary'));
 5745:     } else {
 5746:         my %servers = &get_servers($domain,'library');
 5747:         foreach my $tryserver (keys(%servers)) {
 5748:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5749:                 push(@homeservers,$tryserver);
 5750:             }
 5751:         }
 5752:     }
 5753:     my $response;
 5754:     foreach my $server (@homeservers) {
 5755:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 5756:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5757:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 5758:             split(':',$response);
 5759:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 5760:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 5761:         foreach my $item (split('&',$cat_title)) {   
 5762:             my ($name,$value)=split('=',$item);
 5763:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 5764:         }
 5765:         foreach my $item (split('&',$cat_order)) {
 5766:             my ($name,$value)=split('=',$item);
 5767:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 5768:         }
 5769:         return 'ok';
 5770:     }
 5771:     return $response;
 5772: }
 5773: 
 5774: sub auto_courserequest_checks {
 5775:     my ($dom) = @_;
 5776:     my %validations;
 5777:     return %validations; 
 5778: }
 5779: 
 5780: sub auto_validate_class_sec {
 5781:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5782:     my $homeserver = &homeserver($cnum,$cdom);
 5783:     my $ownerlist;
 5784:     if (ref($owners) eq 'ARRAY') {
 5785:         $ownerlist = join(',',@{$owners});
 5786:     } else {
 5787:         $ownerlist = $owners;
 5788:     }
 5789:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 5790:                         &escape($ownerlist).':'.$cdom,$homeserver);
 5791:     return $response;
 5792: }
 5793: 
 5794: # ------------------------------------------------------- Course Group routines
 5795: 
 5796: sub get_coursegroups {
 5797:     my ($cdom,$cnum,$group,$namespace) = @_;
 5798:     return(&dump($namespace,$cdom,$cnum,$group));
 5799: }
 5800: 
 5801: sub modify_coursegroup {
 5802:     my ($cdom,$cnum,$groupsettings) = @_;
 5803:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 5804: }
 5805: 
 5806: sub toggle_coursegroup_status {
 5807:     my ($cdom,$cnum,$group,$action) = @_;
 5808:     my ($from_namespace,$to_namespace);
 5809:     if ($action eq 'delete') {
 5810:         $from_namespace = 'coursegroups';
 5811:         $to_namespace = 'deleted_groups';
 5812:     } else {
 5813:         $from_namespace = 'deleted_groups';
 5814:         $to_namespace = 'coursegroups';
 5815:     }
 5816:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 5817:     if (my $tmp = &error(%curr_group)) {
 5818:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 5819:         return ('read error',$tmp);
 5820:     } else {
 5821:         my %savedsettings = %curr_group; 
 5822:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 5823:         my $deloutcome;
 5824:         if ($result eq 'ok') {
 5825:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 5826:         } else {
 5827:             return ('write error',$result);
 5828:         }
 5829:         if ($deloutcome eq 'ok') {
 5830:             return 'ok';
 5831:         } else {
 5832:             return ('delete error',$deloutcome);
 5833:         }
 5834:     }
 5835: }
 5836: 
 5837: sub modify_group_roles {
 5838:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 5839:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 5840:     my $role = 'gr/'.&escape($userprivs);
 5841:     my ($uname,$udom) = split(/:/,$user);
 5842:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 5843:     if ($result eq 'ok') {
 5844:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 5845:     }
 5846:     return $result;
 5847: }
 5848: 
 5849: sub modify_coursegroup_membership {
 5850:     my ($cdom,$cnum,$membership) = @_;
 5851:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 5852:     return $result;
 5853: }
 5854: 
 5855: sub get_active_groups {
 5856:     my ($udom,$uname,$cdom,$cnum) = @_;
 5857:     my $now = time;
 5858:     my %groups = ();
 5859:     foreach my $key (keys(%env)) {
 5860:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 5861:             my ($start,$end) = split(/\./,$env{$key});
 5862:             if (($end!=0) && ($end<$now)) { next; }
 5863:             if (($start!=0) && ($start>$now)) { next; }
 5864:             if ($1 eq $cdom && $2 eq $cnum) {
 5865:                 $groups{$3} = $env{$key} ;
 5866:             }
 5867:         }
 5868:     }
 5869:     return %groups;
 5870: }
 5871: 
 5872: sub get_group_membership {
 5873:     my ($cdom,$cnum,$group) = @_;
 5874:     return(&dump('groupmembership',$cdom,$cnum,$group));
 5875: }
 5876: 
 5877: sub get_users_groups {
 5878:     my ($udom,$uname,$courseid) = @_;
 5879:     my @usersgroups;
 5880:     my $cachetime=1800;
 5881: 
 5882:     my $hashid="$udom:$uname:$courseid";
 5883:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 5884:     if (defined($cached)) {
 5885:         @usersgroups = split(/:/,$grouplist);
 5886:     } else {  
 5887:         $grouplist = '';
 5888:         my $courseurl = &courseid_to_courseurl($courseid);
 5889:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 5890:         my $access_end = $env{'course.'.$courseid.
 5891:                               '.default_enrollment_end_date'};
 5892:         my $now = time;
 5893:         foreach my $key (keys(%roleshash)) {
 5894:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 5895:                 my $group = $1;
 5896:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 5897:                     my $start = $2;
 5898:                     my $end = $1;
 5899:                     if ($start == -1) { next; } # deleted from group
 5900:                     if (($start!=0) && ($start>$now)) { next; }
 5901:                     if (($end!=0) && ($end<$now)) {
 5902:                         if ($access_end && $access_end < $now) {
 5903:                             if ($access_end - $end < 86400) {
 5904:                                 push(@usersgroups,$group);
 5905:                             }
 5906:                         }
 5907:                         next;
 5908:                     }
 5909:                     push(@usersgroups,$group);
 5910:                 }
 5911:             }
 5912:         }
 5913:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 5914:         $grouplist = join(':',@usersgroups);
 5915:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 5916:     }
 5917:     return @usersgroups;
 5918: }
 5919: 
 5920: sub devalidate_getgroups_cache {
 5921:     my ($udom,$uname,$cdom,$cnum)=@_;
 5922:     my $courseid = $cdom.'_'.$cnum;
 5923: 
 5924:     my $hashid="$udom:$uname:$courseid";
 5925:     &devalidate_cache_new('getgroups',$hashid);
 5926: }
 5927: 
 5928: # ------------------------------------------------------------------ Plain Text
 5929: 
 5930: sub plaintext {
 5931:     my ($short,$type,$cid,$forcedefault) = @_;
 5932:     if ($short =~ /^cr/) {
 5933: 	return (split('/',$short))[-1];
 5934:     }
 5935:     if (!defined($cid)) {
 5936:         $cid = $env{'request.course.id'};
 5937:     }
 5938:     if (defined($cid) && ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '')) {
 5939:         unless ($forcedefault) {
 5940:             my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 5941:             &Apache::lonlocal::mt_escape(\$roletext);
 5942:             return &Apache::lonlocal::mt($roletext);
 5943:         }
 5944:     }
 5945:     my %rolenames = (
 5946:                       Course    => 'std',
 5947:                       Community => 'alt1',
 5948:                     );
 5949:     if (defined($type) && 
 5950:          defined($rolenames{$type}) && 
 5951:          defined($prp{$short}{$rolenames{$type}})) {
 5952:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 5953:     } else {
 5954:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 5955:     }
 5956: }
 5957: 
 5958: # ----------------------------------------------------------------- Assign Role
 5959: 
 5960: sub assignrole {
 5961:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 5962:         $context)=@_;
 5963:     my $mrole;
 5964:     if ($role =~ /^cr\//) {
 5965:         my $cwosec=$url;
 5966:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5967: 	unless (&allowed('ccr',$cwosec)) {
 5968:            &logthis('Refused custom assignrole: '.
 5969:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5970: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 5971:            return 'refused'; 
 5972:         }
 5973:         $mrole='cr';
 5974:     } elsif ($role =~ /^gr\//) {
 5975:         my $cwogrp=$url;
 5976:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 5977:         unless (&allowed('mdg',$cwogrp)) {
 5978:             &logthis('Refused group assignrole: '.
 5979:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5980:                     $env{'user.name'}.' at '.$env{'user.domain'});
 5981:             return 'refused';
 5982:         }
 5983:         $mrole='gr';
 5984:     } else {
 5985:         my $cwosec=$url;
 5986:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5987:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 5988:             my $refused;
 5989:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 5990:                 if (!(&allowed('c'.$role,$url))) {
 5991:                     $refused = 1;
 5992:                 }
 5993:             } else {
 5994:                 $refused = 1;
 5995:             }
 5996:             if ($refused) {
 5997:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5998:                     $refused = '';
 5999:                 } else {
 6000:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 6001:                              ' '.$role.' '.$end.' '.$start.' by '.
 6002: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 6003:                     return 'refused';
 6004:                 }
 6005:             }
 6006:         }
 6007:         $mrole=$role;
 6008:     }
 6009:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 6010:                 "$udom:$uname:$url".'_'."$mrole=$role";
 6011:     if ($end) { $command.='_'.$end; }
 6012:     if ($start) {
 6013: 	if ($end) { 
 6014:            $command.='_'.$start; 
 6015:         } else {
 6016:            $command.='_0_'.$start;
 6017:         }
 6018:     }
 6019:     my $origstart = $start;
 6020:     my $origend = $end;
 6021:     my $delflag;
 6022: # actually delete
 6023:     if ($deleteflag) {
 6024: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 6025: # modify command to delete the role
 6026:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 6027:                 "$udom:$uname:$url".'_'."$mrole";
 6028: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 6029: # set start and finish to negative values for userrolelog
 6030:            $start=-1;
 6031:            $end=-1;
 6032:            $delflag = 1;
 6033:         }
 6034:     }
 6035: # send command
 6036:     my $answer=&reply($command,&homeserver($uname,$udom));
 6037: # log new user role if status is ok
 6038:     if ($answer eq 'ok') {
 6039: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 6040: # for course roles, perform group memberships changes triggered by role change.
 6041:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 6042:         unless ($role =~ /^gr/) {
 6043:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 6044:                                              $origstart,$selfenroll,$context);
 6045:         }
 6046:     }
 6047:     return $answer;
 6048: }
 6049: 
 6050: # -------------------------------------------------- Modify user authentication
 6051: # Overrides without validation
 6052: 
 6053: sub modifyuserauth {
 6054:     my ($udom,$uname,$umode,$upass)=@_;
 6055:     my $uhome=&homeserver($uname,$udom);
 6056:     unless (&allowed('mau',$udom)) { return 'refused'; }
 6057:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 6058:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 6059:              ' in domain '.$env{'request.role.domain'});  
 6060:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 6061: 		     &escape($upass),$uhome);
 6062:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 6063:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 6064:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 6065:     &log($udom,,$uname,$uhome,
 6066:         'Authentication changed by '.$env{'user.domain'}.', '.
 6067:                                      $env{'user.name'}.', '.$umode.
 6068:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 6069:     unless ($reply eq 'ok') {
 6070:         &logthis('Authentication mode error: '.$reply);
 6071: 	return 'error: '.$reply;
 6072:     }   
 6073:     return 'ok';
 6074: }
 6075: 
 6076: # --------------------------------------------------------------- Modify a user
 6077: 
 6078: sub modifyuser {
 6079:     my ($udom,    $uname, $uid,
 6080:         $umode,   $upass, $first,
 6081:         $middle,  $last,  $gene,
 6082:         $forceid, $desiredhome, $email, $inststatus)=@_;
 6083:     $udom= &LONCAPA::clean_domain($udom);
 6084:     $uname=&LONCAPA::clean_username($uname);
 6085:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 6086:              $umode.', '.$first.', '.$middle.', '.
 6087: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 6088:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 6089:                                      ' desiredhome not specified'). 
 6090:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 6091:              ' in domain '.$env{'request.role.domain'});
 6092:     my $uhome=&homeserver($uname,$udom,'true');
 6093: # ----------------------------------------------------------------- Create User
 6094:     if (($uhome eq 'no_host') && 
 6095: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 6096:         my $unhome='';
 6097:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 6098:             $unhome = $desiredhome;
 6099: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 6100: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 6101:         } else { # load balancing routine for determining $unhome
 6102:             my $loadm=10000000;
 6103: 	    my %servers = &get_servers($udom,'library');
 6104: 	    foreach my $tryserver (keys(%servers)) {
 6105: 		my $answer=reply('load',$tryserver);
 6106: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 6107: 		    $loadm=$answer;
 6108: 		    $unhome=$tryserver;
 6109: 		}
 6110: 	    }
 6111:         }
 6112:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 6113: 	    return 'error: unable to find a home server for '.$uname.
 6114:                    ' in domain '.$udom;
 6115:         }
 6116:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 6117:                          &escape($upass),$unhome);
 6118: 	unless ($reply eq 'ok') {
 6119:             return 'error: '.$reply;
 6120:         }   
 6121:         $uhome=&homeserver($uname,$udom,'true');
 6122:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 6123: 	    return 'error: unable verify users home machine.';
 6124:         }
 6125:     }   # End of creation of new user
 6126: # ---------------------------------------------------------------------- Add ID
 6127:     if ($uid) {
 6128:        $uid=~tr/A-Z/a-z/;
 6129:        my %uidhash=&idrget($udom,$uname);
 6130:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 6131:          && (!$forceid)) {
 6132: 	  unless ($uid eq $uidhash{$uname}) {
 6133: 	      return 'error: user id "'.$uid.'" does not match '.
 6134:                   'current user id "'.$uidhash{$uname}.'".';
 6135:           }
 6136:        } else {
 6137: 	  &idput($udom,($uname => $uid));
 6138:        }
 6139:     }
 6140: # -------------------------------------------------------------- Add names, etc
 6141:     my @tmp=&get('environment',
 6142: 		   ['firstname','middlename','lastname','generation','id',
 6143:                     'permanentemail','inststatus'],
 6144: 		   $udom,$uname);
 6145:     my %names;
 6146:     if ($tmp[0] =~ m/^error:.*/) { 
 6147:         %names=(); 
 6148:     } else {
 6149:         %names = @tmp;
 6150:     }
 6151: #
 6152: # Make sure to not trash student environment if instructor does not bother
 6153: # to supply name and email information
 6154: #
 6155:     if ($first)  { $names{'firstname'}  = $first; }
 6156:     if (defined($middle)) { $names{'middlename'} = $middle; }
 6157:     if ($last)   { $names{'lastname'}   = $last; }
 6158:     if (defined($gene))   { $names{'generation'} = $gene; }
 6159:     if ($email) {
 6160:        $email=~s/[^\w\@\.\-\,]//gs;
 6161:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 6162:     }
 6163:     if ($uid) { $names{'id'}  = $uid; }
 6164:     if (defined($inststatus)) {
 6165:         $names{'inststatus'} = '';
 6166:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 6167:         if (ref($usertypes) eq 'HASH') {
 6168:             my @okstatuses; 
 6169:             foreach my $item (split(/:/,$inststatus)) {
 6170:                 if (defined($usertypes->{$item})) {
 6171:                     push(@okstatuses,$item);  
 6172:                 }
 6173:             }
 6174:             if (@okstatuses) {
 6175:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 6176:             }
 6177:         }
 6178:     }
 6179:     my $reply = &put('environment', \%names, $udom,$uname);
 6180:     if ($reply ne 'ok') { return 'error: '.$reply; }
 6181:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 6182:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 6183:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 6184:                  $umode.', '.$first.', '.$middle.', '.
 6185: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
 6186:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 6187:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 6188:     } else {
 6189:         $logmsg .= ' during self creation';
 6190:     }
 6191:     &logthis($logmsg);
 6192:     return 'ok';
 6193: }
 6194: 
 6195: # -------------------------------------------------------------- Modify student
 6196: 
 6197: sub modifystudent {
 6198:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 6199:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 6200:         $selfenroll,$context,$inststatus)=@_;
 6201:     if (!$cid) {
 6202: 	unless ($cid=$env{'request.course.id'}) {
 6203: 	    return 'not_in_class';
 6204: 	}
 6205:     }
 6206: # --------------------------------------------------------------- Make the user
 6207:     my $reply=&modifyuser
 6208: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 6209:          $desiredhome,$email,$inststatus);
 6210:     unless ($reply eq 'ok') { return $reply; }
 6211:     # This will cause &modify_student_enrollment to get the uid from the
 6212:     # students environment
 6213:     $uid = undef if (!$forceid);
 6214:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 6215: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 6216:     return $reply;
 6217: }
 6218: 
 6219: sub modify_student_enrollment {
 6220:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 6221:     my ($cdom,$cnum,$chome);
 6222:     if (!$cid) {
 6223: 	unless ($cid=$env{'request.course.id'}) {
 6224: 	    return 'not_in_class';
 6225: 	}
 6226: 	$cdom=$env{'course.'.$cid.'.domain'};
 6227: 	$cnum=$env{'course.'.$cid.'.num'};
 6228:     } else {
 6229: 	($cdom,$cnum)=split(/_/,$cid);
 6230:     }
 6231:     $chome=$env{'course.'.$cid.'.home'};
 6232:     if (!$chome) {
 6233: 	$chome=&homeserver($cnum,$cdom);
 6234:     }
 6235:     if (!$chome) { return 'unknown_course'; }
 6236:     # Make sure the user exists
 6237:     my $uhome=&homeserver($uname,$udom);
 6238:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6239: 	return 'error: no such user';
 6240:     }
 6241:     # Get student data if we were not given enough information
 6242:     if (!defined($first)  || $first  eq '' || 
 6243:         !defined($last)   || $last   eq '' || 
 6244:         !defined($uid)    || $uid    eq '' || 
 6245:         !defined($middle) || $middle eq '' || 
 6246:         !defined($gene)   || $gene   eq '') {
 6247:         # They did not supply us with enough data to enroll the student, so
 6248:         # we need to pick up more information.
 6249:         my %tmp = &get('environment',
 6250:                        ['firstname','middlename','lastname', 'generation','id']
 6251:                        ,$udom,$uname);
 6252: 
 6253:         #foreach my $key (keys(%tmp)) {
 6254:         #    &logthis("key $key = ".$tmp{$key});
 6255:         #}
 6256:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 6257:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 6258:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 6259:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 6260:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 6261:     }
 6262:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 6263:     my $reply=cput('classlist',
 6264: 		   {"$uname:$udom" => 
 6265: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 6266: 		   $cdom,$cnum);
 6267:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 6268: 	return 'error: '.$reply;
 6269:     } else {
 6270: 	&devalidate_getsection_cache($udom,$uname,$cid);
 6271:     }
 6272:     # Add student role to user
 6273:     my $uurl='/'.$cid;
 6274:     $uurl=~s/\_/\//g;
 6275:     if ($usec) {
 6276: 	$uurl.='/'.$usec;
 6277:     }
 6278:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 6279: }
 6280: 
 6281: sub format_name {
 6282:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 6283:     my $name;
 6284:     if ($first ne 'lastname') {
 6285: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 6286:     } else {
 6287: 	if ($lastname=~/\S/) {
 6288: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 6289: 	    $name=~s/\s+,/,/;
 6290: 	} else {
 6291: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 6292: 	}
 6293:     }
 6294:     $name=~s/^\s+//;
 6295:     $name=~s/\s+$//;
 6296:     $name=~s/\s+/ /g;
 6297:     return $name;
 6298: }
 6299: 
 6300: # ------------------------------------------------- Write to course preferences
 6301: 
 6302: sub writecoursepref {
 6303:     my ($courseid,%prefs)=@_;
 6304:     $courseid=~s/^\///;
 6305:     $courseid=~s/\_/\//g;
 6306:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6307:     my $chome=homeserver($cnum,$cdomain);
 6308:     if (($chome eq '') || ($chome eq 'no_host')) { 
 6309: 	return 'error: no such course';
 6310:     }
 6311:     my $cstring='';
 6312:     foreach my $pref (keys(%prefs)) {
 6313: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 6314:     }
 6315:     $cstring=~s/\&$//;
 6316:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 6317: }
 6318: 
 6319: # ---------------------------------------------------------- Make/modify course
 6320: 
 6321: sub createcourse {
 6322:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 6323:         $course_owner,$crstype,$cnum)=@_;
 6324:     $url=&declutter($url);
 6325:     my $cid='';
 6326:     unless (&allowed('ccc',$udom)) {
 6327:         return 'refused';
 6328:     }
 6329: # --------------------------------------------------------------- Get Unique ID
 6330:     my $uname;
 6331:     if ($cnum =~ /^$match_courseid$/) {
 6332:         my $chome=&homeserver($cnum,$udom,'true');
 6333:         if (($chome eq '') || ($chome eq 'no_host')) {
 6334:             $uname = $cnum;
 6335:         } else {
 6336:             $uname = &generate_coursenum($udom);
 6337:         }
 6338:     } else {
 6339:         $uname = &generate_coursenum($udom);
 6340:     }
 6341:     return $uname if ($uname =~ /^error/);
 6342: # -------------------------------------------------- Check supplied server name
 6343:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 6344:     if (! &is_library($course_server)) {
 6345:         return 'error:bad server name '.$course_server;
 6346:     }
 6347: # ------------------------------------------------------------- Make the course
 6348:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 6349:                       $course_server);
 6350:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 6351:     my $uhome=&homeserver($uname,$udom,'true');
 6352:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6353: 	return 'error: no such course';
 6354:     }
 6355: # ----------------------------------------------------------------- Course made
 6356: # log existence
 6357:     my $newcourse = {
 6358:                     $udom.'_'.$uname => {
 6359:                                      description => $description,
 6360:                                      inst_code   => $inst_code,
 6361:                                      owner       => $course_owner,
 6362:                                      type        => $crstype,
 6363:                                                 },
 6364:                     };
 6365:     &courseidput($udom,$newcourse,$uhome,'notime');
 6366: # set toplevel url
 6367:     my $topurl=$url;
 6368:     unless ($nonstandard) {
 6369: # ------------------------------------------ For standard courses, make top url
 6370:         my $mapurl=&clutter($url);
 6371:         if ($mapurl eq '/res/') { $mapurl=''; }
 6372:         $env{'form.initmap'}=(<<ENDINITMAP);
 6373: <map>
 6374: <resource id="1" type="start"></resource>
 6375: <resource id="2" src="$mapurl"></resource>
 6376: <resource id="3" type="finish"></resource>
 6377: <link index="1" from="1" to="2"></link>
 6378: <link index="2" from="2" to="3"></link>
 6379: </map>
 6380: ENDINITMAP
 6381:         $topurl=&declutter(
 6382:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 6383:                           );
 6384:     }
 6385: # ----------------------------------------------------------- Write preferences
 6386:     &writecoursepref($udom.'_'.$uname,
 6387:                      ('description' => $description,
 6388:                       'url'         => $topurl));
 6389:     return '/'.$udom.'/'.$uname;
 6390: }
 6391: 
 6392: # ------------------------------------------------------------------- Create ID
 6393: sub generate_coursenum {
 6394:     my ($udom) = @_;
 6395:     my $domdesc = &domain($udom);
 6396:     return 'error: invalid domain' if ($domdesc eq '');
 6397:     my $uname=int(1+rand(9)).
 6398:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6399:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6400:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6401: # ----------------------------------------------- Make sure that does not exist
 6402:     my $uhome=&homeserver($uname,$udom,'true');
 6403:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6404:         $uname=int(1+rand(9)).
 6405:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6406:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6407:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6408:         $uhome=&homeserver($uname,$udom,'true');
 6409:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6410:             return 'error: unable to generate unique course-ID';
 6411:         }
 6412:     }
 6413:     return $uname;
 6414: }
 6415: 
 6416: sub is_course {
 6417:     my ($cdom,$cnum) = @_;
 6418:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 6419: 				undef,'.');
 6420:     if (exists($courses{$cdom.'_'.$cnum})) {
 6421:         return 1;
 6422:     }
 6423:     return 0;
 6424: }
 6425: 
 6426: # ---------------------------------------------------------- Assign Custom Role
 6427: 
 6428: sub assigncustomrole {
 6429:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 6430:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 6431:                        $end,$start,$deleteflag,$selfenroll,$context);
 6432: }
 6433: 
 6434: # ----------------------------------------------------------------- Revoke Role
 6435: 
 6436: sub revokerole {
 6437:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 6438:     my $now=time;
 6439:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 6440: }
 6441: 
 6442: # ---------------------------------------------------------- Revoke Custom Role
 6443: 
 6444: sub revokecustomrole {
 6445:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 6446:     my $now=time;
 6447:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 6448:            $deleteflag,$selfenroll,$context);
 6449: }
 6450: 
 6451: # ------------------------------------------------------------ Disk usage
 6452: sub diskusage {
 6453:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 6454:     $directorypath =~ s/\/$//;
 6455:     my $listing=&reply('du2:'.&escape($directorypath).':'
 6456:                        .&escape($getpropath).':'.&escape($uname).':'
 6457:                        .&escape($udom),homeserver($uname,$udom));
 6458:     if ($listing eq 'unknown_cmd') {
 6459:         if ($getpropath) {
 6460:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 6461:         }
 6462:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 6463:     }
 6464:     return $listing;
 6465: }
 6466: 
 6467: sub is_locked {
 6468:     my ($file_name, $domain, $user) = @_;
 6469:     my @check;
 6470:     my $is_locked;
 6471:     push @check, $file_name;
 6472:     my %locked = &get('file_permissions',\@check,
 6473: 		      $env{'user.domain'},$env{'user.name'});
 6474:     my ($tmp)=keys(%locked);
 6475:     if ($tmp=~/^error:/) { undef(%locked); }
 6476:     
 6477:     if (ref($locked{$file_name}) eq 'ARRAY') {
 6478:         $is_locked = 'false';
 6479:         foreach my $entry (@{$locked{$file_name}}) {
 6480:            if (ref($entry) eq 'ARRAY') { 
 6481:                $is_locked = 'true';
 6482:                last;
 6483:            }
 6484:        }
 6485:     } else {
 6486:         $is_locked = 'false';
 6487:     }
 6488: }
 6489: 
 6490: sub declutter_portfile {
 6491:     my ($file) = @_;
 6492:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 6493:     return $file;
 6494: }
 6495: 
 6496: # ------------------------------------------------------------- Mark as Read Only
 6497: 
 6498: sub mark_as_readonly {
 6499:     my ($domain,$user,$files,$what) = @_;
 6500:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6501:     my ($tmp)=keys(%current_permissions);
 6502:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6503:     foreach my $file (@{$files}) {
 6504: 	$file = &declutter_portfile($file);
 6505:         push(@{$current_permissions{$file}},$what);
 6506:     }
 6507:     &put('file_permissions',\%current_permissions,$domain,$user);
 6508:     return;
 6509: }
 6510: 
 6511: # ------------------------------------------------------------Save Selected Files
 6512: 
 6513: sub save_selected_files {
 6514:     my ($user, $path, @files) = @_;
 6515:     my $filename = $user."savedfiles";
 6516:     my @other_files = &files_not_in_path($user, $path);
 6517:     open (OUT, '>'.$tmpdir.$filename);
 6518:     foreach my $file (@files) {
 6519:         print (OUT $env{'form.currentpath'}.$file."\n");
 6520:     }
 6521:     foreach my $file (@other_files) {
 6522:         print (OUT $file."\n");
 6523:     }
 6524:     close (OUT);
 6525:     return 'ok';
 6526: }
 6527: 
 6528: sub clear_selected_files {
 6529:     my ($user) = @_;
 6530:     my $filename = $user."savedfiles";
 6531:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6532:     print (OUT undef);
 6533:     close (OUT);
 6534:     return ("ok");    
 6535: }
 6536: 
 6537: sub files_in_path {
 6538:     my ($user, $path) = @_;
 6539:     my $filename = $user."savedfiles";
 6540:     my %return_files;
 6541:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6542:     while (my $line_in = <IN>) {
 6543:         chomp ($line_in);
 6544:         my @paths_and_file = split (m!/!, $line_in);
 6545:         my $file_part = pop (@paths_and_file);
 6546:         my $path_part = join ('/', @paths_and_file);
 6547:         $path_part.='/';
 6548:         my $path_and_file = $path_part.$file_part;
 6549:         if ($path_part eq $path) {
 6550:             $return_files{$file_part}= 'selected';
 6551:         }
 6552:     }
 6553:     close (IN);
 6554:     return (\%return_files);
 6555: }
 6556: 
 6557: # called in portfolio select mode, to show files selected NOT in current directory
 6558: sub files_not_in_path {
 6559:     my ($user, $path) = @_;
 6560:     my $filename = $user."savedfiles";
 6561:     my @return_files;
 6562:     my $path_part;
 6563:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6564:     while (my $line = <IN>) {
 6565:         #ok, I know it's clunky, but I want it to work
 6566:         my @paths_and_file = split(m|/|, $line);
 6567:         my $file_part = pop(@paths_and_file);
 6568:         chomp($file_part);
 6569:         my $path_part = join('/', @paths_and_file);
 6570:         $path_part .= '/';
 6571:         my $path_and_file = $path_part.$file_part;
 6572:         if ($path_part ne $path) {
 6573:             push(@return_files, ($path_and_file));
 6574:         }
 6575:     }
 6576:     close(OUT);
 6577:     return (@return_files);
 6578: }
 6579: 
 6580: #----------------------------------------------Get portfolio file permissions
 6581: 
 6582: sub get_portfile_permissions {
 6583:     my ($domain,$user) = @_;
 6584:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6585:     my ($tmp)=keys(%current_permissions);
 6586:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6587:     return \%current_permissions;
 6588: }
 6589: 
 6590: #---------------------------------------------Get portfolio file access controls
 6591: 
 6592: sub get_access_controls {
 6593:     my ($current_permissions,$group,$file) = @_;
 6594:     my %access;
 6595:     my $real_file = $file;
 6596:     $file =~ s/\.meta$//;
 6597:     if (defined($file)) {
 6598:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 6599:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 6600:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 6601:             }
 6602:         }
 6603:     } else {
 6604:         foreach my $key (keys(%{$current_permissions})) {
 6605:             if ($key =~ /\0accesscontrol$/) {
 6606:                 if (defined($group)) {
 6607:                     if ($key !~ m-^\Q$group\E/-) {
 6608:                         next;
 6609:                     }
 6610:                 }
 6611:                 my ($fullpath) = split(/\0/,$key);
 6612:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 6613:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 6614:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 6615:                     }
 6616:                 }
 6617:             }
 6618:         }
 6619:     }
 6620:     return %access;
 6621: }
 6622: 
 6623: sub modify_access_controls {
 6624:     my ($file_name,$changes,$domain,$user)=@_;
 6625:     my ($outcome,$deloutcome);
 6626:     my %store_permissions;
 6627:     my %new_values;
 6628:     my %new_control;
 6629:     my %translation;
 6630:     my @deletions = ();
 6631:     my $now = time;
 6632:     if (exists($$changes{'activate'})) {
 6633:         if (ref($$changes{'activate'}) eq 'HASH') {
 6634:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 6635:             my $numnew = scalar(@newitems);
 6636:             for (my $i=0; $i<$numnew; $i++) {
 6637:                 my $newkey = $newitems[$i];
 6638:                 my $newid = &Apache::loncommon::get_cgi_id();
 6639:                 if ($newkey =~ /^\d+:/) { 
 6640:                     $newkey =~ s/^(\d+)/$newid/;
 6641:                     $translation{$1} = $newid;
 6642:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 6643:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 6644:                     $translation{$1} = $newid;
 6645:                 }
 6646:                 $new_values{$file_name."\0".$newkey} = 
 6647:                                           $$changes{'activate'}{$newitems[$i]};
 6648:                 $new_control{$newkey} = $now;
 6649:             }
 6650:         }
 6651:     }
 6652:     my %todelete;
 6653:     my %changed_items;
 6654:     foreach my $action ('delete','update') {
 6655:         if (exists($$changes{$action})) {
 6656:             if (ref($$changes{$action}) eq 'HASH') {
 6657:                 foreach my $key (keys(%{$$changes{$action}})) {
 6658:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 6659:                     if ($action eq 'delete') { 
 6660:                         $todelete{$itemnum} = 1;
 6661:                     } else {
 6662:                         $changed_items{$itemnum} = $key;
 6663:                     }
 6664:                 }
 6665:             }
 6666:         }
 6667:     }
 6668:     # get lock on access controls for file.
 6669:     my $lockhash = {
 6670:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 6671:                                                        ':'.$env{'user.domain'},
 6672:                    }; 
 6673:     my $tries = 0;
 6674:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6675:    
 6676:     while (($gotlock ne 'ok') && $tries <3) {
 6677:         $tries ++;
 6678:         sleep 1;
 6679:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6680:     }
 6681:     if ($gotlock eq 'ok') {
 6682:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 6683:         my ($tmp)=keys(%curr_permissions);
 6684:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 6685:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 6686:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 6687:             if (ref($curr_controls) eq 'HASH') {
 6688:                 foreach my $control_item (keys(%{$curr_controls})) {
 6689:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 6690:                     if (defined($todelete{$itemnum})) {
 6691:                         push(@deletions,$file_name."\0".$control_item);
 6692:                     } else {
 6693:                         if (defined($changed_items{$itemnum})) {
 6694:                             $new_control{$changed_items{$itemnum}} = $now;
 6695:                             push(@deletions,$file_name."\0".$control_item);
 6696:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 6697:                         } else {
 6698:                             $new_control{$control_item} = $$curr_controls{$control_item};
 6699:                         }
 6700:                     }
 6701:                 }
 6702:             }
 6703:         }
 6704:         my ($group);
 6705:         if (&is_course($domain,$user)) {
 6706:             ($group,my $file) = split(/\//,$file_name,2);
 6707:         }
 6708:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 6709:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 6710:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 6711:         #  remove lock
 6712:         my @del_lock = ($file_name."\0".'locked_access_records');
 6713:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 6714:         my $sqlresult =
 6715:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 6716:                                     $group);
 6717:     } else {
 6718:         $outcome = "error: could not obtain lockfile\n";  
 6719:     }
 6720:     return ($outcome,$deloutcome,\%new_values,\%translation);
 6721: }
 6722: 
 6723: sub make_public_indefinitely {
 6724:     my ($requrl) = @_;
 6725:     my $now = time;
 6726:     my $action = 'activate';
 6727:     my $aclnum = 0;
 6728:     if (&is_portfolio_url($requrl)) {
 6729:         my (undef,$udom,$unum,$file_name,$group) =
 6730:             &parse_portfolio_url($requrl);
 6731:         my $current_perms = &get_portfile_permissions($udom,$unum);
 6732:         my %access_controls = &get_access_controls($current_perms,
 6733:                                                    $group,$file_name);
 6734:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 6735:             my ($num,$scope,$end,$start) = 
 6736:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6737:             if ($scope eq 'public') {
 6738:                 if ($start <= $now && $end == 0) {
 6739:                     $action = 'none';
 6740:                 } else {
 6741:                     $action = 'update';
 6742:                     $aclnum = $num;
 6743:                 }
 6744:                 last;
 6745:             }
 6746:         }
 6747:         if ($action eq 'none') {
 6748:              return 'ok';
 6749:         } else {
 6750:             my %changes;
 6751:             my $newend = 0;
 6752:             my $newstart = $now;
 6753:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 6754:             $changes{$action}{$newkey} = {
 6755:                 type => 'public',
 6756:                 time => {
 6757:                     start => $newstart,
 6758:                     end   => $newend,
 6759:                 },
 6760:             };
 6761:             my ($outcome,$deloutcome,$new_values,$translation) =
 6762:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 6763:             return $outcome;
 6764:         }
 6765:     } else {
 6766:         return 'invalid';
 6767:     }
 6768: }
 6769: 
 6770: #------------------------------------------------------Get Marked as Read Only
 6771: 
 6772: sub get_marked_as_readonly {
 6773:     my ($domain,$user,$what,$group) = @_;
 6774:     my $current_permissions = &get_portfile_permissions($domain,$user);
 6775:     my @readonly_files;
 6776:     my $cmp1=$what;
 6777:     if (ref($what)) { $cmp1=join('',@{$what}) };
 6778:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6779:         if (defined($group)) {
 6780:             if ($file_name !~ m-^\Q$group\E/-) {
 6781:                 next;
 6782:             }
 6783:         }
 6784:         if (ref($value) eq "ARRAY"){
 6785:             foreach my $stored_what (@{$value}) {
 6786:                 my $cmp2=$stored_what;
 6787:                 if (ref($stored_what) eq 'ARRAY') {
 6788:                     $cmp2=join('',@{$stored_what});
 6789:                 }
 6790:                 if ($cmp1 eq $cmp2) {
 6791:                     push(@readonly_files, $file_name);
 6792:                     last;
 6793:                 } elsif (!defined($what)) {
 6794:                     push(@readonly_files, $file_name);
 6795:                     last;
 6796:                 }
 6797:             }
 6798:         }
 6799:     }
 6800:     return @readonly_files;
 6801: }
 6802: #-----------------------------------------------------------Get Marked as Read Only Hash
 6803: 
 6804: sub get_marked_as_readonly_hash {
 6805:     my ($current_permissions,$group,$what) = @_;
 6806:     my %readonly_files;
 6807:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6808:         if (defined($group)) {
 6809:             if ($file_name !~ m-^\Q$group\E/-) {
 6810:                 next;
 6811:             }
 6812:         }
 6813:         if (ref($value) eq "ARRAY"){
 6814:             foreach my $stored_what (@{$value}) {
 6815:                 if (ref($stored_what) eq 'ARRAY') {
 6816:                     foreach my $lock_descriptor(@{$stored_what}) {
 6817:                         if ($lock_descriptor eq 'graded') {
 6818:                             $readonly_files{$file_name} = 'graded';
 6819:                         } elsif ($lock_descriptor eq 'handback') {
 6820:                             $readonly_files{$file_name} = 'handback';
 6821:                         } else {
 6822:                             if (!exists($readonly_files{$file_name})) {
 6823:                                 $readonly_files{$file_name} = 'locked';
 6824:                             }
 6825:                         }
 6826:                     }
 6827:                 } 
 6828:             }
 6829:         } 
 6830:     }
 6831:     return %readonly_files;
 6832: }
 6833: # ------------------------------------------------------------ Unmark as Read Only
 6834: 
 6835: sub unmark_as_readonly {
 6836:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 6837:     # for portfolio submissions, $what contains [$symb,$crsid] 
 6838:     my ($domain,$user,$what,$file_name,$group) = @_;
 6839:     $file_name = &declutter_portfile($file_name);
 6840:     my $symb_crs = $what;
 6841:     if (ref($what)) { $symb_crs=join('',@$what); }
 6842:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 6843:     my ($tmp)=keys(%current_permissions);
 6844:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6845:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 6846:     foreach my $file (@readonly_files) {
 6847: 	my $clean_file = &declutter_portfile($file);
 6848: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 6849: 	my $current_locks = $current_permissions{$file};
 6850:         my @new_locks;
 6851:         my @del_keys;
 6852:         if (ref($current_locks) eq "ARRAY"){
 6853:             foreach my $locker (@{$current_locks}) {
 6854:                 my $compare=$locker;
 6855:                 if (ref($locker) eq 'ARRAY') {
 6856:                     $compare=join('',@{$locker});
 6857:                     if ($compare ne $symb_crs) {
 6858:                         push(@new_locks, $locker);
 6859:                     }
 6860:                 }
 6861:             }
 6862:             if (scalar(@new_locks) > 0) {
 6863:                 $current_permissions{$file} = \@new_locks;
 6864:             } else {
 6865:                 push(@del_keys, $file);
 6866:                 &del('file_permissions',\@del_keys, $domain, $user);
 6867:                 delete($current_permissions{$file});
 6868:             }
 6869:         }
 6870:     }
 6871:     &put('file_permissions',\%current_permissions,$domain,$user);
 6872:     return;
 6873: }
 6874: 
 6875: # ------------------------------------------------------------ Directory lister
 6876: 
 6877: sub dirlist {
 6878:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 6879:     $uri=~s/^\///;
 6880:     $uri=~s/\/$//;
 6881:     my ($udom, $uname);
 6882:     if ($getuserdir) {
 6883:         $udom = $userdomain;
 6884:         $uname = $username;
 6885:     } else {
 6886:         (undef,$udom,$uname)=split(/\//,$uri);
 6887:         if(defined($userdomain)) {
 6888:             $udom = $userdomain;
 6889:         }
 6890:         if(defined($username)) {
 6891:             $uname = $username;
 6892:         }
 6893:     }
 6894:     my ($dirRoot,$listing,@listing_results);
 6895: 
 6896:     $dirRoot = $perlvar{'lonDocRoot'};
 6897:     if (defined($getpropath)) {
 6898:         $dirRoot = &propath($udom,$uname);
 6899:         $dirRoot =~ s/\/$//;
 6900:     } elsif (defined($getuserdir)) {
 6901:         my $subdir=$uname.'__';
 6902:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 6903:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 6904:                    ."/$udom/$subdir/$uname";
 6905:     } elsif (defined($alternateRoot)) {
 6906:         $dirRoot = $alternateRoot;
 6907:     }
 6908: 
 6909:     if($udom) {
 6910:         if($uname) {
 6911:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 6912:                               .$getuserdir.':'.&escape($dirRoot)
 6913:                               .':'.&escape($uname).':'.&escape($udom),
 6914:                               &homeserver($uname,$udom));
 6915:             if ($listing eq 'unknown_cmd') {
 6916:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 6917:                                   &homeserver($uname,$udom));
 6918:             } else {
 6919:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6920:             }
 6921:             if ($listing eq 'unknown_cmd') {
 6922:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 6923: 				  &homeserver($uname,$udom));
 6924:                 @listing_results = split(/:/,$listing);
 6925:             } else {
 6926:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6927:             }
 6928:             return @listing_results;
 6929:         } elsif(!$alternateRoot) {
 6930:             my %allusers;
 6931: 	    my %servers = &get_servers($udom,'library');
 6932:  	    foreach my $tryserver (keys(%servers)) {
 6933:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 6934:                                   &escape($udom),$tryserver);
 6935:                 if ($listing eq 'unknown_cmd') {
 6936: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 6937: 				      $udom, $tryserver);
 6938:                 } else {
 6939:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 6940:                 }
 6941: 		if ($listing eq 'unknown_cmd') {
 6942: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 6943: 				      $udom, $tryserver);
 6944: 		    @listing_results = split(/:/,$listing);
 6945: 		} else {
 6946: 		    @listing_results =
 6947: 			map { &unescape($_); } split(/:/,$listing);
 6948: 		}
 6949: 		if ($listing_results[0] ne 'no_such_dir' && 
 6950: 		    $listing_results[0] ne 'empty'       &&
 6951: 		    $listing_results[0] ne 'con_lost') {
 6952: 		    foreach my $line (@listing_results) {
 6953: 			my ($entry) = split(/&/,$line,2);
 6954: 			$allusers{$entry} = 1;
 6955: 		    }
 6956: 		}
 6957:             }
 6958:             my $alluserstr='';
 6959:             foreach my $user (sort(keys(%allusers))) {
 6960:                 $alluserstr.=$user.'&user:';
 6961:             }
 6962:             $alluserstr=~s/:$//;
 6963:             return split(/:/,$alluserstr);
 6964:         } else {
 6965:             return ('missing user name');
 6966:         }
 6967:     } elsif(!defined($getpropath)) {
 6968:         my @all_domains = sort(&all_domains());
 6969:         foreach my $domain (@all_domains) {
 6970:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 6971:         }
 6972:         return @all_domains;
 6973:     } else {
 6974:         return ('missing domain');
 6975:     }
 6976: }
 6977: 
 6978: # --------------------------------------------- GetFileTimestamp
 6979: # This function utilizes dirlist and returns the date stamp for
 6980: # when it was last modified.  It will also return an error of -1
 6981: # if an error occurs
 6982: 
 6983: sub GetFileTimestamp {
 6984:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 6985:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 6986:     $studentName   = &LONCAPA::clean_username($studentName);
 6987:     my ($fileStat) = 
 6988:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
 6989:                                  undef,$getuserdir);
 6990:     my @stats = split('&', $fileStat);
 6991:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6992:         # @stats contains first the filename, then the stat output
 6993:         return $stats[10]; # so this is 10 instead of 9.
 6994:     } else {
 6995:         return -1;
 6996:     }
 6997: }
 6998: 
 6999: sub stat_file {
 7000:     my ($uri) = @_;
 7001:     $uri = &clutter_with_no_wrapper($uri);
 7002: 
 7003:     my ($udom,$uname,$file);
 7004:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 7005: 	($udom,$uname,$file) =
 7006: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 7007: 	$file = 'userfiles/'.$file;
 7008:     }
 7009:     if ($uri =~ m-^/res/-) {
 7010: 	($udom,$uname) = 
 7011: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 7012: 	$file = $uri;
 7013:     }
 7014: 
 7015:     if (!$udom || !$uname || !$file) {
 7016: 	# unable to handle the uri
 7017: 	return ();
 7018:     }
 7019:     my $getpropath;
 7020:     if ($file =~ /^userfiles\//) {
 7021:         $getpropath = 1;
 7022:     }
 7023:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
 7024:     my @stats = split('&', $result);
 7025:     
 7026:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 7027: 	shift(@stats); #filename is first
 7028: 	return @stats;
 7029:     }
 7030:     return ();
 7031: }
 7032: 
 7033: # -------------------------------------------------------- Value of a Condition
 7034: 
 7035: # gets the value of a specific preevaluated condition
 7036: #    stored in the string  $env{user.state.<cid>}
 7037: # or looks up a condition reference in the bighash and if if hasn't
 7038: # already been evaluated recurses into docondval to get the value of
 7039: # the condition, then memoizing it to 
 7040: #   $env{user.state.<cid>.<condition>}
 7041: sub directcondval {
 7042:     my $number=shift;
 7043:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 7044: 	&Apache::lonuserstate::evalstate();
 7045:     }
 7046:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 7047: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 7048:     } elsif ($number =~ /^_/) {
 7049: 	my $sub_condition;
 7050: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7051: 		&GDBM_READER(),0640)) {
 7052: 	    $sub_condition=$bighash{'conditions'.$number};
 7053: 	    untie(%bighash);
 7054: 	}
 7055: 	my $value = &docondval($sub_condition);
 7056: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 7057: 	return $value;
 7058:     }
 7059:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 7060:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 7061:     } else {
 7062:        return 2;
 7063:     }
 7064: }
 7065: 
 7066: # get the collection of conditions for this resource
 7067: sub condval {
 7068:     my $condidx=shift;
 7069:     my $allpathcond='';
 7070:     foreach my $cond (split(/\|/,$condidx)) {
 7071: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 7072: 	    $allpathcond.=
 7073: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 7074: 	}
 7075:     }
 7076:     $allpathcond=~s/\|$//;
 7077:     return &docondval($allpathcond);
 7078: }
 7079: 
 7080: #evaluates an expression of conditions
 7081: sub docondval {
 7082:     my ($allpathcond) = @_;
 7083:     my $result=0;
 7084:     if ($env{'request.course.id'}
 7085: 	&& defined($allpathcond)) {
 7086: 	my $operand='|';
 7087: 	my @stack;
 7088: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 7089: 	    if ($chunk eq '(') {
 7090: 		push @stack,($operand,$result);
 7091: 	    } elsif ($chunk eq ')') {
 7092: 		my $before=pop @stack;
 7093: 		if (pop @stack eq '&') {
 7094: 		    $result=$result>$before?$before:$result;
 7095: 		} else {
 7096: 		    $result=$result>$before?$result:$before;
 7097: 		}
 7098: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 7099: 		$operand=$chunk;
 7100: 	    } else {
 7101: 		my $new=directcondval($chunk);
 7102: 		if ($operand eq '&') {
 7103: 		    $result=$result>$new?$new:$result;
 7104: 		} else {
 7105: 		    $result=$result>$new?$result:$new;
 7106: 		}
 7107: 	    }
 7108: 	}
 7109:     }
 7110:     return $result;
 7111: }
 7112: 
 7113: # ---------------------------------------------------- Devalidate courseresdata
 7114: 
 7115: sub devalidatecourseresdata {
 7116:     my ($coursenum,$coursedomain)=@_;
 7117:     my $hashid=$coursenum.':'.$coursedomain;
 7118:     &devalidate_cache_new('courseres',$hashid);
 7119: }
 7120: 
 7121: 
 7122: # --------------------------------------------------- Course Resourcedata Query
 7123: #
 7124: #  Parameters:
 7125: #      $coursenum    - Number of the course.
 7126: #      $coursedomain - Domain at which the course was created.
 7127: #  Returns:
 7128: #     A hash of the course parameters along (I think) with timestamps
 7129: #     and version info.
 7130: 
 7131: sub get_courseresdata {
 7132:     my ($coursenum,$coursedomain)=@_;
 7133:     my $coursehom=&homeserver($coursenum,$coursedomain);
 7134:     my $hashid=$coursenum.':'.$coursedomain;
 7135:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 7136:     my %dumpreply;
 7137:     unless (defined($cached)) {
 7138: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 7139: 	$result=\%dumpreply;
 7140: 	my ($tmp) = keys(%dumpreply);
 7141: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 7142: 	    &do_cache_new('courseres',$hashid,$result,600);
 7143: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 7144: 	    return $tmp;
 7145: 	} elsif ($tmp =~ /^(error)/) {
 7146: 	    $result=undef;
 7147: 	    &do_cache_new('courseres',$hashid,$result,600);
 7148: 	}
 7149:     }
 7150:     return $result;
 7151: }
 7152: 
 7153: sub devalidateuserresdata {
 7154:     my ($uname,$udom)=@_;
 7155:     my $hashid="$udom:$uname";
 7156:     &devalidate_cache_new('userres',$hashid);
 7157: }
 7158: 
 7159: sub get_userresdata {
 7160:     my ($uname,$udom)=@_;
 7161:     #most student don\'t have any data set, check if there is some data
 7162:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 7163: 
 7164:     my $hashid="$udom:$uname";
 7165:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 7166:     if (!defined($cached)) {
 7167: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 7168: 	$result=\%resourcedata;
 7169: 	&do_cache_new('userres',$hashid,$result,600);
 7170:     }
 7171:     my ($tmp)=keys(%$result);
 7172:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 7173: 	return $result;
 7174:     }
 7175:     #error 2 occurs when the .db doesn't exist
 7176:     if ($tmp!~/error: 2 /) {
 7177: 	&logthis("<font color=\"blue\">WARNING:".
 7178: 		 " Trying to get resource data for ".
 7179: 		 $uname." at ".$udom.": ".
 7180: 		 $tmp."</font>");
 7181:     } elsif ($tmp=~/error: 2 /) {
 7182: 	#&EXT_cache_set($udom,$uname);
 7183: 	&do_cache_new('userres',$hashid,undef,600);
 7184: 	undef($tmp); # not really an error so don't send it back
 7185:     }
 7186:     return $tmp;
 7187: }
 7188: #----------------------------------------------- resdata - return resource data
 7189: #  Purpose:
 7190: #    Return resource data for either users or for a course.
 7191: #  Parameters:
 7192: #     $name      - Course/user name.
 7193: #     $domain    - Name of the domain the user/course is registered on.
 7194: #     $type      - Type of thing $name is (must be 'course' or 'user'
 7195: #     @which     - Array of names of resources desired.
 7196: #  Returns:
 7197: #     The value of the first reasource in @which that is found in the
 7198: #     resource hash.
 7199: #  Exceptional Conditions:
 7200: #     If the $type passed in is not valid (not the string 'course' or 
 7201: #     'user', an undefined  reference is returned.
 7202: #     If none of the resources are found, an undef is returned
 7203: sub resdata {
 7204:     my ($name,$domain,$type,@which)=@_;
 7205:     my $result;
 7206:     if ($type eq 'course') {
 7207: 	$result=&get_courseresdata($name,$domain);
 7208:     } elsif ($type eq 'user') {
 7209: 	$result=&get_userresdata($name,$domain);
 7210:     }
 7211:     if (!ref($result)) { return $result; }    
 7212:     foreach my $item (@which) {
 7213: 	if (defined($result->{$item->[0]})) {
 7214: 	    return [$result->{$item->[0]},$item->[1]];
 7215: 	}
 7216:     }
 7217:     return undef;
 7218: }
 7219: 
 7220: #
 7221: # EXT resource caching routines
 7222: #
 7223: 
 7224: sub clear_EXT_cache_status {
 7225:     &delenv('cache.EXT.');
 7226: }
 7227: 
 7228: sub EXT_cache_status {
 7229:     my ($target_domain,$target_user) = @_;
 7230:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7231:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 7232:         # We know already the user has no data
 7233:         return 1;
 7234:     } else {
 7235:         return 0;
 7236:     }
 7237: }
 7238: 
 7239: sub EXT_cache_set {
 7240:     my ($target_domain,$target_user) = @_;
 7241:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7242:     #&appenv({$cachename => time});
 7243: }
 7244: 
 7245: # --------------------------------------------------------- Value of a Variable
 7246: sub EXT {
 7247: 
 7248:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 7249:     unless ($varname) { return ''; }
 7250:     #get real user name/domain, courseid and symb
 7251:     my $courseid;
 7252:     my $publicuser;
 7253:     if ($symbparm) {
 7254: 	$symbparm=&get_symb_from_alias($symbparm);
 7255:     }
 7256:     if (!($uname && $udom)) {
 7257:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 7258:       if (!$symbparm) {	$symbparm=$cursymb; }
 7259:     } else {
 7260: 	$courseid=$env{'request.course.id'};
 7261:     }
 7262:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 7263:     my $rest;
 7264:     if (defined($therest[0])) {
 7265:        $rest=join('.',@therest);
 7266:     } else {
 7267:        $rest='';
 7268:     }
 7269: 
 7270:     my $qualifierrest=$qualifier;
 7271:     if ($rest) { $qualifierrest.='.'.$rest; }
 7272:     my $spacequalifierrest=$space;
 7273:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 7274:     if ($realm eq 'user') {
 7275: # --------------------------------------------------------------- user.resource
 7276: 	if ($space eq 'resource') {
 7277: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 7278: 		  || defined($Apache::lonhomework::parsing_a_task))
 7279: 		 &&
 7280: 		 ($symbparm eq &symbread()) ) {	
 7281: 		# if we are in the middle of processing the resource the
 7282: 		# get the value we are planning on committing
 7283:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 7284:                     return $Apache::lonhomework::results{$qualifierrest};
 7285:                 } else {
 7286:                     return $Apache::lonhomework::history{$qualifierrest};
 7287:                 }
 7288: 	    } else {
 7289: 		my %restored;
 7290: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 7291: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 7292: 		} else {
 7293: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 7294: 		}
 7295: 		return $restored{$qualifierrest};
 7296: 	    }
 7297: # ----------------------------------------------------------------- user.access
 7298:         } elsif ($space eq 'access') {
 7299: 	    # FIXME - not supporting calls for a specific user
 7300:             return &allowed($qualifier,$rest);
 7301: # ------------------------------------------ user.preferences, user.environment
 7302:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 7303: 	    if (($uname eq $env{'user.name'}) &&
 7304: 		($udom eq $env{'user.domain'})) {
 7305: 		return $env{join('.',('environment',$qualifierrest))};
 7306: 	    } else {
 7307: 		my %returnhash;
 7308: 		if (!$publicuser) {
 7309: 		    %returnhash=&userenvironment($udom,$uname,
 7310: 						 $qualifierrest);
 7311: 		}
 7312: 		return $returnhash{$qualifierrest};
 7313: 	    }
 7314: # ----------------------------------------------------------------- user.course
 7315:         } elsif ($space eq 'course') {
 7316: 	    # FIXME - not supporting calls for a specific user
 7317:             return $env{join('.',('request.course',$qualifier))};
 7318: # ------------------------------------------------------------------- user.role
 7319:         } elsif ($space eq 'role') {
 7320: 	    # FIXME - not supporting calls for a specific user
 7321:             my ($role,$where)=split(/\./,$env{'request.role'});
 7322:             if ($qualifier eq 'value') {
 7323: 		return $role;
 7324:             } elsif ($qualifier eq 'extent') {
 7325:                 return $where;
 7326:             }
 7327: # ----------------------------------------------------------------- user.domain
 7328:         } elsif ($space eq 'domain') {
 7329:             return $udom;
 7330: # ------------------------------------------------------------------- user.name
 7331:         } elsif ($space eq 'name') {
 7332:             return $uname;
 7333: # ---------------------------------------------------- Any other user namespace
 7334:         } else {
 7335: 	    my %reply;
 7336: 	    if (!$publicuser) {
 7337: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 7338: 	    }
 7339: 	    return $reply{$qualifierrest};
 7340:         }
 7341:     } elsif ($realm eq 'query') {
 7342: # ---------------------------------------------- pull stuff out of query string
 7343:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 7344: 						[$spacequalifierrest]);
 7345: 	return $env{'form.'.$spacequalifierrest}; 
 7346:    } elsif ($realm eq 'request') {
 7347: # ------------------------------------------------------------- request.browser
 7348:         if ($space eq 'browser') {
 7349: 	    if ($qualifier eq 'textremote') {
 7350: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 7351: 		    return 1;
 7352: 		} else {
 7353: 		    return 0;
 7354: 		}
 7355: 	    } else {
 7356: 		return $env{'browser.'.$qualifier};
 7357: 	    }
 7358: # ------------------------------------------------------------ request.filename
 7359:         } else {
 7360:             return $env{'request.'.$spacequalifierrest};
 7361:         }
 7362:     } elsif ($realm eq 'course') {
 7363: # ---------------------------------------------------------- course.description
 7364:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 7365:     } elsif ($realm eq 'resource') {
 7366: 
 7367: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 7368: 	    if (!$symbparm) { $symbparm=&symbread(); }
 7369: 	}
 7370: 
 7371: 	if ($space eq 'title') {
 7372: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 7373: 	    return &gettitle($symbparm);
 7374: 	}
 7375: 	
 7376: 	if ($space eq 'map') {
 7377: 	    my ($map) = &decode_symb($symbparm);
 7378: 	    return &symbread($map);
 7379: 	}
 7380: 	if ($space eq 'filename') {
 7381: 	    if ($symbparm) {
 7382: 		return &clutter((&decode_symb($symbparm))[2]);
 7383: 	    }
 7384: 	    return &hreflocation('',$env{'request.filename'});
 7385: 	}
 7386: 
 7387: 	my ($section, $group, @groups);
 7388: 	my ($courselevelm,$courselevel);
 7389: 	if ($symbparm && defined($courseid) && 
 7390: 	    $courseid eq $env{'request.course.id'}) {
 7391: 
 7392: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 7393: 
 7394: # ----------------------------------------------------- Cascading lookup scheme
 7395: 	    my $symbp=$symbparm;
 7396: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 7397: 
 7398: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 7399: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 7400: 
 7401: 	    if (($env{'user.name'} eq $uname) &&
 7402: 		($env{'user.domain'} eq $udom)) {
 7403: 		$section=$env{'request.course.sec'};
 7404:                 @groups = split(/:/,$env{'request.course.groups'});  
 7405:                 @groups=&sort_course_groups($courseid,@groups); 
 7406: 	    } else {
 7407: 		if (! defined($usection)) {
 7408: 		    $section=&getsection($udom,$uname,$courseid);
 7409: 		} else {
 7410: 		    $section = $usection;
 7411: 		}
 7412:                 @groups = &get_users_groups($udom,$uname,$courseid);
 7413: 	    }
 7414: 
 7415: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 7416: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 7417: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 7418: 
 7419: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 7420: 	    my $courselevelr=$courseid.'.'.$symbparm;
 7421: 	    $courselevelm=$courseid.'.'.$mapparm;
 7422: 
 7423: # ----------------------------------------------------------- first, check user
 7424: 
 7425: 	    my $userreply=&resdata($uname,$udom,'user',
 7426: 				       ([$courselevelr,'resource'],
 7427: 					[$courselevelm,'map'     ],
 7428: 					[$courselevel, 'course'  ]));
 7429: 	    if (defined($userreply)) { return &get_reply($userreply); }
 7430: 
 7431: # ------------------------------------------------ second, check some of course
 7432:             my $coursereply;
 7433:             if (@groups > 0) {
 7434:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 7435:                                        $mapparm,$spacequalifierrest);
 7436:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 7437:             }
 7438: 
 7439: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7440: 				  $env{'course.'.$courseid.'.domain'},
 7441: 				  'course',
 7442: 				  ([$seclevelr,   'resource'],
 7443: 				   [$seclevelm,   'map'     ],
 7444: 				   [$seclevel,    'course'  ],
 7445: 				   [$courselevelr,'resource']));
 7446: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7447: 
 7448: # ------------------------------------------------------ third, check map parms
 7449: 	    my %parmhash=();
 7450: 	    my $thisparm='';
 7451: 	    if (tie(%parmhash,'GDBM_File',
 7452: 		    $env{'request.course.fn'}.'_parms.db',
 7453: 		    &GDBM_READER(),0640)) {
 7454: 		$thisparm=$parmhash{$symbparm};
 7455: 		untie(%parmhash);
 7456: 	    }
 7457: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 7458: 	}
 7459: # ------------------------------------------ fourth, look in resource metadata
 7460: 
 7461: 	$spacequalifierrest=~s/\./\_/;
 7462: 	my $filename;
 7463: 	if (!$symbparm) { $symbparm=&symbread(); }
 7464: 	if ($symbparm) {
 7465: 	    $filename=(&decode_symb($symbparm))[2];
 7466: 	} else {
 7467: 	    $filename=$env{'request.filename'};
 7468: 	}
 7469: 	my $metadata=&metadata($filename,$spacequalifierrest);
 7470: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7471: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 7472: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7473: 
 7474: # ---------------------------------------------- fourth, look in rest of course
 7475: 	if ($symbparm && defined($courseid) && 
 7476: 	    $courseid eq $env{'request.course.id'}) {
 7477: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7478: 				     $env{'course.'.$courseid.'.domain'},
 7479: 				     'course',
 7480: 				     ([$courselevelm,'map'   ],
 7481: 				      [$courselevel, 'course']));
 7482: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7483: 	}
 7484: # ------------------------------------------------------------------ Cascade up
 7485: 	unless ($space eq '0') {
 7486: 	    my @parts=split(/_/,$space);
 7487: 	    my $id=pop(@parts);
 7488: 	    my $part=join('_',@parts);
 7489: 	    if ($part eq '') { $part='0'; }
 7490: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 7491: 				 $symbparm,$udom,$uname,$section,1);
 7492: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 7493: 	}
 7494: 	if ($recurse) { return undef; }
 7495: 	my $pack_def=&packages_tab_default($filename,$varname);
 7496: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 7497: # ---------------------------------------------------- Any other user namespace
 7498:     } elsif ($realm eq 'environment') {
 7499: # ----------------------------------------------------------------- environment
 7500: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 7501: 	    return $env{'environment.'.$spacequalifierrest};
 7502: 	} else {
 7503: 	    if ($uname eq 'anonymous' && $udom eq '') {
 7504: 		return '';
 7505: 	    }
 7506: 	    my %returnhash=&userenvironment($udom,$uname,
 7507: 					    $spacequalifierrest);
 7508: 	    return $returnhash{$spacequalifierrest};
 7509: 	}
 7510:     } elsif ($realm eq 'system') {
 7511: # ----------------------------------------------------------------- system.time
 7512: 	if ($space eq 'time') {
 7513: 	    return time;
 7514:         }
 7515:     } elsif ($realm eq 'server') {
 7516: # ----------------------------------------------------------------- system.time
 7517: 	if ($space eq 'name') {
 7518: 	    return $ENV{'SERVER_NAME'};
 7519:         }
 7520:     }
 7521:     return '';
 7522: }
 7523: 
 7524: sub get_reply {
 7525:     my ($reply_value) = @_;
 7526:     if (ref($reply_value) eq 'ARRAY') {
 7527:         if (wantarray) {
 7528: 	    return @$reply_value;
 7529:         }
 7530:         return $reply_value->[0];
 7531:     } else {
 7532:         return $reply_value;
 7533:     }
 7534: }
 7535: 
 7536: sub check_group_parms {
 7537:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 7538:     my @groupitems = ();
 7539:     my $resultitem;
 7540:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 7541:     foreach my $group (@{$groups}) {
 7542:         foreach my $level (@levels) {
 7543:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 7544:              push(@groupitems,[$item,$level->[1]]);
 7545:         }
 7546:     }
 7547:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 7548:                             $env{'course.'.$courseid.'.domain'},
 7549:                                      'course',@groupitems);
 7550:     return $coursereply;
 7551: }
 7552: 
 7553: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 7554:     my ($courseid,@groups) = @_;
 7555:     @groups = sort(@groups);
 7556:     return @groups;
 7557: }
 7558: 
 7559: sub packages_tab_default {
 7560:     my ($uri,$varname)=@_;
 7561:     my (undef,$part,$name)=split(/\./,$varname);
 7562: 
 7563:     my (@extension,@specifics,$do_default);
 7564:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 7565: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 7566: 	if ($pack_type eq 'default') {
 7567: 	    $do_default=1;
 7568: 	} elsif ($pack_type eq 'extension') {
 7569: 	    push(@extension,[$package,$pack_type,$pack_part]);
 7570: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 7571: 	    # only look at packages defaults for packages that this id is
 7572: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 7573: 	}
 7574:     }
 7575:     # first look for a package that matches the requested part id
 7576:     foreach my $package (@specifics) {
 7577: 	my (undef,$pack_type,$pack_part)=@{$package};
 7578: 	next if ($pack_part ne $part);
 7579: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7580: 	    return $packagetab{"$pack_type&$name&default"};
 7581: 	}
 7582:     }
 7583:     # look for any possible matching non extension_ package
 7584:     foreach my $package (@specifics) {
 7585: 	my (undef,$pack_type,$pack_part)=@{$package};
 7586: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7587: 	    return $packagetab{"$pack_type&$name&default"};
 7588: 	}
 7589: 	if ($pack_type eq 'part') { $pack_part='0'; }
 7590: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 7591: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 7592: 	}
 7593:     }
 7594:     # look for any posible extension_ match
 7595:     foreach my $package (@extension) {
 7596: 	my ($package,$pack_type)=@{$package};
 7597: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7598: 	    return $packagetab{"$pack_type&$name&default"};
 7599: 	}
 7600: 	if (defined($packagetab{$package."&$name&default"})) {
 7601: 	    return $packagetab{$package."&$name&default"};
 7602: 	}
 7603:     }
 7604:     # look for a global default setting
 7605:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 7606: 	return $packagetab{"default&$name&default"};
 7607:     }
 7608:     return undef;
 7609: }
 7610: 
 7611: sub add_prefix_and_part {
 7612:     my ($prefix,$part)=@_;
 7613:     my $keyroot;
 7614:     if (defined($prefix) && $prefix !~ /^__/) {
 7615: 	# prefix that has a part already
 7616: 	$keyroot=$prefix;
 7617:     } elsif (defined($prefix)) {
 7618: 	# prefix that is missing a part
 7619: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 7620:     } else {
 7621: 	# no prefix at all
 7622: 	if (defined($part)) { $keyroot='_'.$part; }
 7623:     }
 7624:     return $keyroot;
 7625: }
 7626: 
 7627: # ---------------------------------------------------------------- Get metadata
 7628: 
 7629: my %metaentry;
 7630: sub metadata {
 7631:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 7632:     $uri=&declutter($uri);
 7633:     # if it is a non metadata possible uri return quickly
 7634:     if (($uri eq '') || 
 7635: 	(($uri =~ m|^/*adm/|) && 
 7636: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 7637:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 7638: 	return undef;
 7639:     }
 7640:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 7641: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 7642: 	return undef;
 7643:     }
 7644:     my $filename=$uri;
 7645:     $uri=~s/\.meta$//;
 7646: #
 7647: # Is the metadata already cached?
 7648: # Look at timestamp of caching
 7649: # Everything is cached by the main uri, libraries are never directly cached
 7650: #
 7651:     if (!defined($liburi)) {
 7652: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 7653: 	if (defined($cached)) { return $result->{':'.$what}; }
 7654:     }
 7655:     {
 7656: #
 7657: # Is this a recursive call for a library?
 7658: #
 7659: #	if (! exists($metacache{$uri})) {
 7660: #	    $metacache{$uri}={};
 7661: #	}
 7662: 	my $cachetime = 60*60;
 7663:         if ($liburi) {
 7664: 	    $liburi=&declutter($liburi);
 7665:             $filename=$liburi;
 7666:         } else {
 7667: 	    &devalidate_cache_new('meta',$uri);
 7668: 	    undef(%metaentry);
 7669: 	}
 7670:         my %metathesekeys=();
 7671:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 7672: 	my $metastring;
 7673: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 7674: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 7675: 	    $metastring = 
 7676: 		&Apache::lonnet::ssi_body($which,
 7677: 					  ('grade_target' => 'meta'));
 7678: 	    $cachetime = 1; # only want this cached in the child not long term
 7679: 	} elsif ($uri !~ m -^(editupload)/-) {
 7680: 	    my $file=&filelocation('',&clutter($filename));
 7681: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 7682: 	    $metastring=&getfile($file);
 7683: 	}
 7684:         my $parser=HTML::LCParser->new(\$metastring);
 7685:         my $token;
 7686:         undef %metathesekeys;
 7687:         while ($token=$parser->get_token) {
 7688: 	    if ($token->[0] eq 'S') {
 7689: 		if (defined($token->[2]->{'package'})) {
 7690: #
 7691: # This is a package - get package info
 7692: #
 7693: 		    my $package=$token->[2]->{'package'};
 7694: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7695: 		    if (defined($token->[2]->{'id'})) { 
 7696: 			$keyroot.='_'.$token->[2]->{'id'}; 
 7697: 		    }
 7698: 		    if ($metaentry{':packages'}) {
 7699: 			$metaentry{':packages'}.=','.$package.$keyroot;
 7700: 		    } else {
 7701: 			$metaentry{':packages'}=$package.$keyroot;
 7702: 		    }
 7703: 		    foreach my $pack_entry (keys(%packagetab)) {
 7704: 			my $part=$keyroot;
 7705: 			$part=~s/^\_//;
 7706: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 7707: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 7708: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 7709: 			    # ignore package.tab specified default values
 7710:                             # here &package_tab_default() will fetch those
 7711: 			    if ($subp eq 'default') { next; }
 7712: 			    my $value=$packagetab{$pack_entry};
 7713: 			    my $unikey;
 7714: 			    if ($pack =~ /_0$/) {
 7715: 				$unikey='parameter_0_'.$name;
 7716: 				$part=0;
 7717: 			    } else {
 7718: 				$unikey='parameter'.$keyroot.'_'.$name;
 7719: 			    }
 7720: 			    if ($subp eq 'display') {
 7721: 				$value.=' [Part: '.$part.']';
 7722: 			    }
 7723: 			    $metaentry{':'.$unikey.'.part'}=$part;
 7724: 			    $metathesekeys{$unikey}=1;
 7725: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7726: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 7727: 			    }
 7728: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 7729: 				$metaentry{':'.$unikey}=
 7730: 				    $metaentry{':'.$unikey.'.default'};
 7731: 			    }
 7732: 			}
 7733: 		    }
 7734: 		} else {
 7735: #
 7736: # This is not a package - some other kind of start tag
 7737: #
 7738: 		    my $entry=$token->[1];
 7739: 		    my $unikey;
 7740: 		    if ($entry eq 'import') {
 7741: 			$unikey='';
 7742: 		    } else {
 7743: 			$unikey=$entry;
 7744: 		    }
 7745: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7746: 
 7747: 		    if (defined($token->[2]->{'id'})) { 
 7748: 			$unikey.='_'.$token->[2]->{'id'}; 
 7749: 		    }
 7750: 
 7751: 		    if ($entry eq 'import') {
 7752: #
 7753: # Importing a library here
 7754: #
 7755: 			if ($depthcount<20) {
 7756: 			    my $location=$parser->get_text('/import');
 7757: 			    my $dir=$filename;
 7758: 			    $dir=~s|[^/]*$||;
 7759: 			    $location=&filelocation($dir,$location);
 7760: 			    my $metadata = 
 7761: 				&metadata($uri,'keys', $location,$unikey,
 7762: 					  $depthcount+1);
 7763: 			    foreach my $meta (split(',',$metadata)) {
 7764: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 7765: 				$metathesekeys{$meta}=1;
 7766: 			    }
 7767: 			}
 7768: 		    } else { 
 7769: 			
 7770: 			if (defined($token->[2]->{'name'})) { 
 7771: 			    $unikey.='_'.$token->[2]->{'name'}; 
 7772: 			}
 7773: 			$metathesekeys{$unikey}=1;
 7774: 			foreach my $param (@{$token->[3]}) {
 7775: 			    $metaentry{':'.$unikey.'.'.$param} =
 7776: 				$token->[2]->{$param};
 7777: 			}
 7778: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 7779: 			my $default=$metaentry{':'.$unikey.'.default'};
 7780: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 7781: 		 # only ws inside the tag, and not in default, so use default
 7782: 		 # as value
 7783: 			    $metaentry{':'.$unikey}=$default;
 7784: 			} elsif ( $internaltext =~ /\S/ ) {
 7785: 		  # something interesting inside the tag
 7786: 			    $metaentry{':'.$unikey}=$internaltext;
 7787: 			} else {
 7788: 		  # no interesting values, don't set a default
 7789: 			}
 7790: # end of not-a-package not-a-library import
 7791: 		    }
 7792: # end of not-a-package start tag
 7793: 		}
 7794: # the next is the end of "start tag"
 7795: 	    }
 7796: 	}
 7797: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 7798: 	$extension = lc($extension);
 7799: 	if ($extension eq 'htm') { $extension='html'; }
 7800: 
 7801: 	foreach my $key (keys(%packagetab)) {
 7802: 	    #no specific packages #how's our extension
 7803: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 7804: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 7805: 					 \%metathesekeys);
 7806: 	}
 7807: 
 7808: 	if (!exists($metaentry{':packages'})
 7809: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 7810: 	    foreach my $key (keys(%packagetab)) {
 7811: 		#no specific packages well let's get default then
 7812: 		if ($key!~/^default&/) { next; }
 7813: 		&metadata_create_package_def($uri,$key,'default',
 7814: 					     \%metathesekeys);
 7815: 	    }
 7816: 	}
 7817: # are there custom rights to evaluate
 7818: 	if ($metaentry{':copyright'} eq 'custom') {
 7819: 
 7820:     #
 7821:     # Importing a rights file here
 7822:     #
 7823: 	    unless ($depthcount) {
 7824: 		my $location=$metaentry{':customdistributionfile'};
 7825: 		my $dir=$filename;
 7826: 		$dir=~s|[^/]*$||;
 7827: 		$location=&filelocation($dir,$location);
 7828: 		my $rights_metadata =
 7829: 		    &metadata($uri,'keys',$location,'_rights',
 7830: 			      $depthcount+1);
 7831: 		foreach my $rights (split(',',$rights_metadata)) {
 7832: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 7833: 		    $metathesekeys{$rights}=1;
 7834: 		}
 7835: 	    }
 7836: 	}
 7837: 	# uniqifiy package listing
 7838: 	my %seen;
 7839: 	my @uniq_packages =
 7840: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 7841: 	$metaentry{':packages'} = join(',',@uniq_packages);
 7842: 
 7843: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 7844: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 7845: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 7846: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 7847: # this is the end of "was not already recently cached
 7848:     }
 7849:     return $metaentry{':'.$what};
 7850: }
 7851: 
 7852: sub metadata_create_package_def {
 7853:     my ($uri,$key,$package,$metathesekeys)=@_;
 7854:     my ($pack,$name,$subp)=split(/\&/,$key);
 7855:     if ($subp eq 'default') { next; }
 7856:     
 7857:     if (defined($metaentry{':packages'})) {
 7858: 	$metaentry{':packages'}.=','.$package;
 7859:     } else {
 7860: 	$metaentry{':packages'}=$package;
 7861:     }
 7862:     my $value=$packagetab{$key};
 7863:     my $unikey;
 7864:     $unikey='parameter_0_'.$name;
 7865:     $metaentry{':'.$unikey.'.part'}=0;
 7866:     $$metathesekeys{$unikey}=1;
 7867:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7868: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 7869:     }
 7870:     if (defined($metaentry{':'.$unikey.'.default'})) {
 7871: 	$metaentry{':'.$unikey}=
 7872: 	    $metaentry{':'.$unikey.'.default'};
 7873:     }
 7874: }
 7875: 
 7876: sub metadata_generate_part0 {
 7877:     my ($metadata,$metacache,$uri) = @_;
 7878:     my %allnames;
 7879:     foreach my $metakey (keys(%$metadata)) {
 7880: 	if ($metakey=~/^parameter\_(.*)/) {
 7881: 	  my $part=$$metacache{':'.$metakey.'.part'};
 7882: 	  my $name=$$metacache{':'.$metakey.'.name'};
 7883: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 7884: 	    $allnames{$name}=$part;
 7885: 	  }
 7886: 	}
 7887:     }
 7888:     foreach my $name (keys(%allnames)) {
 7889:       $$metadata{"parameter_0_$name"}=1;
 7890:       my $key=":parameter_0_$name";
 7891:       $$metacache{"$key.part"}='0';
 7892:       $$metacache{"$key.name"}=$name;
 7893:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 7894: 					   $allnames{$name}.'_'.$name.
 7895: 					   '.type'};
 7896:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 7897: 			     '.display'};
 7898:       my $expr='[Part: '.$allnames{$name}.']';
 7899:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 7900:       $$metacache{"$key.display"}=$olddis;
 7901:     }
 7902: }
 7903: 
 7904: # ------------------------------------------------------ Devalidate title cache
 7905: 
 7906: sub devalidate_title_cache {
 7907:     my ($url)=@_;
 7908:     if (!$env{'request.course.id'}) { return; }
 7909:     my $symb=&symbread($url);
 7910:     if (!$symb) { return; }
 7911:     my $key=$env{'request.course.id'}."\0".$symb;
 7912:     &devalidate_cache_new('title',$key);
 7913: }
 7914: 
 7915: # ------------------------------------------------- Get the title of a resource
 7916: 
 7917: sub gettitle {
 7918:     my $urlsymb=shift;
 7919:     my $symb=&symbread($urlsymb);
 7920:     if ($symb) {
 7921: 	my $key=$env{'request.course.id'}."\0".$symb;
 7922: 	my ($result,$cached)=&is_cached_new('title',$key);
 7923: 	if (defined($cached)) { 
 7924: 	    return $result;
 7925: 	}
 7926: 	my ($map,$resid,$url)=&decode_symb($symb);
 7927: 	my $title='';
 7928: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 7929: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 7930: 	} else {
 7931: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7932: 		    &GDBM_READER(),0640)) {
 7933: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 7934: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 7935: 		untie(%bighash);
 7936: 	    }
 7937: 	}
 7938: 	$title=~s/\&colon\;/\:/gs;
 7939: 	if ($title) {
 7940: 	    return &do_cache_new('title',$key,$title,600);
 7941: 	}
 7942: 	$urlsymb=$url;
 7943:     }
 7944:     my $title=&metadata($urlsymb,'title');
 7945:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 7946:     return $title;
 7947: }
 7948: 
 7949: sub get_slot {
 7950:     my ($which,$cnum,$cdom)=@_;
 7951:     if (!$cnum || !$cdom) {
 7952: 	(undef,my $courseid)=&whichuser();
 7953: 	$cdom=$env{'course.'.$courseid.'.domain'};
 7954: 	$cnum=$env{'course.'.$courseid.'.num'};
 7955:     }
 7956:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 7957:     my %slotinfo;
 7958:     if (exists($remembered{$key})) {
 7959: 	$slotinfo{$which} = $remembered{$key};
 7960:     } else {
 7961: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 7962: 	&Apache::lonhomework::showhash(%slotinfo);
 7963: 	my ($tmp)=keys(%slotinfo);
 7964: 	if ($tmp=~/^error:/) { return (); }
 7965: 	$remembered{$key} = $slotinfo{$which};
 7966:     }
 7967:     if (ref($slotinfo{$which}) eq 'HASH') {
 7968: 	return %{$slotinfo{$which}};
 7969:     }
 7970:     return $slotinfo{$which};
 7971: }
 7972: # ------------------------------------------------- Update symbolic store links
 7973: 
 7974: sub symblist {
 7975:     my ($mapname,%newhash)=@_;
 7976:     $mapname=&deversion(&declutter($mapname));
 7977:     my %hash;
 7978:     if (($env{'request.course.fn'}) && (%newhash)) {
 7979:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7980:                       &GDBM_WRCREAT(),0640)) {
 7981: 	    foreach my $url (keys(%newhash)) {
 7982: 		next if ($url eq 'last_known'
 7983: 			 && $env{'form.no_update_last_known'});
 7984: 		$hash{declutter($url)}=&encode_symb($mapname,
 7985: 						    $newhash{$url}->[1],
 7986: 						    $newhash{$url}->[0]);
 7987:             }
 7988:             if (untie(%hash)) {
 7989: 		return 'ok';
 7990:             }
 7991:         }
 7992:     }
 7993:     return 'error';
 7994: }
 7995: 
 7996: # --------------------------------------------------------------- Verify a symb
 7997: 
 7998: sub symbverify {
 7999:     my ($symb,$thisurl)=@_;
 8000:     my $thisfn=$thisurl;
 8001:     $thisfn=&declutter($thisfn);
 8002: # direct jump to resource in page or to a sequence - will construct own symbs
 8003:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 8004: # check URL part
 8005:     my ($map,$resid,$url)=&decode_symb($symb);
 8006: 
 8007:     unless ($url eq $thisfn) { return 0; }
 8008: 
 8009:     $symb=&symbclean($symb);
 8010:     $thisurl=&deversion($thisurl);
 8011:     $thisfn=&deversion($thisfn);
 8012: 
 8013:     my %bighash;
 8014:     my $okay=0;
 8015: 
 8016:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8017:                             &GDBM_READER(),0640)) {
 8018:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 8019:         unless ($ids) { 
 8020:            $ids=$bighash{'ids_/'.$thisurl};
 8021:         }
 8022:         if ($ids) {
 8023: # ------------------------------------------------------------------- Has ID(s)
 8024: 	    foreach my $id (split(/\,/,$ids)) {
 8025: 	       my ($mapid,$resid)=split(/\./,$id);
 8026:                if (
 8027:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 8028:    eq $symb) { 
 8029: 		   if (($env{'request.role.adv'}) ||
 8030: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 8031: 		       $okay=1; 
 8032: 		   }
 8033: 	       }
 8034: 	   }
 8035:         }
 8036: 	untie(%bighash);
 8037:     }
 8038:     return $okay;
 8039: }
 8040: 
 8041: # --------------------------------------------------------------- Clean-up symb
 8042: 
 8043: sub symbclean {
 8044:     my $symb=shift;
 8045:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 8046: # remove version from map
 8047:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 8048: 
 8049: # remove version from URL
 8050:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 8051: 
 8052: # remove wrapper
 8053: 
 8054:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 8055:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 8056:     return $symb;
 8057: }
 8058: 
 8059: # ---------------------------------------------- Split symb to find map and url
 8060: 
 8061: sub encode_symb {
 8062:     my ($map,$resid,$url)=@_;
 8063:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 8064: }
 8065: 
 8066: sub decode_symb {
 8067:     my $symb=shift;
 8068:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 8069:     my ($map,$resid,$url)=split(/___/,$symb);
 8070:     return (&fixversion($map),$resid,&fixversion($url));
 8071: }
 8072: 
 8073: sub fixversion {
 8074:     my $fn=shift;
 8075:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 8076:     my %bighash;
 8077:     my $uri=&clutter($fn);
 8078:     my $key=$env{'request.course.id'}.'_'.$uri;
 8079: # is this cached?
 8080:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 8081:     if (defined($cached)) { return $result; }
 8082: # unfortunately not cached, or expired
 8083:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8084: 	    &GDBM_READER(),0640)) {
 8085:  	if ($bighash{'version_'.$uri}) {
 8086:  	    my $version=$bighash{'version_'.$uri};
 8087:  	    unless (($version eq 'mostrecent') || 
 8088: 		    ($version==&getversion($uri))) {
 8089:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 8090:  	    }
 8091:  	}
 8092:  	untie %bighash;
 8093:     }
 8094:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 8095: }
 8096: 
 8097: sub deversion {
 8098:     my $url=shift;
 8099:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 8100:     return $url;
 8101: }
 8102: 
 8103: # ------------------------------------------------------ Return symb list entry
 8104: 
 8105: sub symbread {
 8106:     my ($thisfn,$donotrecurse)=@_;
 8107:     my $cache_str='request.symbread.cached.'.$thisfn;
 8108:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 8109: # no filename provided? try from environment
 8110:     unless ($thisfn) {
 8111:         if ($env{'request.symb'}) {
 8112: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 8113: 	}
 8114: 	$thisfn=$env{'request.filename'};
 8115:     }
 8116:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8117: # is that filename actually a symb? Verify, clean, and return
 8118:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 8119: 	if (&symbverify($thisfn,$1)) {
 8120: 	    return $env{$cache_str}=&symbclean($thisfn);
 8121: 	}
 8122:     }
 8123:     $thisfn=declutter($thisfn);
 8124:     my %hash;
 8125:     my %bighash;
 8126:     my $syval='';
 8127:     if (($env{'request.course.fn'}) && ($thisfn)) {
 8128:         my $targetfn = $thisfn;
 8129:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 8130:             $targetfn = 'adm/wrapper/'.$thisfn;
 8131:         }
 8132: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 8133: 	    $targetfn=$1;
 8134: 	}
 8135:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 8136:                       &GDBM_READER(),0640)) {
 8137: 	    $syval=$hash{$targetfn};
 8138:             untie(%hash);
 8139:         }
 8140: # ---------------------------------------------------------- There was an entry
 8141:         if ($syval) {
 8142: 	    #unless ($syval=~/\_\d+$/) {
 8143: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 8144: 		    #&appenv({'request.ambiguous' => $thisfn});
 8145: 		    #return $env{$cache_str}='';
 8146: 		#}    
 8147: 		#$syval.=$1;
 8148: 	    #}
 8149:         } else {
 8150: # ------------------------------------------------------- Was not in symb table
 8151:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8152:                             &GDBM_READER(),0640)) {
 8153: # ---------------------------------------------- Get ID(s) for current resource
 8154:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 8155:               unless ($ids) { 
 8156:                  $ids=$bighash{'ids_/'.$thisfn};
 8157:               }
 8158:               unless ($ids) {
 8159: # alias?
 8160: 		  $ids=$bighash{'mapalias_'.$thisfn};
 8161:               }
 8162:               if ($ids) {
 8163: # ------------------------------------------------------------------- Has ID(s)
 8164:                  my @possibilities=split(/\,/,$ids);
 8165:                  if ($#possibilities==0) {
 8166: # ----------------------------------------------- There is only one possibility
 8167: 		     my ($mapid,$resid)=split(/\./,$ids);
 8168: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 8169: 						    $resid,$thisfn);
 8170:                  } elsif (!$donotrecurse) {
 8171: # ------------------------------------------ There is more than one possibility
 8172:                      my $realpossible=0;
 8173:                      foreach my $id (@possibilities) {
 8174: 			 my $file=$bighash{'src_'.$id};
 8175:                          if (&allowed('bre',$file)) {
 8176:          		    my ($mapid,$resid)=split(/\./,$id);
 8177:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 8178: 				$realpossible++;
 8179:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 8180: 						    $resid,$thisfn);
 8181:                             }
 8182: 			 }
 8183:                      }
 8184: 		     if ($realpossible!=1) { $syval=''; }
 8185:                  } else {
 8186:                      $syval='';
 8187:                  }
 8188: 	      }
 8189:               untie(%bighash)
 8190:            }
 8191:         }
 8192:         if ($syval) {
 8193: 	    return $env{$cache_str}=$syval;
 8194:         }
 8195:     }
 8196:     &appenv({'request.ambiguous' => $thisfn});
 8197:     return $env{$cache_str}='';
 8198: }
 8199: 
 8200: # ---------------------------------------------------------- Return random seed
 8201: 
 8202: sub numval {
 8203:     my $txt=shift;
 8204:     $txt=~tr/A-J/0-9/;
 8205:     $txt=~tr/a-j/0-9/;
 8206:     $txt=~tr/K-T/0-9/;
 8207:     $txt=~tr/k-t/0-9/;
 8208:     $txt=~tr/U-Z/0-5/;
 8209:     $txt=~tr/u-z/0-5/;
 8210:     $txt=~s/\D//g;
 8211:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 8212:     return int($txt);
 8213: }
 8214: 
 8215: sub numval2 {
 8216:     my $txt=shift;
 8217:     $txt=~tr/A-J/0-9/;
 8218:     $txt=~tr/a-j/0-9/;
 8219:     $txt=~tr/K-T/0-9/;
 8220:     $txt=~tr/k-t/0-9/;
 8221:     $txt=~tr/U-Z/0-5/;
 8222:     $txt=~tr/u-z/0-5/;
 8223:     $txt=~s/\D//g;
 8224:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8225:     my $total;
 8226:     foreach my $val (@txts) { $total+=$val; }
 8227:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 8228:     return int($total);
 8229: }
 8230: 
 8231: sub numval3 {
 8232:     use integer;
 8233:     my $txt=shift;
 8234:     $txt=~tr/A-J/0-9/;
 8235:     $txt=~tr/a-j/0-9/;
 8236:     $txt=~tr/K-T/0-9/;
 8237:     $txt=~tr/k-t/0-9/;
 8238:     $txt=~tr/U-Z/0-5/;
 8239:     $txt=~tr/u-z/0-5/;
 8240:     $txt=~s/\D//g;
 8241:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8242:     my $total;
 8243:     foreach my $val (@txts) { $total+=$val; }
 8244:     if ($_64bit) { $total=(($total<<32)>>32); }
 8245:     return $total;
 8246: }
 8247: 
 8248: sub digest {
 8249:     my ($data)=@_;
 8250:     my $digest=&Digest::MD5::md5($data);
 8251:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 8252:     my ($e,$f);
 8253:     {
 8254:         use integer;
 8255:         $e=($a+$b);
 8256:         $f=($c+$d);
 8257:         if ($_64bit) {
 8258:             $e=(($e<<32)>>32);
 8259:             $f=(($f<<32)>>32);
 8260:         }
 8261:     }
 8262:     if (wantarray) {
 8263: 	return ($e,$f);
 8264:     } else {
 8265: 	my $g;
 8266: 	{
 8267: 	    use integer;
 8268: 	    $g=($e+$f);
 8269: 	    if ($_64bit) {
 8270: 		$g=(($g<<32)>>32);
 8271: 	    }
 8272: 	}
 8273: 	return $g;
 8274:     }
 8275: }
 8276: 
 8277: sub latest_rnd_algorithm_id {
 8278:     return '64bit5';
 8279: }
 8280: 
 8281: sub get_rand_alg {
 8282:     my ($courseid)=@_;
 8283:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 8284:     if ($courseid) {
 8285: 	return $env{"course.$courseid.rndseed"};
 8286:     }
 8287:     return &latest_rnd_algorithm_id();
 8288: }
 8289: 
 8290: sub validCODE {
 8291:     my ($CODE)=@_;
 8292:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 8293:     return 0;
 8294: }
 8295: 
 8296: sub getCODE {
 8297:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 8298:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 8299: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 8300: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 8301: 	return $Apache::lonhomework::history{'resource.CODE'};
 8302:     }
 8303:     return undef;
 8304: }
 8305: 
 8306: sub rndseed {
 8307:     my ($symb,$courseid,$domain,$username)=@_;
 8308:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 8309:     if (!defined($symb)) {
 8310: 	unless ($symb=$wsymb) { return time; }
 8311:     }
 8312:     if (!$courseid) { $courseid=$wcourseid; }
 8313:     if (!$domain) { $domain=$wdomain; }
 8314:     if (!$username) { $username=$wusername }
 8315:     my $which=&get_rand_alg();
 8316: 
 8317:     if (defined(&getCODE())) {
 8318: 	if ($which eq '64bit5') {
 8319: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 8320: 	} elsif ($which eq '64bit4') {
 8321: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 8322: 	} else {
 8323: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 8324: 	}
 8325:     } elsif ($which eq '64bit5') {
 8326: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 8327:     } elsif ($which eq '64bit4') {
 8328: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 8329:     } elsif ($which eq '64bit3') {
 8330: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 8331:     } elsif ($which eq '64bit2') {
 8332: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 8333:     } elsif ($which eq '64bit') {
 8334: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 8335:     }
 8336:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 8337: }
 8338: 
 8339: sub rndseed_32bit {
 8340:     my ($symb,$courseid,$domain,$username)=@_;
 8341:     {
 8342: 	use integer;
 8343: 	my $symbchck=unpack("%32C*",$symb) << 27;
 8344: 	my $symbseed=numval($symb) << 22;
 8345: 	my $namechck=unpack("%32C*",$username) << 17;
 8346: 	my $nameseed=numval($username) << 12;
 8347: 	my $domainseed=unpack("%32C*",$domain) << 7;
 8348: 	my $courseseed=unpack("%32C*",$courseid);
 8349: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 8350: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8351: 	#&logthis("rndseed :$num:$symb");
 8352: 	if ($_64bit) { $num=(($num<<32)>>32); }
 8353: 	return $num;
 8354:     }
 8355: }
 8356: 
 8357: sub rndseed_64bit {
 8358:     my ($symb,$courseid,$domain,$username)=@_;
 8359:     {
 8360: 	use integer;
 8361: 	my $symbchck=unpack("%32S*",$symb) << 21;
 8362: 	my $symbseed=numval($symb) << 10;
 8363: 	my $namechck=unpack("%32S*",$username);
 8364: 	
 8365: 	my $nameseed=numval($username) << 21;
 8366: 	my $domainseed=unpack("%32S*",$domain) << 10;
 8367: 	my $courseseed=unpack("%32S*",$courseid);
 8368: 	
 8369: 	my $num1=$symbchck+$symbseed+$namechck;
 8370: 	my $num2=$nameseed+$domainseed+$courseseed;
 8371: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8372: 	#&logthis("rndseed :$num:$symb");
 8373: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8374: 	return "$num1,$num2";
 8375:     }
 8376: }
 8377: 
 8378: sub rndseed_64bit2 {
 8379:     my ($symb,$courseid,$domain,$username)=@_;
 8380:     {
 8381: 	use integer;
 8382: 	# strings need to be an even # of cahracters long, it it is odd the
 8383:         # last characters gets thrown away
 8384: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8385: 	my $symbseed=numval($symb) << 10;
 8386: 	my $namechck=unpack("%32S*",$username.' ');
 8387: 	
 8388: 	my $nameseed=numval($username) << 21;
 8389: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8390: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8391: 	
 8392: 	my $num1=$symbchck+$symbseed+$namechck;
 8393: 	my $num2=$nameseed+$domainseed+$courseseed;
 8394: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8395: 	#&logthis("rndseed :$num:$symb");
 8396: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8397: 	return "$num1,$num2";
 8398:     }
 8399: }
 8400: 
 8401: sub rndseed_64bit3 {
 8402:     my ($symb,$courseid,$domain,$username)=@_;
 8403:     {
 8404: 	use integer;
 8405: 	# strings need to be an even # of cahracters long, it it is odd the
 8406:         # last characters gets thrown away
 8407: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8408: 	my $symbseed=numval2($symb) << 10;
 8409: 	my $namechck=unpack("%32S*",$username.' ');
 8410: 	
 8411: 	my $nameseed=numval2($username) << 21;
 8412: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8413: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8414: 	
 8415: 	my $num1=$symbchck+$symbseed+$namechck;
 8416: 	my $num2=$nameseed+$domainseed+$courseseed;
 8417: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8418: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8419: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8420: 	
 8421: 	return "$num1:$num2";
 8422:     }
 8423: }
 8424: 
 8425: sub rndseed_64bit4 {
 8426:     my ($symb,$courseid,$domain,$username)=@_;
 8427:     {
 8428: 	use integer;
 8429: 	# strings need to be an even # of cahracters long, it it is odd the
 8430:         # last characters gets thrown away
 8431: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8432: 	my $symbseed=numval3($symb) << 10;
 8433: 	my $namechck=unpack("%32S*",$username.' ');
 8434: 	
 8435: 	my $nameseed=numval3($username) << 21;
 8436: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8437: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8438: 	
 8439: 	my $num1=$symbchck+$symbseed+$namechck;
 8440: 	my $num2=$nameseed+$domainseed+$courseseed;
 8441: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8442: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8443: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8444: 	
 8445: 	return "$num1:$num2";
 8446:     }
 8447: }
 8448: 
 8449: sub rndseed_64bit5 {
 8450:     my ($symb,$courseid,$domain,$username)=@_;
 8451:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 8452:     return "$num1:$num2";
 8453: }
 8454: 
 8455: sub rndseed_CODE_64bit {
 8456:     my ($symb,$courseid,$domain,$username)=@_;
 8457:     {
 8458: 	use integer;
 8459: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8460: 	my $symbseed=numval2($symb);
 8461: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8462: 	my $CODEseed=numval(&getCODE());
 8463: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8464: 	my $num1=$symbseed+$CODEchck;
 8465: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8466: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8467: 	#&logthis("rndseed :$num1:$num2:$symb");
 8468: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8469: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8470: 	return "$num1:$num2";
 8471:     }
 8472: }
 8473: 
 8474: sub rndseed_CODE_64bit4 {
 8475:     my ($symb,$courseid,$domain,$username)=@_;
 8476:     {
 8477: 	use integer;
 8478: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8479: 	my $symbseed=numval3($symb);
 8480: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8481: 	my $CODEseed=numval3(&getCODE());
 8482: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8483: 	my $num1=$symbseed+$CODEchck;
 8484: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8485: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8486: 	#&logthis("rndseed :$num1:$num2:$symb");
 8487: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8488: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8489: 	return "$num1:$num2";
 8490:     }
 8491: }
 8492: 
 8493: sub rndseed_CODE_64bit5 {
 8494:     my ($symb,$courseid,$domain,$username)=@_;
 8495:     my $code = &getCODE();
 8496:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 8497:     return "$num1:$num2";
 8498: }
 8499: 
 8500: sub setup_random_from_rndseed {
 8501:     my ($rndseed)=@_;
 8502:     if ($rndseed =~/([,:])/) {
 8503: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 8504: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 8505:     } else {
 8506: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 8507:     }
 8508: }
 8509: 
 8510: sub latest_receipt_algorithm_id {
 8511:     return 'receipt3';
 8512: }
 8513: 
 8514: sub recunique {
 8515:     my $fucourseid=shift;
 8516:     my $unique;
 8517:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 8518: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8519: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 8520:     } else {
 8521: 	$unique=$perlvar{'lonReceipt'};
 8522:     }
 8523:     return unpack("%32C*",$unique);
 8524: }
 8525: 
 8526: sub recprefix {
 8527:     my $fucourseid=shift;
 8528:     my $prefix;
 8529:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 8530: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8531: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 8532:     } else {
 8533: 	$prefix=$perlvar{'lonHostID'};
 8534:     }
 8535:     return unpack("%32C*",$prefix);
 8536: }
 8537: 
 8538: sub ireceipt {
 8539:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 8540: 
 8541:     my $return =&recprefix($fucourseid).'-';
 8542: 
 8543:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 8544: 	$env{'request.state'} eq 'construct') {
 8545: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 8546: 	return $return;
 8547:     }
 8548: 
 8549:     my $cuname=unpack("%32C*",$funame);
 8550:     my $cudom=unpack("%32C*",$fudom);
 8551:     my $cucourseid=unpack("%32C*",$fucourseid);
 8552:     my $cusymb=unpack("%32C*",$fusymb);
 8553:     my $cunique=&recunique($fucourseid);
 8554:     my $cpart=unpack("%32S*",$part);
 8555:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 8556: 
 8557: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 8558: 			       
 8559: 	$return.= ($cunique%$cuname+
 8560: 		   $cunique%$cudom+
 8561: 		   $cusymb%$cuname+
 8562: 		   $cusymb%$cudom+
 8563: 		   $cucourseid%$cuname+
 8564: 		   $cucourseid%$cudom+
 8565: 		   $cpart%$cuname+
 8566: 		   $cpart%$cudom);
 8567:     } else {
 8568: 	$return.= ($cunique%$cuname+
 8569: 		   $cunique%$cudom+
 8570: 		   $cusymb%$cuname+
 8571: 		   $cusymb%$cudom+
 8572: 		   $cucourseid%$cuname+
 8573: 		   $cucourseid%$cudom);
 8574:     }
 8575:     return $return;
 8576: }
 8577: 
 8578: sub receipt {
 8579:     my ($part)=@_;
 8580:     my ($symb,$courseid,$domain,$name) = &whichuser();
 8581:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 8582: }
 8583: 
 8584: sub whichuser {
 8585:     my ($passedsymb)=@_;
 8586:     my ($symb,$courseid,$domain,$name,$publicuser);
 8587:     if (defined($env{'form.grade_symb'})) {
 8588: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 8589: 	my $allowed=&allowed('vgr',$tmp_courseid);
 8590: 	if (!$allowed &&
 8591: 	    exists($env{'request.course.sec'}) &&
 8592: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 8593: 	    $allowed=&allowed('vgr',$tmp_courseid.
 8594: 			      '/'.$env{'request.course.sec'});
 8595: 	}
 8596: 	if ($allowed) {
 8597: 	    ($symb)=&get_env_multiple('form.grade_symb');
 8598: 	    $courseid=$tmp_courseid;
 8599: 	    ($domain)=&get_env_multiple('form.grade_domain');
 8600: 	    ($name)=&get_env_multiple('form.grade_username');
 8601: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 8602: 	}
 8603:     }
 8604:     if (!$passedsymb) {
 8605: 	$symb=&symbread();
 8606:     } else {
 8607: 	$symb=$passedsymb;
 8608:     }
 8609:     $courseid=$env{'request.course.id'};
 8610:     $domain=$env{'user.domain'};
 8611:     $name=$env{'user.name'};
 8612:     if ($name eq 'public' && $domain eq 'public') {
 8613: 	if (!defined($env{'form.username'})) {
 8614: 	    $env{'form.username'}.=time.rand(10000000);
 8615: 	}
 8616: 	$name.=$env{'form.username'};
 8617:     }
 8618:     return ($symb,$courseid,$domain,$name,$publicuser);
 8619: 
 8620: }
 8621: 
 8622: # ------------------------------------------------------------ Serves up a file
 8623: # returns either the contents of the file or 
 8624: # -1 if the file doesn't exist
 8625: #
 8626: # if the target is a file that was uploaded via DOCS, 
 8627: # a check will be made to see if a current copy exists on the local server,
 8628: # if it does this will be served, otherwise a copy will be retrieved from
 8629: # the home server for the course and stored in /home/httpd/html/userfiles on
 8630: # the local server.   
 8631: 
 8632: sub getfile {
 8633:     my ($file) = @_;
 8634:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8635:     &repcopy($file);
 8636:     return &readfile($file);
 8637: }
 8638: 
 8639: sub repcopy_userfile {
 8640:     my ($file)=@_;
 8641:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8642:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 8643:     my ($cdom,$cnum,$filename) = 
 8644: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 8645:     my $uri="/uploaded/$cdom/$cnum/$filename";
 8646:     if (-e "$file") {
 8647: # we already have a local copy, check it out
 8648: 	my @fileinfo = stat($file);
 8649: 	my $rtncode;
 8650: 	my $info;
 8651: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 8652: 	if ($lwpresp ne 'ok') {
 8653: # there is no such file anymore, even though we had a local copy
 8654: 	    if ($rtncode eq '404') {
 8655: 		unlink($file);
 8656: 	    }
 8657: 	    return -1;
 8658: 	}
 8659: 	if ($info < $fileinfo[9]) {
 8660: # nice, the file we have is up-to-date, just say okay
 8661: 	    return 'ok';
 8662: 	} else {
 8663: # the file is outdated, get rid of it
 8664: 	    unlink($file);
 8665: 	}
 8666:     }
 8667: # one way or the other, at this point, we don't have the file
 8668: # construct the correct path for the file
 8669:     my @parts = ($cdom,$cnum); 
 8670:     if ($filename =~ m|^(.+)/[^/]+$|) {
 8671: 	push @parts, split(/\//,$1);
 8672:     }
 8673:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 8674:     foreach my $part (@parts) {
 8675: 	$path .= '/'.$part;
 8676: 	if (!-e $path) {
 8677: 	    mkdir($path,0770);
 8678: 	}
 8679:     }
 8680: # now the path exists for sure
 8681: # get a user agent
 8682:     my $ua=new LWP::UserAgent;
 8683:     my $transferfile=$file.'.in.transfer';
 8684: # FIXME: this should flock
 8685:     if (-e $transferfile) { return 'ok'; }
 8686:     my $request;
 8687:     $uri=~s/^\///;
 8688:     my $homeserver = &homeserver($cnum,$cdom);
 8689:     my $protocol = $protocol{$homeserver};
 8690:     $protocol = 'http' if ($protocol ne 'https');
 8691:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
 8692:     my $response=$ua->request($request,$transferfile);
 8693: # did it work?
 8694:     if ($response->is_error()) {
 8695: 	unlink($transferfile);
 8696: 	&logthis("Userfile repcopy failed for $uri");
 8697: 	return -1;
 8698:     }
 8699: # worked, rename the transfer file
 8700:     rename($transferfile,$file);
 8701:     return 'ok';
 8702: }
 8703: 
 8704: sub tokenwrapper {
 8705:     my $uri=shift;
 8706:     $uri=~s|^https?\://([^/]+)||;
 8707:     $uri=~s|^/||;
 8708:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 8709:     my $token=$1;
 8710:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 8711:     if ($udom && $uname && $file) {
 8712: 	$file=~s|(\?\.*)*$||;
 8713:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 8714:         my $homeserver = &homeserver($uname,$udom);
 8715:         my $protocol = $protocol{$homeserver};
 8716:         $protocol = 'http' if ($protocol ne 'https');
 8717:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
 8718:                (($uri=~/\?/)?'&':'?').'token='.$token.
 8719:                                '&tokenissued='.$perlvar{'lonHostID'};
 8720:     } else {
 8721:         return '/adm/notfound.html';
 8722:     }
 8723: }
 8724: 
 8725: # call with reqtype HEAD: get last modification time
 8726: # call with reqtype GET: get the file contents
 8727: # Do not call this with reqtype GET for large files! It loads everything into memory
 8728: #
 8729: sub getuploaded {
 8730:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 8731:     $uri=~s/^\///;
 8732:     my $homeserver = &homeserver($cnum,$cdom);
 8733:     my $protocol = $protocol{$homeserver};
 8734:     $protocol = 'http' if ($protocol ne 'https');
 8735:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
 8736:     my $ua=new LWP::UserAgent;
 8737:     my $request=new HTTP::Request($reqtype,$uri);
 8738:     my $response=$ua->request($request);
 8739:     $$rtncode = $response->code;
 8740:     if (! $response->is_success()) {
 8741: 	return 'failed';
 8742:     }      
 8743:     if ($reqtype eq 'HEAD') {
 8744: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 8745:     } elsif ($reqtype eq 'GET') {
 8746: 	$$info = $response->content;
 8747:     }
 8748:     return 'ok';
 8749: }
 8750: 
 8751: sub readfile {
 8752:     my $file = shift;
 8753:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 8754:     my $fh;
 8755:     open($fh,"<$file");
 8756:     my $a='';
 8757:     while (my $line = <$fh>) { $a .= $line; }
 8758:     return $a;
 8759: }
 8760: 
 8761: sub filelocation {
 8762:     my ($dir,$file) = @_;
 8763:     my $location;
 8764:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 8765: 
 8766:     if ($file =~ m-^/adm/-) {
 8767: 	$file=~s-^/adm/wrapper/-/-;
 8768: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8769:     }
 8770: 
 8771:     if ($file=~m:^/~:) { # is a contruction space reference
 8772:         $location = $file;
 8773:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 8774:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 8775: 	# is a correct contruction space reference
 8776:         $location = $file;
 8777:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
 8778:         $location = $file;
 8779:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 8780:         my ($udom,$uname,$filename)=
 8781:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 8782:         my $home=&homeserver($uname,$udom);
 8783:         my $is_me=0;
 8784:         my @ids=&current_machine_ids();
 8785:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 8786:         if ($is_me) {
 8787:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
 8788:         } else {
 8789:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 8790:   	      $udom.'/'.$uname.'/'.$filename;
 8791:         }
 8792:     } elsif ($file =~ m-^/adm/-) {
 8793: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 8794:     } else {
 8795:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8796:         $file=~s:^/res/:/:;
 8797:         if ( !( $file =~ m:^/:) ) {
 8798:             $location = $dir. '/'.$file;
 8799:         } else {
 8800:             $location = '/home/httpd/html/res'.$file;
 8801:         }
 8802:     }
 8803:     $location=~s://+:/:g; # remove duplicate /
 8804:     while ($location=~m{/\.\./}) {
 8805: 	if ($location =~ m{/[^/]+/\.\./}) {
 8806: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 8807: 	} else {
 8808: 	    $location=~ s{/\.\./}{/}g;
 8809: 	}
 8810:     } #remove dir/..
 8811:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 8812:     return $location;
 8813: }
 8814: 
 8815: sub hreflocation {
 8816:     my ($dir,$file)=@_;
 8817:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
 8818: 	$file=filelocation($dir,$file);
 8819:     } elsif ($file=~m-^/adm/-) {
 8820: 	$file=~s-^/adm/wrapper/-/-;
 8821: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8822:     }
 8823:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 8824: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 8825:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 8826: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 8827:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 8828: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 8829: 	    -/uploaded/$1/$2/-x;
 8830:     }
 8831:     if ($file=~ m{^/userfiles/}) {
 8832: 	$file =~ s{^/userfiles/}{/uploaded/};
 8833:     }
 8834:     return $file;
 8835: }
 8836: 
 8837: sub current_machine_domains {
 8838:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 8839: }
 8840: 
 8841: sub machine_domains {
 8842:     my ($hostname) = @_;
 8843:     my @domains;
 8844:     my %hostname = &all_hostnames();
 8845:     while( my($id, $name) = each(%hostname)) {
 8846: #	&logthis("-$id-$name-$hostname-");
 8847: 	if ($hostname eq $name) {
 8848: 	    push(@domains,&host_domain($id));
 8849: 	}
 8850:     }
 8851:     return @domains;
 8852: }
 8853: 
 8854: sub current_machine_ids {
 8855:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 8856: }
 8857: 
 8858: sub machine_ids {
 8859:     my ($hostname) = @_;
 8860:     $hostname ||= &hostname($perlvar{'lonHostID'});
 8861:     my @ids;
 8862:     my %name_to_host = &all_names();
 8863:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 8864: 	return @{ $name_to_host{$hostname} };
 8865:     }
 8866:     return;
 8867: }
 8868: 
 8869: sub additional_machine_domains {
 8870:     my @domains;
 8871:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 8872:     while( my $line = <$fh>) {
 8873:         $line =~ s/\s//g;
 8874:         push(@domains,$line);
 8875:     }
 8876:     return @domains;
 8877: }
 8878: 
 8879: sub default_login_domain {
 8880:     my $domain = $perlvar{'lonDefDomain'};
 8881:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 8882:     foreach my $posdom (&current_machine_domains(),
 8883:                         &additional_machine_domains()) {
 8884:         if (lc($posdom) eq lc($testdomain)) {
 8885:             $domain=$posdom;
 8886:             last;
 8887:         }
 8888:     }
 8889:     return $domain;
 8890: }
 8891: 
 8892: # ------------------------------------------------------------- Declutters URLs
 8893: 
 8894: sub declutter {
 8895:     my $thisfn=shift;
 8896:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8897:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8898:     $thisfn=~s/^\///;
 8899:     $thisfn=~s|^adm/wrapper/||;
 8900:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 8901:     $thisfn=~s/^res\///;
 8902:     $thisfn=~s/\?.+$//;
 8903:     return $thisfn;
 8904: }
 8905: 
 8906: # ------------------------------------------------------------- Clutter up URLs
 8907: 
 8908: sub clutter {
 8909:     my $thisfn='/'.&declutter(shift);
 8910:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 8911: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 8912:        $thisfn='/res'.$thisfn; 
 8913:     }
 8914:     if ($thisfn !~m|/adm|) {
 8915: 	if ($thisfn =~ m|/ext/|) {
 8916: 	    $thisfn='/adm/wrapper'.$thisfn;
 8917: 	} else {
 8918: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 8919: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 8920: 	    if ($embstyle eq 'ssi'
 8921: 		|| ($embstyle eq 'hdn')
 8922: 		|| ($embstyle eq 'rat')
 8923: 		|| ($embstyle eq 'prv')
 8924: 		|| ($embstyle eq 'ign')) {
 8925: 		#do nothing with these
 8926: 	    } elsif (($embstyle eq 'img') 
 8927: 		|| ($embstyle eq 'emb')
 8928: 		|| ($embstyle eq 'wrp')) {
 8929: 		$thisfn='/adm/wrapper'.$thisfn;
 8930: 	    } elsif ($embstyle eq 'unk'
 8931: 		     && $thisfn!~/\.(sequence|page)$/) {
 8932: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 8933: 	    } else {
 8934: #		&logthis("Got a blank emb style");
 8935: 	    }
 8936: 	}
 8937:     }
 8938:     return $thisfn;
 8939: }
 8940: 
 8941: sub clutter_with_no_wrapper {
 8942:     my $uri = &clutter(shift);
 8943:     if ($uri =~ m-^/adm/-) {
 8944: 	$uri =~ s-^/adm/wrapper/-/-;
 8945: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 8946:     }
 8947:     return $uri;
 8948: }
 8949: 
 8950: sub freeze_escape {
 8951:     my ($value)=@_;
 8952:     if (ref($value)) {
 8953: 	$value=&nfreeze($value);
 8954: 	return '__FROZEN__'.&escape($value);
 8955:     }
 8956:     return &escape($value);
 8957: }
 8958: 
 8959: 
 8960: sub thaw_unescape {
 8961:     my ($value)=@_;
 8962:     if ($value =~ /^__FROZEN__/) {
 8963: 	substr($value,0,10,undef);
 8964: 	$value=&unescape($value);
 8965: 	return &thaw($value);
 8966:     }
 8967:     return &unescape($value);
 8968: }
 8969: 
 8970: sub correct_line_ends {
 8971:     my ($result)=@_;
 8972:     $$result =~s/\r\n/\n/mg;
 8973:     $$result =~s/\r/\n/mg;
 8974: }
 8975: # ================================================================ Main Program
 8976: 
 8977: sub goodbye {
 8978:    &logthis("Starting Shut down");
 8979: #not converted to using infrastruture and probably shouldn't be
 8980:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 8981: #converted
 8982: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 8983:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 8984: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 8985: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 8986: #1.1 only
 8987: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 8988: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 8989: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 8990: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 8991:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 8992:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 8993:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 8994:    &flushcourselogs();
 8995:    &logthis("Shutting down");
 8996: }
 8997: 
 8998: sub get_dns {
 8999:     my ($url,$func,$ignore_cache) = @_;
 9000:     if (!$ignore_cache) {
 9001: 	my ($content,$cached)=
 9002: 	    &Apache::lonnet::is_cached_new('dns',$url);
 9003: 	if ($cached) {
 9004: 	    &$func($content);
 9005: 	    return;
 9006: 	}
 9007:     }
 9008: 
 9009:     my %alldns;
 9010:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 9011:     foreach my $dns (<$config>) {
 9012: 	next if ($dns !~ /^\^(\S*)/x);
 9013:         my $line = $1;
 9014:         my ($host,$protocol) = split(/:/,$line);
 9015:         if ($protocol ne 'https') {
 9016:             $protocol = 'http';
 9017:         }
 9018: 	$alldns{$host} = $protocol;
 9019:     }
 9020:     while (%alldns) {
 9021: 	my ($dns) = keys(%alldns);
 9022: 	my $ua=new LWP::UserAgent;
 9023: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
 9024: 	my $response=$ua->request($request);
 9025:         delete($alldns{$dns});
 9026: 	next if ($response->is_error());
 9027: 	my @content = split("\n",$response->content);
 9028: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 9029: 	&$func(\@content);
 9030: 	return;
 9031:     }
 9032:     close($config);
 9033:     my $which = (split('/',$url))[3];
 9034:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 9035:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 9036:     my @content = <$config>;
 9037:     &$func(\@content);
 9038:     return;
 9039: }
 9040: # ------------------------------------------------------------ Read domain file
 9041: {
 9042:     my $loaded;
 9043:     my %domain;
 9044: 
 9045:     sub parse_domain_tab {
 9046: 	my ($lines) = @_;
 9047: 	foreach my $line (@$lines) {
 9048: 	    next if ($line =~ /^(\#|\s*$ )/x);
 9049: 
 9050: 	    chomp($line);
 9051: 	    my ($name,@elements) = split(/:/,$line,9);
 9052: 	    my %this_domain;
 9053: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 9054: 			       'lang_def', 'city', 'longi', 'lati',
 9055: 			       'primary') {
 9056: 		$this_domain{$field} = shift(@elements);
 9057: 	    }
 9058: 	    $domain{$name} = \%this_domain;
 9059: 	}
 9060:     }
 9061: 
 9062:     sub reset_domain_info {
 9063: 	undef($loaded);
 9064: 	undef(%domain);
 9065:     }
 9066: 
 9067:     sub load_domain_tab {
 9068: 	my ($ignore_cache) = @_;
 9069: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 9070: 	my $fh;
 9071: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 9072: 	    my @lines = <$fh>;
 9073: 	    &parse_domain_tab(\@lines);
 9074: 	}
 9075: 	close($fh);
 9076: 	$loaded = 1;
 9077:     }
 9078: 
 9079:     sub domain {
 9080: 	&load_domain_tab() if (!$loaded);
 9081: 
 9082: 	my ($name,$what) = @_;
 9083: 	return if ( !exists($domain{$name}) );
 9084: 
 9085: 	if (!$what) {
 9086: 	    return $domain{$name}{'description'};
 9087: 	}
 9088: 	return $domain{$name}{$what};
 9089:     }
 9090: 
 9091:     sub domain_info {
 9092:         &load_domain_tab() if (!$loaded);
 9093:         return %domain;
 9094:     }
 9095: 
 9096: }
 9097: 
 9098: 
 9099: # ------------------------------------------------------------- Read hosts file
 9100: {
 9101:     my %hostname;
 9102:     my %hostdom;
 9103:     my %libserv;
 9104:     my $loaded;
 9105:     my %name_to_host;
 9106: 
 9107:     sub parse_hosts_tab {
 9108: 	my ($file) = @_;
 9109: 	foreach my $configline (@$file) {
 9110: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 9111: 	    next if ($configline =~ /^\^/);
 9112: 	    chomp($configline);
 9113: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
 9114: 	    $name=~s/\s//g;
 9115: 	    if ($id && $domain && $role && $name) {
 9116: 		$hostname{$id}=$name;
 9117: 		push(@{$name_to_host{$name}}, $id);
 9118: 		$hostdom{$id}=$domain;
 9119: 		if ($role eq 'library') { $libserv{$id}=$name; }
 9120:                 if (defined($protocol)) {
 9121:                     if ($protocol eq 'https') {
 9122:                         $protocol{$id} = $protocol;
 9123:                     } else {
 9124:                         $protocol{$id} = 'http'; 
 9125:                     }
 9126:                 } else {
 9127:                     $protocol{$id} = 'http';
 9128:                 }
 9129: 	    }
 9130: 	}
 9131:     }
 9132:     
 9133:     sub reset_hosts_info {
 9134: 	&purge_remembered();
 9135: 	&reset_domain_info();
 9136: 	&reset_hosts_ip_info();
 9137: 	undef(%name_to_host);
 9138: 	undef(%hostname);
 9139: 	undef(%hostdom);
 9140: 	undef(%libserv);
 9141: 	undef($loaded);
 9142:     }
 9143: 
 9144:     sub load_hosts_tab {
 9145: 	my ($ignore_cache) = @_;
 9146: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 9147: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 9148: 	my @config = <$config>;
 9149: 	&parse_hosts_tab(\@config);
 9150: 	close($config);
 9151: 	$loaded=1;
 9152:     }
 9153: 
 9154:     sub hostname {
 9155: 	&load_hosts_tab() if (!$loaded);
 9156: 
 9157: 	my ($lonid) = @_;
 9158: 	return $hostname{$lonid};
 9159:     }
 9160: 
 9161:     sub all_hostnames {
 9162: 	&load_hosts_tab() if (!$loaded);
 9163: 
 9164: 	return %hostname;
 9165:     }
 9166: 
 9167:     sub all_names {
 9168: 	&load_hosts_tab() if (!$loaded);
 9169: 
 9170: 	return %name_to_host;
 9171:     }
 9172: 
 9173:     sub all_host_domain {
 9174:         &load_hosts_tab() if (!$loaded);
 9175:         return %hostdom;
 9176:     }
 9177: 
 9178:     sub is_library {
 9179: 	&load_hosts_tab() if (!$loaded);
 9180: 
 9181: 	return exists($libserv{$_[0]});
 9182:     }
 9183: 
 9184:     sub all_library {
 9185: 	&load_hosts_tab() if (!$loaded);
 9186: 
 9187: 	return %libserv;
 9188:     }
 9189: 
 9190:     sub get_servers {
 9191: 	&load_hosts_tab() if (!$loaded);
 9192: 
 9193: 	my ($domain,$type) = @_;
 9194: 	my %possible_hosts = ($type eq 'library') ? %libserv
 9195: 	                                          : %hostname;
 9196: 	my %result;
 9197: 	if (ref($domain) eq 'ARRAY') {
 9198: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9199: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 9200: 		    $result{$host} = $hostname;
 9201: 		}
 9202: 	    }
 9203: 	} else {
 9204: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9205: 		if ($hostdom{$host} eq $domain) {
 9206: 		    $result{$host} = $hostname;
 9207: 		}
 9208: 	    }
 9209: 	}
 9210: 	return %result;
 9211:     }
 9212: 
 9213:     sub host_domain {
 9214: 	&load_hosts_tab() if (!$loaded);
 9215: 
 9216: 	my ($lonid) = @_;
 9217: 	return $hostdom{$lonid};
 9218:     }
 9219: 
 9220:     sub all_domains {
 9221: 	&load_hosts_tab() if (!$loaded);
 9222: 
 9223: 	my %seen;
 9224: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 9225: 	return @uniq;
 9226:     }
 9227: }
 9228: 
 9229: { 
 9230:     my %iphost;
 9231:     my %name_to_ip;
 9232:     my %lonid_to_ip;
 9233: 
 9234:     sub get_hosts_from_ip {
 9235: 	my ($ip) = @_;
 9236: 	my %iphosts = &get_iphost();
 9237: 	if (ref($iphosts{$ip})) {
 9238: 	    return @{$iphosts{$ip}};
 9239: 	}
 9240: 	return;
 9241:     }
 9242:     
 9243:     sub reset_hosts_ip_info {
 9244: 	undef(%iphost);
 9245: 	undef(%name_to_ip);
 9246: 	undef(%lonid_to_ip);
 9247:     }
 9248: 
 9249:     sub get_host_ip {
 9250: 	my ($lonid) = @_;
 9251: 	if (exists($lonid_to_ip{$lonid})) {
 9252: 	    return $lonid_to_ip{$lonid};
 9253: 	}
 9254: 	my $name=&hostname($lonid);
 9255:    	my $ip = gethostbyname($name);
 9256: 	return if (!$ip || length($ip) ne 4);
 9257: 	$ip=inet_ntoa($ip);
 9258: 	$name_to_ip{$name}   = $ip;
 9259: 	$lonid_to_ip{$lonid} = $ip;
 9260: 	return $ip;
 9261:     }
 9262:     
 9263:     sub get_iphost {
 9264: 	my ($ignore_cache) = @_;
 9265: 
 9266: 	if (!$ignore_cache) {
 9267: 	    if (%iphost) {
 9268: 		return %iphost;
 9269: 	    }
 9270: 	    my ($ip_info,$cached)=
 9271: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 9272: 	    if ($cached) {
 9273: 		%iphost      = %{$ip_info->[0]};
 9274: 		%name_to_ip  = %{$ip_info->[1]};
 9275: 		%lonid_to_ip = %{$ip_info->[2]};
 9276: 		return %iphost;
 9277: 	    }
 9278: 	}
 9279: 
 9280: 	# get yesterday's info for fallback
 9281: 	my %old_name_to_ip;
 9282: 	my ($ip_info,$cached)=
 9283: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 9284: 	if ($cached) {
 9285: 	    %old_name_to_ip = %{$ip_info->[1]};
 9286: 	}
 9287: 
 9288: 	my %name_to_host = &all_names();
 9289: 	foreach my $name (keys(%name_to_host)) {
 9290: 	    my $ip;
 9291: 	    if (!exists($name_to_ip{$name})) {
 9292: 		$ip = gethostbyname($name);
 9293: 		if (!$ip || length($ip) ne 4) {
 9294: 		    if (defined($old_name_to_ip{$name})) {
 9295: 			$ip = $old_name_to_ip{$name};
 9296: 			&logthis("Can't find $name defaulting to old $ip");
 9297: 		    } else {
 9298: 			&logthis("Name $name no IP found");
 9299: 			next;
 9300: 		    }
 9301: 		} else {
 9302: 		    $ip=inet_ntoa($ip);
 9303: 		}
 9304: 		$name_to_ip{$name} = $ip;
 9305: 	    } else {
 9306: 		$ip = $name_to_ip{$name};
 9307: 	    }
 9308: 	    foreach my $id (@{ $name_to_host{$name} }) {
 9309: 		$lonid_to_ip{$id} = $ip;
 9310: 	    }
 9311: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 9312: 	}
 9313: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 9314: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 9315: 				      48*60*60);
 9316: 
 9317: 	return %iphost;
 9318:     }
 9319: 
 9320:     #
 9321:     #  Given a DNS returns the loncapa host name for that DNS 
 9322:     # 
 9323:     sub host_from_dns {
 9324:         my ($dns) = @_;
 9325:         my @hosts;
 9326:         my $ip;
 9327: 
 9328:         if (exists($name_to_ip{$dns})) {
 9329:             $ip = $name_to_ip{$dns};
 9330:         }
 9331:         if (!$ip) {
 9332:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
 9333:             if (length($ip) == 4) { 
 9334: 	        $ip   = &IO::Socket::inet_ntoa($ip);
 9335:             }
 9336:         }
 9337:         if ($ip) {
 9338: 	    @hosts = get_hosts_from_ip($ip);
 9339: 	    return $hosts[0];
 9340:         }
 9341:         return undef;
 9342:     }
 9343: 
 9344: }
 9345: 
 9346: BEGIN {
 9347: 
 9348: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 9349:     unless ($readit) {
 9350: {
 9351:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 9352:     %perlvar = (%perlvar,%{$configvars});
 9353: }
 9354: 
 9355: 
 9356: # ------------------------------------------------------ Read spare server file
 9357: {
 9358:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 9359: 
 9360:     while (my $configline=<$config>) {
 9361:        chomp($configline);
 9362:        if ($configline) {
 9363: 	   my ($host,$type) = split(':',$configline,2);
 9364: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 9365: 	   push(@{ $spareid{$type} }, $host);
 9366:        }
 9367:     }
 9368:     close($config);
 9369: }
 9370: # ------------------------------------------------------------ Read permissions
 9371: {
 9372:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 9373: 
 9374:     while (my $configline=<$config>) {
 9375: 	chomp($configline);
 9376: 	if ($configline) {
 9377: 	    my ($role,$perm)=split(/ /,$configline);
 9378: 	    if ($perm ne '') { $pr{$role}=$perm; }
 9379: 	}
 9380:     }
 9381:     close($config);
 9382: }
 9383: 
 9384: # -------------------------------------------- Read plain texts for permissions
 9385: {
 9386:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 9387: 
 9388:     while (my $configline=<$config>) {
 9389: 	chomp($configline);
 9390: 	if ($configline) {
 9391: 	    my ($short,@plain)=split(/:/,$configline);
 9392:             %{$prp{$short}} = ();
 9393: 	    if (@plain > 0) {
 9394:                 $prp{$short}{'std'} = $plain[0];
 9395:                 for (my $i=1; $i<@plain; $i++) {
 9396:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 9397:                 }
 9398:             }
 9399: 	}
 9400:     }
 9401:     close($config);
 9402: }
 9403: 
 9404: # ---------------------------------------------------------- Read package table
 9405: {
 9406:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 9407: 
 9408:     while (my $configline=<$config>) {
 9409: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 9410: 	chomp($configline);
 9411: 	my ($short,$plain)=split(/:/,$configline);
 9412: 	my ($pack,$name)=split(/\&/,$short);
 9413: 	if ($plain ne '') {
 9414: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 9415: 	    $packagetab{$short}=$plain; 
 9416: 	}
 9417:     }
 9418:     close($config);
 9419: }
 9420: 
 9421: # ------------- set up temporary directory
 9422: {
 9423:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 9424: 
 9425: }
 9426: 
 9427: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 9428: 				'compress_threshold'=> 20_000,
 9429:  			        });
 9430: 
 9431: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 9432: $dumpcount=0;
 9433: $locknum=0;
 9434: 
 9435: &logtouch();
 9436: &logthis('<font color="yellow">INFO: Read configuration</font>');
 9437: $readit=1;
 9438:     {
 9439: 	use integer;
 9440: 	my $test=(2**32)+1;
 9441: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 9442: 	&logthis(" Detected 64bit platform ($_64bit)");
 9443:     }
 9444: }
 9445: }
 9446: 
 9447: 1;
 9448: __END__
 9449: 
 9450: =pod
 9451: 
 9452: =head1 NAME
 9453: 
 9454: Apache::lonnet - Subroutines to ask questions about things in the network.
 9455: 
 9456: =head1 SYNOPSIS
 9457: 
 9458: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 9459: 
 9460:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 9461: 
 9462: Common parameters:
 9463: 
 9464: =over 4
 9465: 
 9466: =item *
 9467: 
 9468: $uname : an internal username (if $cname expecting a course Id specifically)
 9469: 
 9470: =item *
 9471: 
 9472: $udom : a domain (if $cdom expecting a course's domain specifically)
 9473: 
 9474: =item *
 9475: 
 9476: $symb : a resource instance identifier
 9477: 
 9478: =item *
 9479: 
 9480: $namespace : the name of a .db file that contains the data needed or
 9481: being set.
 9482: 
 9483: =back
 9484: 
 9485: =head1 OVERVIEW
 9486: 
 9487: lonnet provides subroutines which interact with the
 9488: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 9489: about classes, users, and resources.
 9490: 
 9491: For many of these objects you can also use this to store data about
 9492: them or modify them in various ways.
 9493: 
 9494: =head2 Symbs
 9495: 
 9496: To identify a specific instance of a resource, LON-CAPA uses symbols
 9497: or "symbs"X<symb>. These identifiers are built from the URL of the
 9498: map, the resource number of the resource in the map, and the URL of
 9499: the resource itself. The latter is somewhat redundant, but might help
 9500: if maps change.
 9501: 
 9502: An example is
 9503: 
 9504:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 9505: 
 9506: The respective map entry is
 9507: 
 9508:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 9509:   title="Problem 2">
 9510:  </resource>
 9511: 
 9512: Symbs are used by the random number generator, as well as to store and
 9513: restore data specific to a certain instance of for example a problem.
 9514: 
 9515: =head2 Storing And Retrieving Data
 9516: 
 9517: X<store()>X<cstore()>X<restore()>Three of the most important functions
 9518: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 9519: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 9520: is is the non-critical message twin of cstore. These functions are for
 9521: handlers to store a perl hash to a user's permanent data space in an
 9522: easy manner, and to retrieve it again on another call. It is expected
 9523: that a handler would use this once at the beginning to retrieve data,
 9524: and then again once at the end to send only the new data back.
 9525: 
 9526: The data is stored in the user's data directory on the user's
 9527: homeserver under the ID of the course.
 9528: 
 9529: The hash that is returned by restore will have all of the previous
 9530: value for all of the elements of the hash.
 9531: 
 9532: Example:
 9533: 
 9534:  #creating a hash
 9535:  my %hash;
 9536:  $hash{'foo'}='bar';
 9537: 
 9538:  #storing it
 9539:  &Apache::lonnet::cstore(\%hash);
 9540: 
 9541:  #changing a value
 9542:  $hash{'foo'}='notbar';
 9543: 
 9544:  #adding a new value
 9545:  $hash{'bar'}='foo';
 9546:  &Apache::lonnet::cstore(\%hash);
 9547: 
 9548:  #retrieving the hash
 9549:  my %history=&Apache::lonnet::restore();
 9550: 
 9551:  #print the hash
 9552:  foreach my $key (sort(keys(%history))) {
 9553:    print("\%history{$key} = $history{$key}");
 9554:  }
 9555: 
 9556: Will print out:
 9557: 
 9558:  %history{1:foo} = bar
 9559:  %history{1:keys} = foo:timestamp
 9560:  %history{1:timestamp} = 990455579
 9561:  %history{2:bar} = foo
 9562:  %history{2:foo} = notbar
 9563:  %history{2:keys} = foo:bar:timestamp
 9564:  %history{2:timestamp} = 990455580
 9565:  %history{bar} = foo
 9566:  %history{foo} = notbar
 9567:  %history{timestamp} = 990455580
 9568:  %history{version} = 2
 9569: 
 9570: Note that the special hash entries C<keys>, C<version> and
 9571: C<timestamp> were added to the hash. C<version> will be equal to the
 9572: total number of versions of the data that have been stored. The
 9573: C<timestamp> attribute will be the UNIX time the hash was
 9574: stored. C<keys> is available in every historical section to list which
 9575: keys were added or changed at a specific historical revision of a
 9576: hash.
 9577: 
 9578: B<Warning>: do not store the hash that restore returns directly. This
 9579: will cause a mess since it will restore the historical keys as if the
 9580: were new keys. I.E. 1:foo will become 1:1:foo etc.
 9581: 
 9582: Calling convention:
 9583: 
 9584:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 9585:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 9586: 
 9587: For more detailed information, see lonnet specific documentation.
 9588: 
 9589: =head1 RETURN MESSAGES
 9590: 
 9591: =over 4
 9592: 
 9593: =item * B<con_lost>: unable to contact remote host
 9594: 
 9595: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 9596: when the connection is brought back up
 9597: 
 9598: =item * B<con_failed>: unable to contact remote host and unable to save message
 9599: for later delivery
 9600: 
 9601: =item * B<error:>: an error a occurred, a description of the error follows the :
 9602: 
 9603: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 9604: that was requested
 9605: 
 9606: =back
 9607: 
 9608: =head1 PUBLIC SUBROUTINES
 9609: 
 9610: =head2 Session Environment Functions
 9611: 
 9612: =over 4
 9613: 
 9614: =item * 
 9615: X<appenv()>
 9616: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
 9617: the user envirnoment file, and will be restored for each access this
 9618: user makes during this session, also modifies the %env for the current
 9619: process. Optional rolesarrayref - if defined contains a reference to an array
 9620: of roles which are exempt from the restriction on modifying user.role entries 
 9621: in the user's environment.db and in %env.    
 9622: 
 9623: =item *
 9624: X<delenv()>
 9625: B<delenv($delthis,$regexp)>: removes all items from the session
 9626: environment file that begin with $delthis. If the 
 9627: optional second arg - $regexp - is true, $delthis is treated as a 
 9628: regular expression, otherwise \Q$delthis\E is used. 
 9629: The values are also deleted from the current processes %env.
 9630: 
 9631: =item * get_env_multiple($name) 
 9632: 
 9633: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9634: values may be defined and end up as an array ref.
 9635: 
 9636: returns an array of values
 9637: 
 9638: =back
 9639: 
 9640: =head2 User Information
 9641: 
 9642: =over 4
 9643: 
 9644: =item *
 9645: X<queryauthenticate()>
 9646: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 9647: authentication scheme
 9648: 
 9649: =item *
 9650: X<authenticate()>
 9651: B<authenticate($uname,$upass,$udom)>: try to
 9652: authenticate user from domain's lib servers (first use the current
 9653: one). C<$upass> should be the users password.
 9654: 
 9655: =item *
 9656: X<homeserver()>
 9657: B<homeserver($uname,$udom)>: find the server which has
 9658: the user's directory and files (there must be only one), this caches
 9659: the answer, and also caches if there is a borken connection.
 9660: 
 9661: =item *
 9662: X<idget()>
 9663: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 9664: (IDs are a unique resource in a domain, there must be only 1 ID per
 9665: username, and only 1 username per ID in a specific domain) (returns
 9666: hash: id=>name,id=>name)
 9667: 
 9668: =item *
 9669: X<idrget()>
 9670: B<idrget($udom,@unames)>: find the IDs behind a list of
 9671: usernames (returns hash: name=>id,name=>id)
 9672: 
 9673: =item *
 9674: X<idput()>
 9675: B<idput($udom,%ids)>: store away a list of names and associated IDs
 9676: 
 9677: =item *
 9678: X<rolesinit()>
 9679: B<rolesinit($udom,$username,$authhost)>: get user privileges
 9680: 
 9681: =item *
 9682: X<getsection()>
 9683: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 9684: course $cname, return section name/number or '' for "not in course"
 9685: and '-1' for "no section"
 9686: 
 9687: =item *
 9688: X<userenvironment()>
 9689: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 9690: passed in @what from the requested user's environment, returns a hash
 9691: 
 9692: =item * 
 9693: X<userlog_query()>
 9694: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 9695: activity.log file. %filters defines filters applied when parsing the
 9696: log file. These can be start or end timestamps, or the type of action
 9697: - log to look for Login or Logout events, check for Checkin or
 9698: Checkout, role for role selection. The response is in the form
 9699: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 9700: escaped strings of the action recorded in the activity.log file.
 9701: 
 9702: =back
 9703: 
 9704: =head2 User Roles
 9705: 
 9706: =over 4
 9707: 
 9708: =item *
 9709: 
 9710: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 9711:  F: full access
 9712:  U,I,K: authentication modes (cxx only)
 9713:  '': forbidden
 9714:  1: user needs to choose course
 9715:  2: browse allowed
 9716:  A: passphrase authentication needed
 9717: 
 9718: =item *
 9719: 
 9720: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 9721: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 9722: and course level
 9723: 
 9724: =item *
 9725: 
 9726: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
 9727: (rolesplain.tab); plain text explanation of a user role term.
 9728: $type is Course (default) or Community.
 9729: If $forcedefault evaluates to true, text returned will be default 
 9730: text for $type. Otherwise, if this is a course, the text returned 
 9731: will be a custom name for the role (if defined in the course's 
 9732: environment).  If no custom name is defined the default is returned.
 9733:    
 9734: =item *
 9735: 
 9736: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
 9737: All arguments are optional. Returns a hash of a roles, either for
 9738: co-author/assistant author roles for a user's Construction Space
 9739: (default), or if $context is 'userroles', roles for the user himself,
 9740: In the hash, keys are set to colon-separated $uname,$udom,$role, and
 9741: (optionally) if $withsec is true, a fourth colon-separated item - $section.
 9742: For each key, value is set to colon-separated start and end times for
 9743: the role.  If no username and domain are specified, will default to
 9744: current user/domain. Types, roles, and roledoms are references to arrays
 9745: of role statuses (active, future or previous), roles 
 9746: (e.g., cc,in, st etc.) and domains of the roles which can be used
 9747: to restrict the list of roles reported. If no array ref is 
 9748: provided for types, will default to return only active roles.
 9749: 
 9750: =back
 9751: 
 9752: =head2 User Modification
 9753: 
 9754: =over 4
 9755: 
 9756: =item *
 9757: 
 9758: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
 9759: user for the level given by URL.  Optional start and end dates (leave empty
 9760: string or zero for "no date")
 9761: 
 9762: =item *
 9763: 
 9764: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 9765: change a users, password, possible return values are: ok,
 9766: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 9767: refused
 9768: 
 9769: =item *
 9770: 
 9771: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 9772: 
 9773: =item *
 9774: 
 9775: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
 9776:            $forceid,$desiredhome,$email,$inststatus) : 
 9777: modify user
 9778: 
 9779: =item *
 9780: 
 9781: modifystudent
 9782: 
 9783: modify a student's enrollment and identification information.
 9784: The course id is resolved based on the current users environment.  
 9785: This means the envoking user must be a course coordinator or otherwise
 9786: associated with a course.
 9787: 
 9788: This call is essentially a wrapper for lonnet::modifyuser and
 9789: lonnet::modify_student_enrollment
 9790: 
 9791: Inputs: 
 9792: 
 9793: =over 4
 9794: 
 9795: =item B<$udom> Student's loncapa domain
 9796: 
 9797: =item B<$uname> Student's loncapa login name
 9798: 
 9799: =item B<$uid> Student/Employee ID
 9800: 
 9801: =item B<$umode> Student's authentication mode
 9802: 
 9803: =item B<$upass> Student's password
 9804: 
 9805: =item B<$first> Student's first name
 9806: 
 9807: =item B<$middle> Student's middle name
 9808: 
 9809: =item B<$last> Student's last name
 9810: 
 9811: =item B<$gene> Student's generation
 9812: 
 9813: =item B<$usec> Student's section in course
 9814: 
 9815: =item B<$end> Unix time of the roles expiration
 9816: 
 9817: =item B<$start> Unix time of the roles start date
 9818: 
 9819: =item B<$forceid> If defined, allow $uid to be changed
 9820: 
 9821: =item B<$desiredhome> server to use as home server for student
 9822: 
 9823: =item B<$email> Student's permanent e-mail address
 9824: 
 9825: =item B<$type> Type of enrollment (auto or manual)
 9826: 
 9827: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
 9828: 
 9829: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
 9830: 
 9831: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
 9832: 
 9833: =item B<$context> role change context (shown in User Management Logs display in a course)
 9834: 
 9835: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
 9836: 
 9837: =back
 9838: 
 9839: =item *
 9840: 
 9841: modify_student_enrollment
 9842: 
 9843: Change a students enrollment status in a class.  The environment variable
 9844: 'role.request.course' must be defined for this function to proceed.
 9845: 
 9846: Inputs:
 9847: 
 9848: =over 4
 9849: 
 9850: =item $udom, students domain
 9851: 
 9852: =item $uname, students name
 9853: 
 9854: =item $uid, students user id
 9855: 
 9856: =item $first, students first name
 9857: 
 9858: =item $middle
 9859: 
 9860: =item $last
 9861: 
 9862: =item $gene
 9863: 
 9864: =item $usec
 9865: 
 9866: =item $end
 9867: 
 9868: =item $start
 9869: 
 9870: =item $type
 9871: 
 9872: =item $locktype
 9873: 
 9874: =item $cid
 9875: 
 9876: =item $selfenroll
 9877: 
 9878: =item $context
 9879: 
 9880: =back
 9881: 
 9882: 
 9883: =item *
 9884: 
 9885: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 9886: custom role; give a custom role to a user for the level given by URL.  Specify
 9887: name and domain of role author, and role name
 9888: 
 9889: =item *
 9890: 
 9891: revokerole($udom,$uname,$url,$role) : revoke a role for url
 9892: 
 9893: =item *
 9894: 
 9895: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 9896: 
 9897: =back
 9898: 
 9899: =head2 Course Infomation
 9900: 
 9901: =over 4
 9902: 
 9903: =item *
 9904: 
 9905: coursedescription($courseid) : returns a hash of information about the
 9906: specified course id, including all environment settings for the
 9907: course, the description of the course will be in the hash under the
 9908: key 'description'
 9909: 
 9910: =item *
 9911: 
 9912: resdata($name,$domain,$type,@which) : request for current parameter
 9913: setting for a specific $type, where $type is either 'course' or 'user',
 9914: @what should be a list of parameters to ask about. This routine caches
 9915: answers for 5 minutes.
 9916: 
 9917: =item *
 9918: 
 9919: get_courseresdata($courseid, $domain) : dump the entire course resource
 9920: data base, returning a hash that is keyed by the resource name and has
 9921: values that are the resource value.  I believe that the timestamps and
 9922: versions are also returned.
 9923: 
 9924: 
 9925: =back
 9926: 
 9927: =head2 Course Modification
 9928: 
 9929: =over 4
 9930: 
 9931: =item *
 9932: 
 9933: writecoursepref($courseid,%prefs) : write preferences (environment
 9934: database) for a course
 9935: 
 9936: =item *
 9937: 
 9938: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
 9939: 
 9940: =item *
 9941: 
 9942: generate_coursenum($udom) : get a unique (unused) course number in domain $udom
 9943: 
 9944: =back
 9945: 
 9946: =head2 Resource Subroutines
 9947: 
 9948: =over 4
 9949: 
 9950: =item *
 9951: 
 9952: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 9953: 
 9954: =item *
 9955: 
 9956: repcopy($filename) : subscribes to the requested file, and attempts to
 9957: replicate from the owning library server, Might return
 9958: 'unavailable', 'not_found', 'forbidden', 'ok', or
 9959: 'bad_request', also attempts to grab the metadata for the
 9960: resource. Expects the local filesystem pathname
 9961: (/home/httpd/html/res/....)
 9962: 
 9963: =back
 9964: 
 9965: =head2 Resource Information
 9966: 
 9967: =over 4
 9968: 
 9969: =item *
 9970: 
 9971: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 9972: a vairety of different possible values, $varname should be a request
 9973: string, and the other parameters can be used to specify who and what
 9974: one is asking about.
 9975: 
 9976: Possible values for $varname are environment.lastname (or other item
 9977: from the envirnment hash), user.name (or someother aspect about the
 9978: user), resource.0.maxtries (or some other part and parameter of a
 9979: resource)
 9980: 
 9981: =item *
 9982: 
 9983: directcondval($number) : get current value of a condition; reads from a state
 9984: string
 9985: 
 9986: =item *
 9987: 
 9988: condval($condidx) : value of condition index based on state
 9989: 
 9990: =item *
 9991: 
 9992: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 9993: resource's metadata, $what should be either a specific key, or either
 9994: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 9995: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 9996: 
 9997: this function automatically caches all requests
 9998: 
 9999: =item *
10000: 
10001: metadata_query($query,$custom,$customshow) : make a metadata query against the
10002: network of library servers; returns file handle of where SQL and regex results
10003: will be stored for query
10004: 
10005: =item *
10006: 
10007: symbread($filename) : return symbolic list entry (filename argument optional);
10008: returns the data handle
10009: 
10010: =item *
10011: 
10012: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
10013: a possible symb for the URL in $thisfn, and if is an encryypted
10014: resource that the user accessed using /enc/ returns a 1 on success, 0
10015: on failure, user must be in a course, as it assumes the existance of
10016: the course initial hash, and uses $env('request.course.id'}
10017: 
10018: 
10019: =item *
10020: 
10021: symbclean($symb) : removes versions numbers from a symb, returns the
10022: cleaned symb
10023: 
10024: =item *
10025: 
10026: is_on_map($uri) : checks if the $uri is somewhere on the current
10027: course map, user must be in a course for it to work.
10028: 
10029: =item *
10030: 
10031: numval($salt) : return random seed value (addend for rndseed)
10032: 
10033: =item *
10034: 
10035: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10036: a random seed, all arguments are optional, if they aren't sent it uses the
10037: environment to derive them. Note: if symb isn't sent and it can't get one
10038: from &symbread it will use the current time as its return value
10039: 
10040: =item *
10041: 
10042: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10043: unfakeable, receipt
10044: 
10045: =item *
10046: 
10047: receipt() : API to ireceipt working off of env values; given out to users
10048: 
10049: =item *
10050: 
10051: countacc($url) : count the number of accesses to a given URL
10052: 
10053: =item *
10054: 
10055: 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
10056: 
10057: =item *
10058: 
10059: 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)
10060: 
10061: =item *
10062: 
10063: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
10064: 
10065: =item *
10066: 
10067: devalidate($symb) : devalidate temporary spreadsheet calculations,
10068: forcing spreadsheet to reevaluate the resource scores next time.
10069: 
10070: =back
10071: 
10072: =head2 Storing/Retreiving Data
10073: 
10074: =over 4
10075: 
10076: =item *
10077: 
10078: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
10079: for this url; hashref needs to be given and should be a \%hashname; the
10080: remaining args aren't required and if they aren't passed or are '' they will
10081: be derived from the env
10082: 
10083: =item *
10084: 
10085: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
10086: uses critical subroutine
10087: 
10088: =item *
10089: 
10090: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
10091: all args are optional
10092: 
10093: =item *
10094: 
10095: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
10096: dumps the complete (or key matching regexp) namespace into a hash
10097: ($udom, $uname, $regexp, $range are optional) for a namespace that is
10098: normally &store()ed into
10099: 
10100: $range should be either an integer '100' (give me the first 100
10101:                                            matching records)
10102:               or be  two integers sperated by a - with no spaces
10103:                  '30-50' (give me the 30th through the 50th matching
10104:                           records)
10105: 
10106: 
10107: =item *
10108: 
10109: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
10110: replaces a &store() version of data with a replacement set of data
10111: for a particular resource in a namespace passed in the $storehash hash 
10112: reference
10113: 
10114: =item *
10115: 
10116: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
10117: works very similar to store/cstore, but all data is stored in a
10118: temporary location and can be reset using tmpreset, $storehash should
10119: be a hash reference, returns nothing on success
10120: 
10121: =item *
10122: 
10123: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
10124: similar to restore, but all data is stored in a temporary location and
10125: can be reset using tmpreset. Returns a hash of values on success,
10126: error string otherwise.
10127: 
10128: =item *
10129: 
10130: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
10131: deltes all keys for $symb form the temporary storage hash.
10132: 
10133: =item *
10134: 
10135: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10136: reference filled in from namesp ($udom and $uname are optional)
10137: 
10138: =item *
10139: 
10140: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
10141: namesp ($udom and $uname are optional)
10142: 
10143: =item *
10144: 
10145: dump($namespace,$udom,$uname,$regexp,$range) : 
10146: dumps the complete (or key matching regexp) namespace into a hash
10147: ($udom, $uname, $regexp, $range are optional)
10148: 
10149: $range should be either an integer '100' (give me the first 100
10150:                                            matching records)
10151:               or be  two integers sperated by a - with no spaces
10152:                  '30-50' (give me the 30th through the 50th matching
10153:                           records)
10154: =item *
10155: 
10156: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
10157: $store can be a scalar, an array reference, or if the amount to be 
10158: incremented is > 1, a hash reference.
10159: 
10160: ($udom and $uname are optional)
10161: 
10162: =item *
10163: 
10164: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
10165: ($udom and $uname are optional)
10166: 
10167: =item *
10168: 
10169: cput($namespace,$storehash,$udom,$uname) : critical put
10170: ($udom and $uname are optional)
10171: 
10172: =item *
10173: 
10174: newput($namespace,$storehash,$udom,$uname) :
10175: 
10176: Attempts to store the items in the $storehash, but only if they don't
10177: currently exist, if this succeeds you can be certain that you have 
10178: successfully created a new key value pair in the $namespace db.
10179: 
10180: 
10181: Args:
10182:  $namespace: name of database to store values to
10183:  $storehash: hashref to store to the db
10184:  $udom: (optional) domain of user containing the db
10185:  $uname: (optional) name of user caontaining the db
10186: 
10187: Returns:
10188:  'ok' -> succeeded in storing all keys of $storehash
10189:  'key_exists: <key>' -> failed to anything out of $storehash, as at
10190:                         least <key> already existed in the db (other
10191:                         requested keys may also already exist)
10192:  'error: <msg>' -> unable to tie the DB or other error occurred
10193:  'con_lost' -> unable to contact request server
10194:  'refused' -> action was not allowed by remote machine
10195: 
10196: 
10197: =item *
10198: 
10199: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10200: reference filled in from namesp (encrypts the return communication)
10201: ($udom and $uname are optional)
10202: 
10203: =item *
10204: 
10205: log($udom,$name,$home,$message) : write to permanent log for user; use
10206: critical subroutine
10207: 
10208: =item *
10209: 
10210: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
10211: array reference filled in from namespace found in domain level on either
10212: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
10213: 
10214: =item *
10215: 
10216: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
10217: domain level either on specified domain server ($uhome) or primary domain 
10218: server ($udom and $uhome are optional)
10219: 
10220: =item * 
10221: 
10222: get_domain_defaults($target_domain) : returns hash with defaults for
10223: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
10224: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
10225: or localauth), initial password or a kerberos realm, language (e.g., en-us).
10226: Values are retrieved from cache (if current), or from domain's configuration.db
10227: (if available), or lastly from values in lonTabs/dns_domain,tab, 
10228: or lonTabs/domain.tab. 
10229: 
10230: %domdefaults = &get_auth_defaults($target_domain);
10231: 
10232: =back
10233: 
10234: =head2 Network Status Functions
10235: 
10236: =over 4
10237: 
10238: =item *
10239: 
10240: dirlist($uri) : return directory list based on URI
10241: 
10242: =item *
10243: 
10244: spareserver() : find server with least workload from spare.tab
10245: 
10246: 
10247: =item *
10248: 
10249: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
10250: if there is no corresponding loncapa host.
10251: 
10252: =back
10253: 
10254: 
10255: =head2 Apache Request
10256: 
10257: =over 4
10258: 
10259: =item *
10260: 
10261: ssi($url,%hash) : server side include, does a complete request cycle on url to
10262: localhost, posts hash
10263: 
10264: =back
10265: 
10266: =head2 Data to String to Data
10267: 
10268: =over 4
10269: 
10270: =item *
10271: 
10272: hash2str(%hash) : convert a hash into a string complete with escaping and '='
10273: and '&' separators, supports elements that are arrayrefs and hashrefs
10274: 
10275: =item *
10276: 
10277: hashref2str($hashref) : convert a hashref into a string complete with
10278: escaping and '=' and '&' separators, supports elements that are
10279: arrayrefs and hashrefs
10280: 
10281: =item *
10282: 
10283: arrayref2str($arrayref) : convert an arrayref into a string complete
10284: with escaping and '&' separators, supports elements that are arrayrefs
10285: and hashrefs
10286: 
10287: =item *
10288: 
10289: str2hash($string) : convert string to hash using unescaping and
10290: splitting on '=' and '&', supports elements that are arrayrefs and
10291: hashrefs
10292: 
10293: =item *
10294: 
10295: str2array($string) : convert string to hash using unescaping and
10296: splitting on '&', supports elements that are arrayrefs and hashrefs
10297: 
10298: =back
10299: 
10300: =head2 Logging Routines
10301: 
10302: =over 4
10303: 
10304: These routines allow one to make log messages in the lonnet.log and
10305: lonnet.perm logfiles.
10306: 
10307: =item *
10308: 
10309: logtouch() : make sure the logfile, lonnet.log, exists
10310: 
10311: =item *
10312: 
10313: logthis() : append message to the normal lonnet.log file, it gets
10314: preiodically rolled over and deleted.
10315: 
10316: =item *
10317: 
10318: logperm() : append a permanent message to lonnet.perm.log, this log
10319: file never gets deleted by any automated portion of the system, only
10320: messages of critical importance should go in here.
10321: 
10322: =back
10323: 
10324: =head2 General File Helper Routines
10325: 
10326: =over 4
10327: 
10328: =item *
10329: 
10330: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10331: (a) files in /uploaded
10332:   (i) If a local copy of the file exists - 
10333:       compares modification date of local copy with last-modified date for 
10334:       definitive version stored on home server for course. If local copy is 
10335:       stale, requests a new version from the home server and stores it. 
10336:       If the original has been removed from the home server, then local copy 
10337:       is unlinked.
10338:   (ii) If local copy does not exist -
10339:       requests the file from the home server and stores it. 
10340:   
10341:   If $caller is 'uploadrep':  
10342:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10343:     for request for files originally uploaded via DOCS. 
10344:      - returns 'ok' if fresh local copy now available, -1 otherwise.
10345:   
10346:   Otherwise:
10347:      This indicates a call from the content generation phase of the request.
10348:      -  returns the entire contents of the file or -1.
10349:      
10350: (b) files in /res
10351:    - returns the entire contents of a file or -1; 
10352:    it properly subscribes to and replicates the file if neccessary.
10353: 
10354: 
10355: =item *
10356: 
10357: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10358:                   reference
10359: 
10360: returns either a stat() list of data about the file or an empty list
10361: if the file doesn't exist or couldn't find out about it (connection
10362: problems or user unknown)
10363: 
10364: =item *
10365: 
10366: filelocation($dir,$file) : returns file system location of a file
10367: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10368: directory that relative $file lookups are to looked in ($dir of /a/dir
10369: and a file of ../bob will become /a/bob)
10370: 
10371: =item *
10372: 
10373: hreflocation($dir,$file) : returns file system location or a URL; same as
10374: filelocation except for hrefs
10375: 
10376: =item *
10377: 
10378: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10379: 
10380: =back
10381: 
10382: =head2 Usererfile file routines (/uploaded*)
10383: 
10384: =over 4
10385: 
10386: =item *
10387: 
10388: userfileupload(): main rotine for putting a file in a user or course's
10389:                   filespace, arguments are,
10390: 
10391:  formname - required - this is the name of the element in $env where the
10392:            filename, and the contents of the file to create/modifed exist
10393:            the filename is in $env{'form.'.$formname.'.filename'} and the
10394:            contents of the file is located in $env{'form.'.$formname}
10395:  coursedoc - if true, store the file in the course of the active role
10396:              of the current user
10397:  subdir - required - subdirectory to put the file in under ../userfiles/
10398:          if undefined, it will be placed in "unknown"
10399: 
10400:  (This routine calls clean_filename() to remove any dangerous
10401:  characters from the filename, and then calls finuserfileupload() to
10402:  complete the transaction)
10403: 
10404:  returns either the url of the uploaded file (/uploaded/....) if successful
10405:  and /adm/notfound.html if unsuccessful
10406: 
10407: =item *
10408: 
10409: clean_filename(): routine for cleaing a filename up for storage in
10410:                  userfile space, argument is:
10411: 
10412:  filename - proposed filename
10413: 
10414: returns: the new clean filename
10415: 
10416: =item *
10417: 
10418: finishuserfileupload(): routine that creaes and sends the file to
10419: userspace, probably shouldn't be called directly
10420: 
10421:   docuname: username or courseid of destination for the file
10422:   docudom: domain of user/course of destination for the file
10423:   formname: same as for userfileupload()
10424:   fname: filename (inculding subdirectories) for the file
10425: 
10426:  returns either the url of the uploaded file (/uploaded/....) if successful
10427:  and /adm/notfound.html if unsuccessful
10428: 
10429: =item *
10430: 
10431: renameuserfile(): renames an existing userfile to a new name
10432: 
10433:   Args:
10434:    docuname: username or courseid of destination for the file
10435:    docudom: domain of user/course of destination for the file
10436:    old: current file name (including any subdirs under userfiles)
10437:    new: desired file name (including any subdirs under userfiles)
10438: 
10439: =item *
10440: 
10441: mkdiruserfile(): creates a directory is a userfiles dir
10442: 
10443:   Args:
10444:    docuname: username or courseid of destination for the file
10445:    docudom: domain of user/course of destination for the file
10446:    dir: dir to create (including any subdirs under userfiles)
10447: 
10448: =item *
10449: 
10450: removeuserfile(): removes a file that exists in userfiles
10451: 
10452:   Args:
10453:    docuname: username or courseid of destination for the file
10454:    docudom: domain of user/course of destination for the file
10455:    fname: filname to delete (including any subdirs under userfiles)
10456: 
10457: =item *
10458: 
10459: removeuploadedurl(): convience function for removeuserfile()
10460: 
10461:   Args:
10462:    url:  a full /uploaded/... url to delete
10463: 
10464: =item * 
10465: 
10466: get_portfile_permissions():
10467:   Args:
10468:     domain: domain of user or course contain the portfolio files
10469:     user: name of user or num of course contain the portfolio files
10470:   Returns:
10471:     hashref of a dump of the proper file_permissions.db
10472:    
10473: 
10474: =item * 
10475: 
10476: get_access_controls():
10477: 
10478: Args:
10479:   current_permissions: the hash ref returned from get_portfile_permissions()
10480:   group: (optional) the group you want the files associated with
10481:   file: (optional) the file you want access info on
10482: 
10483: Returns:
10484:     a hash (keys are file names) of hashes containing
10485:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10486:         values are XML containing access control settings (see below) 
10487: 
10488: Internal notes:
10489: 
10490:  access controls are stored in file_permissions.db as key=value pairs.
10491:     key -> path to file/file_name\0uniqueID:scope_end_start
10492:         where scope -> public,guest,course,group,domains or users.
10493:               end -> UNIX time for end of access (0 -> no end date)
10494:               start -> UNIX time for start of access
10495: 
10496:     value -> XML description of access control
10497:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10498:             <start></start>
10499:             <end></end>
10500: 
10501:             <password></password>  for scope type = guest
10502: 
10503:             <domain></domain>     for scope type = course or group
10504:             <number></number>
10505:             <roles id="">
10506:              <role></role>
10507:              <access></access>
10508:              <section></section>
10509:              <group></group>
10510:             </roles>
10511: 
10512:             <dom></dom>         for scope type = domains
10513: 
10514:             <users>             for scope type = users
10515:              <user>
10516:               <uname></uname>
10517:               <udom></udom>
10518:              </user>
10519:             </users>
10520:            </scope> 
10521:               
10522:  Access data is also aggregated for each file in an additional key=value pair:
10523:  key -> path to file/file_name\0accesscontrol 
10524:  value -> reference to hash
10525:           hash contains key = value pairs
10526:           where key = uniqueID:scope_end_start
10527:                 value = UNIX time record was last updated
10528: 
10529:           Used to improve speed of look-ups of access controls for each file.  
10530:  
10531:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10532: 
10533: modify_access_controls():
10534: 
10535: Modifies access controls for a portfolio file
10536: Args
10537: 1. file name
10538: 2. reference to hash of required changes,
10539: 3. domain
10540: 4. username
10541:   where domain,username are the domain of the portfolio owner 
10542:   (either a user or a course) 
10543: 
10544: Returns:
10545: 1. result of additions or updates ('ok' or 'error', with error message). 
10546: 2. result of deletions ('ok' or 'error', with error message).
10547: 3. reference to hash of any new or updated access controls.
10548: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10549:    key = integer (inbound ID)
10550:    value = uniqueID  
10551: 
10552: =back
10553: 
10554: =head2 HTTP Helper Routines
10555: 
10556: =over 4
10557: 
10558: =item *
10559: 
10560: escape() : unpack non-word characters into CGI-compatible hex codes
10561: 
10562: =item *
10563: 
10564: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10565: 
10566: =back
10567: 
10568: =head1 PRIVATE SUBROUTINES
10569: 
10570: =head2 Underlying communication routines (Shouldn't call)
10571: 
10572: =over 4
10573: 
10574: =item *
10575: 
10576: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10577: 
10578: =item *
10579: 
10580: reply() : uses subreply to send a message to remote machine, logs all failures
10581: 
10582: =item *
10583: 
10584: critical() : passes a critical message to another server; if cannot
10585: get through then place message in connection buffer directory and
10586: returns con_delayed, if incapable of saving message, returns
10587: con_failed
10588: 
10589: =item *
10590: 
10591: reconlonc() : tries to reconnect lonc client processes.
10592: 
10593: =back
10594: 
10595: =head2 Resource Access Logging
10596: 
10597: =over 4
10598: 
10599: =item *
10600: 
10601: flushcourselogs() : flush (save) buffer logs and access logs
10602: 
10603: =item *
10604: 
10605: courselog($what) : save message for course in hash
10606: 
10607: =item *
10608: 
10609: courseacclog($what) : save message for course using &courselog().  Perform
10610: special processing for specific resource types (problems, exams, quizzes, etc).
10611: 
10612: =item *
10613: 
10614: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10615: as a PerlChildExitHandler
10616: 
10617: =back
10618: 
10619: =head2 Other
10620: 
10621: =over 4
10622: 
10623: =item *
10624: 
10625: symblist($mapname,%newhash) : update symbolic storage links
10626: 
10627: =back
10628: 
10629: =cut
10630: 

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