File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.992: download - view: text, annotated - select for diffs
Sat Mar 21 21:43:46 2009 UTC (15 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Attempt to retrieve IP of DNS server from %name_to_ip first before calling gethostbyname.
- Move &host_from_dns() subroutine so %name_to_ip is in scope.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.992 2009/03/21 21:43:46 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: # -------------------------------------------------- Non-critical communication
  200: sub subreply {
  201:     my ($cmd,$server)=@_;
  202:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  203:     #
  204:     #  With loncnew process trimming, there's a timing hole between lonc server
  205:     #  process exit and the master server picking up the listen on the AF_UNIX
  206:     #  socket.  In that time interval, a lock file will exist:
  207: 
  208:     my $lockfile=$peerfile.".lock";
  209:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  210: 	sleep(1);
  211:     }
  212:     # At this point, either a loncnew parent is listening or an old lonc
  213:     # or loncnew child is listening so we can connect or everything's dead.
  214:     #
  215:     #   We'll give the connection a few tries before abandoning it.  If
  216:     #   connection is not possible, we'll con_lost back to the client.
  217:     #   
  218:     my $client;
  219:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  220: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  221: 				      Type    => SOCK_STREAM,
  222: 				      Timeout => 10);
  223: 	if ($client) {
  224: 	    last;		# Connected!
  225: 	} else {
  226: 	    &create_connection(&hostname($server),$server);
  227: 	}
  228:         sleep(1);		# Try again later if failed connection.
  229:     }
  230:     my $answer;
  231:     if ($client) {
  232: 	print $client "sethost:$server:$cmd\n";
  233: 	$answer=<$client>;
  234: 	if (!$answer) { $answer="con_lost"; }
  235: 	chomp($answer);
  236:     } else {
  237: 	$answer = 'con_lost';	# Failed connection.
  238:     }
  239:     return $answer;
  240: }
  241: 
  242: sub reply {
  243:     my ($cmd,$server)=@_;
  244:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  245:     my $answer=subreply($cmd,$server);
  246:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  247:        &logthis("<font color=\"blue\">WARNING:".
  248:                 " $cmd to $server returned $answer</font>");
  249:     }
  250:     return $answer;
  251: }
  252: 
  253: # ----------------------------------------------------------- Send USR1 to lonc
  254: 
  255: sub reconlonc {
  256:     my ($lonid) = @_;
  257:     my $hostname = &hostname($lonid);
  258:     if ($lonid) {
  259: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  260: 	if ($hostname && -e $peerfile) {
  261: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  262: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  263: 					     Type    => SOCK_STREAM,
  264: 					     Timeout => 10);
  265: 	    if ($client) {
  266: 		print $client ("reset_retries\n");
  267: 		my $answer=<$client>;
  268: 		#reset just this one.
  269: 	    }
  270: 	}
  271: 	return;
  272:     }
  273: 
  274:     &logthis("Trying to reconnect lonc");
  275:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  276:     if (open(my $fh,"<$loncfile")) {
  277: 	my $loncpid=<$fh>;
  278:         chomp($loncpid);
  279:         if (kill 0 => $loncpid) {
  280: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  281:             kill USR1 => $loncpid;
  282:             sleep 1;
  283:          } else {
  284: 	    &logthis(
  285:                "<font color=\"blue\">WARNING:".
  286:                " lonc at pid $loncpid not responding, giving up</font>");
  287:         }
  288:     } else {
  289: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  290:     }
  291: }
  292: 
  293: # ------------------------------------------------------ Critical communication
  294: 
  295: sub critical {
  296:     my ($cmd,$server)=@_;
  297:     unless (&hostname($server)) {
  298:         &logthis("<font color=\"blue\">WARNING:".
  299:                " Critical message to unknown server ($server)</font>");
  300:         return 'no_such_host';
  301:     }
  302:     my $answer=reply($cmd,$server);
  303:     if ($answer eq 'con_lost') {
  304: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  305: 	my $answer=reply($cmd,$server);
  306:         if ($answer eq 'con_lost') {
  307:             my $now=time;
  308:             my $middlename=$cmd;
  309:             $middlename=substr($middlename,0,16);
  310:             $middlename=~s/\W//g;
  311:             my $dfilename=
  312:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  313:             $dumpcount++;
  314:             {
  315: 		my $dfh;
  316: 		if (open($dfh,">$dfilename")) {
  317: 		    print $dfh "$cmd\n"; 
  318: 		    close($dfh);
  319: 		}
  320:             }
  321:             sleep 2;
  322:             my $wcmd='';
  323:             {
  324: 		my $dfh;
  325: 		if (open($dfh,"<$dfilename")) {
  326: 		    $wcmd=<$dfh>; 
  327: 		    close($dfh);
  328: 		}
  329:             }
  330:             chomp($wcmd);
  331:             if ($wcmd eq $cmd) {
  332: 		&logthis("<font color=\"blue\">WARNING: ".
  333:                          "Connection buffer $dfilename: $cmd</font>");
  334:                 &logperm("D:$server:$cmd");
  335: 	        return 'con_delayed';
  336:             } else {
  337:                 &logthis("<font color=\"red\">CRITICAL:"
  338:                         ." Critical connection failed: $server $cmd</font>");
  339:                 &logperm("F:$server:$cmd");
  340:                 return 'con_failed';
  341:             }
  342:         }
  343:     }
  344:     return $answer;
  345: }
  346: 
  347: # ------------------------------------------- check if return value is an error
  348: 
  349: sub error {
  350:     my ($result) = @_;
  351:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  352: 	if ($2 == 2) { return undef; }
  353: 	return $1;
  354:     }
  355:     return undef;
  356: }
  357: 
  358: sub convert_and_load_session_env {
  359:     my ($lonidsdir,$handle)=@_;
  360:     my @profile;
  361:     {
  362: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  363: 	if (!$opened) {
  364: 	    return 0;
  365: 	}
  366: 	flock($idf,LOCK_SH);
  367: 	@profile=<$idf>;
  368: 	close($idf);
  369:     }
  370:     my %temp_env;
  371:     foreach my $line (@profile) {
  372: 	if ($line !~ m/=/) {
  373: 	    return 0;
  374: 	}
  375: 	chomp($line);
  376: 	my ($envname,$envvalue)=split(/=/,$line,2);
  377: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  378:     }
  379:     unlink("$lonidsdir/$handle.id");
  380:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  381: 	    0640)) {
  382: 	%disk_env = %temp_env;
  383: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  384: 	untie(%disk_env);
  385:     }
  386:     return 1;
  387: }
  388: 
  389: # ------------------------------------------- Transfer profile into environment
  390: my $env_loaded;
  391: sub transfer_profile_to_env {
  392:     my ($lonidsdir,$handle,$force_transfer) = @_;
  393:     if (!$force_transfer && $env_loaded) { return; } 
  394: 
  395:     if (!defined($lonidsdir)) {
  396: 	$lonidsdir = $perlvar{'lonIDsDir'};
  397:     }
  398:     if (!defined($handle)) {
  399:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  400:     }
  401: 
  402:     my $convert;
  403:     {
  404:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  405: 	if (!$opened) {
  406: 	    return;
  407: 	}
  408: 	flock($idf,LOCK_SH);
  409: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  410: 		&GDBM_READER(),0640)) {
  411: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  412: 	    untie(%disk_env);
  413: 	} else {
  414: 	    $convert = 1;
  415: 	}
  416:     }
  417:     if ($convert) {
  418: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  419: 	    &logthis("Failed to load session, or convert session.");
  420: 	}
  421:     }
  422: 
  423:     my %remove;
  424:     while ( my $envname = each(%env) ) {
  425:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  426:             if ($time < time-300) {
  427:                 $remove{$key}++;
  428:             }
  429:         }
  430:     }
  431: 
  432:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  433:     $env_loaded=1;
  434:     foreach my $expired_key (keys(%remove)) {
  435:         &delenv($expired_key);
  436:     }
  437: }
  438: 
  439: # ---------------------------------------------------- Check for valid session 
  440: sub check_for_valid_session {
  441:     my ($r) = @_;
  442:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  443:     my $lonid=$cookies{'lonID'};
  444:     return undef if (!$lonid);
  445: 
  446:     my $handle=&LONCAPA::clean_handle($lonid->value);
  447:     my $lonidsdir=$r->dir_config('lonIDsDir');
  448:     return undef if (!-e "$lonidsdir/$handle.id");
  449: 
  450:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  451:     return undef if (!$opened);
  452: 
  453:     flock($idf,LOCK_SH);
  454:     my %disk_env;
  455:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  456: 	    &GDBM_READER(),0640)) {
  457: 	return undef;	
  458:     }
  459: 
  460:     if (!defined($disk_env{'user.name'})
  461: 	|| !defined($disk_env{'user.domain'})) {
  462: 	return undef;
  463:     }
  464:     return $handle;
  465: }
  466: 
  467: sub timed_flock {
  468:     my ($file,$lock_type) = @_;
  469:     my $failed=0;
  470:     eval {
  471: 	local $SIG{__DIE__}='DEFAULT';
  472: 	local $SIG{ALRM}=sub {
  473: 	    $failed=1;
  474: 	    die("failed lock");
  475: 	};
  476: 	alarm(13);
  477: 	flock($file,$lock_type);
  478: 	alarm(0);
  479:     };
  480:     if ($failed) {
  481: 	return undef;
  482:     } else {
  483: 	return 1;
  484:     }
  485: }
  486: 
  487: # ---------------------------------------------------------- Append Environment
  488: 
  489: sub appenv {
  490:     my ($newenv,$roles) = @_;
  491:     if (ref($newenv) eq 'HASH') {
  492:         foreach my $key (keys(%{$newenv})) {
  493:             my $refused = 0;
  494: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  495:                 $refused = 1;
  496:                 if (ref($roles) eq 'ARRAY') {
  497:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  498:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  499:                         $refused = 0;
  500:                     }
  501:                 }
  502:             }
  503:             if ($refused) {
  504:                 &logthis("<font color=\"blue\">WARNING: ".
  505:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  506:                          .'</font>');
  507: 	        delete($newenv->{$key});
  508:             } else {
  509:                 $env{$key}=$newenv->{$key};
  510:             }
  511:         }
  512:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  513:         if ($opened
  514: 	    && &timed_flock($env_file,LOCK_EX)
  515: 	    &&
  516: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  517: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  518: 	    while (my ($key,$value) = each(%{$newenv})) {
  519: 	        $disk_env{$key} = $value;
  520: 	    }
  521: 	    untie(%disk_env);
  522:         }
  523:     }
  524:     return 'ok';
  525: }
  526: # ----------------------------------------------------- Delete from Environment
  527: 
  528: sub delenv {
  529:     my ($delthis,$regexp) = @_;
  530:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  531:         &logthis("<font color=\"blue\">WARNING: ".
  532:                 "Attempt to delete from environment ".$delthis);
  533:         return 'error';
  534:     }
  535:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  536:     if ($opened
  537: 	&& &timed_flock($env_file,LOCK_EX)
  538: 	&&
  539: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  540: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  541: 	foreach my $key (keys(%disk_env)) {
  542: 	    if ($regexp) {
  543:                 if ($key=~/^$delthis/) {
  544:                     delete($env{$key});
  545:                     delete($disk_env{$key});
  546:                 } 
  547:             } else {
  548:                 if ($key=~/^\Q$delthis\E/) {
  549: 		    delete($env{$key});
  550: 		    delete($disk_env{$key});
  551: 	        }
  552:             }
  553: 	}
  554: 	untie(%disk_env);
  555:     }
  556:     return 'ok';
  557: }
  558: 
  559: sub get_env_multiple {
  560:     my ($name) = @_;
  561:     my @values;
  562:     if (defined($env{$name})) {
  563:         # exists is it an array
  564:         if (ref($env{$name})) {
  565:             @values=@{ $env{$name} };
  566:         } else {
  567:             $values[0]=$env{$name};
  568:         }
  569:     }
  570:     return(@values);
  571: }
  572: 
  573: # ------------------------------------------------------------------- Locking
  574: 
  575: sub set_lock {
  576:     my ($text)=@_;
  577:     $locknum++;
  578:     my $id=$$.'-'.$locknum;
  579:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  580:              'session.lock.'.$id => $text});
  581:     return $id;
  582: }
  583: 
  584: sub get_locks {
  585:     my $num=0;
  586:     my %texts=();
  587:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  588:        if ($lock=~/\w/) {
  589:           $num++;
  590:           $texts{$lock}=$env{'session.lock.'.$lock};
  591:        }
  592:    }
  593:    return ($num,%texts);
  594: }
  595: 
  596: sub remove_lock {
  597:     my ($id)=@_;
  598:     my $newlocks='';
  599:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  600:        if (($lock=~/\w/) && ($lock ne $id)) {
  601:           $newlocks.=','.$lock;
  602:        }
  603:     }
  604:     &appenv({'session.locks' => $newlocks});
  605:     &delenv('session.lock.'.$id);
  606: }
  607: 
  608: sub remove_all_locks {
  609:     my $activelocks=$env{'session.locks'};
  610:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  611:        if ($lock=~/\w/) {
  612:           &remove_lock($lock);
  613:        }
  614:     }
  615: }
  616: 
  617: 
  618: # ------------------------------------------ Find out current server userload
  619: sub userload {
  620:     my $numusers=0;
  621:     {
  622: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  623: 	my $filename;
  624: 	my $curtime=time;
  625: 	while ($filename=readdir(LONIDS)) {
  626: 	    next if ($filename eq '.' || $filename eq '..');
  627: 	    next if ($filename =~ /publicuser_\d+\.id/);
  628: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  629: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  630: 	}
  631: 	closedir(LONIDS);
  632:     }
  633:     my $userloadpercent=0;
  634:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  635:     if ($maxuserload) {
  636: 	$userloadpercent=100*$numusers/$maxuserload;
  637:     }
  638:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  639:     return $userloadpercent;
  640: }
  641: 
  642: # ------------------------------------------ Fight off request when overloaded
  643: 
  644: sub overloaderror {
  645:     my ($r,$checkserver)=@_;
  646:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  647:     my $loadavg;
  648:     if ($checkserver eq $perlvar{'lonHostID'}) {
  649:        open(my $loadfile,'/proc/loadavg');
  650:        $loadavg=<$loadfile>;
  651:        $loadavg =~ s/\s.*//g;
  652:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  653:        close($loadfile);
  654:     } else {
  655:        $loadavg=&reply('load',$checkserver);
  656:     }
  657:     my $overload=$loadavg-100;
  658:     if ($overload>0) {
  659: 	$r->err_headers_out->{'Retry-After'}=$overload;
  660:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  661:         return 413;
  662:     }    
  663:     return '';
  664: }
  665: 
  666: # ------------------------------ Find server with least workload from spare.tab
  667: 
  668: sub spareserver {
  669:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  670:     my $spare_server;
  671:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  672:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  673:                                                      :  $userloadpercent;
  674:     
  675:     foreach my $try_server (@{ $spareid{'primary'} }) {
  676: 	($spare_server, $lowest_load) =
  677: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  678:     }
  679: 
  680:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  681: 
  682:     if (!$found_server) {
  683: 	foreach my $try_server (@{ $spareid{'default'} }) {
  684: 	    ($spare_server, $lowest_load) =
  685: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  686: 	}
  687:     }
  688: 
  689:     if (!$want_server_name) {
  690:         my $protocol = 'http';
  691:         if ($protocol{$spare_server} eq 'https') {
  692:             $protocol = $protocol{$spare_server};
  693:         }
  694: 	$spare_server = $protocol.'://'.&hostname($spare_server);
  695:     }
  696:     return $spare_server;
  697: }
  698: 
  699: sub compare_server_load {
  700:     my ($try_server, $spare_server, $lowest_load) = @_;
  701: 
  702:     my $loadans     = &reply('load',    $try_server);
  703:     my $userloadans = &reply('userload',$try_server);
  704: 
  705:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  706: 	next; #didn't get a number from the server
  707:     }
  708: 
  709:     my $load;
  710:     if ($loadans =~ /\d/) {
  711: 	if ($userloadans =~ /\d/) {
  712: 	    #both are numbers, pick the bigger one
  713: 	    $load = ($loadans > $userloadans) ? $loadans 
  714: 		                              : $userloadans;
  715: 	} else {
  716: 	    $load = $loadans;
  717: 	}
  718:     } else {
  719: 	$load = $userloadans;
  720:     }
  721: 
  722:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  723: 	$spare_server = $try_server;
  724: 	$lowest_load  = $load;
  725:     }
  726:     return ($spare_server,$lowest_load);
  727: }
  728: 
  729: # --------------------------- ask offload servers if user already has a session
  730: sub find_existing_session {
  731:     my ($udom,$uname) = @_;
  732:     foreach my $try_server (@{ $spareid{'primary'} },
  733: 			    @{ $spareid{'default'} }) {
  734: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
  735:     }
  736:     return;
  737: }
  738: 
  739: # -------------------------------- ask if server already has a session for user
  740: sub has_user_session {
  741:     my ($lonid,$udom,$uname) = @_;
  742:     my $result = &reply(join(':','userhassession',
  743: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  744:     return 1 if ($result eq 'ok');
  745: 
  746:     return 0;
  747: }
  748: 
  749: # --------------------------------------------- Try to change a user's password
  750: 
  751: sub changepass {
  752:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  753:     $currentpass = &escape($currentpass);
  754:     $newpass     = &escape($newpass);
  755:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  756: 		       $server);
  757:     if (! $answer) {
  758: 	&logthis("No reply on password change request to $server ".
  759: 		 "by $uname in domain $udom.");
  760:     } elsif ($answer =~ "^ok") {
  761:         &logthis("$uname in $udom successfully changed their password ".
  762: 		 "on $server.");
  763:     } elsif ($answer =~ "^pwchange_failure") {
  764: 	&logthis("$uname in $udom was unable to change their password ".
  765: 		 "on $server.  The action was blocked by either lcpasswd ".
  766: 		 "or pwchange");
  767:     } elsif ($answer =~ "^non_authorized") {
  768:         &logthis("$uname in $udom did not get their password correct when ".
  769: 		 "attempting to change it on $server.");
  770:     } elsif ($answer =~ "^auth_mode_error") {
  771:         &logthis("$uname in $udom attempted to change their password despite ".
  772: 		 "not being locally or internally authenticated on $server.");
  773:     } elsif ($answer =~ "^unknown_user") {
  774:         &logthis("$uname in $udom attempted to change their password ".
  775: 		 "on $server but were unable to because $server is not ".
  776: 		 "their home server.");
  777:     } elsif ($answer =~ "^refused") {
  778: 	&logthis("$server refused to change $uname in $udom password because ".
  779: 		 "it was sent an unencrypted request to change the password.");
  780:     }
  781:     return $answer;
  782: }
  783: 
  784: # ----------------------- Try to determine user's current authentication scheme
  785: 
  786: sub queryauthenticate {
  787:     my ($uname,$udom)=@_;
  788:     my $uhome=&homeserver($uname,$udom);
  789:     if (!$uhome) {
  790: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  791: 	return 'no_host';
  792:     }
  793:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  794:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  795: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  796:     }
  797:     return $answer;
  798: }
  799: 
  800: # --------- Try to authenticate user from domain's lib servers (first this one)
  801: 
  802: sub authenticate {
  803:     my ($uname,$upass,$udom,$checkdefauth)=@_;
  804:     $upass=&escape($upass);
  805:     $uname= &LONCAPA::clean_username($uname);
  806:     my $uhome=&homeserver($uname,$udom,1);
  807:     my $newhome;
  808:     if ((!$uhome) || ($uhome eq 'no_host')) {
  809: # Maybe the machine was offline and only re-appeared again recently?
  810:         &reconlonc();
  811: # One more
  812: 	$uhome=&homeserver($uname,$udom,1);
  813:         if (($uhome eq 'no_host') && $checkdefauth) {
  814:             if (defined(&domain($udom,'primary'))) {
  815:                 $newhome=&domain($udom,'primary');
  816:             }
  817:             if ($newhome ne '') {
  818:                 $uhome = $newhome;
  819:             }
  820:         }
  821: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  822: 	    &logthis("User $uname at $udom is unknown in authenticate");
  823: 	    return 'no_host';
  824:         }
  825:     }
  826:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
  827:     if ($answer eq 'authorized') {
  828:         if ($newhome) {
  829:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
  830:             return 'no_account_on_host'; 
  831:         } else {
  832:             &logthis("User $uname at $udom authorized by $uhome");
  833:             return $uhome;
  834:         }
  835:     }
  836:     if ($answer eq 'non_authorized') {
  837: 	&logthis("User $uname at $udom rejected by $uhome");
  838: 	return 'no_host'; 
  839:     }
  840:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  841:     return 'no_host';
  842: }
  843: 
  844: # ---------------------- Find the homebase for a user from domain's lib servers
  845: 
  846: my %homecache;
  847: sub homeserver {
  848:     my ($uname,$udom,$ignoreBadCache)=@_;
  849:     my $index="$uname:$udom";
  850: 
  851:     if (exists($homecache{$index})) { return $homecache{$index}; }
  852: 
  853:     my %servers = &get_servers($udom,'library');
  854:     foreach my $tryserver (keys(%servers)) {
  855:         next if ($ignoreBadCache ne 'true' && 
  856: 		 exists($badServerCache{$tryserver}));
  857: 
  858: 	my $answer=reply("home:$udom:$uname",$tryserver);
  859: 	if ($answer eq 'found') {
  860: 	    delete($badServerCache{$tryserver}); 
  861: 	    return $homecache{$index}=$tryserver;
  862: 	} elsif ($answer eq 'no_host') {
  863: 	    $badServerCache{$tryserver}=1;
  864: 	}
  865:     }    
  866:     return 'no_host';
  867: }
  868: 
  869: # ------------------------------------- Find the usernames behind a list of IDs
  870: 
  871: sub idget {
  872:     my ($udom,@ids)=@_;
  873:     my %returnhash=();
  874:     
  875:     my %servers = &get_servers($udom,'library');
  876:     foreach my $tryserver (keys(%servers)) {
  877: 	my $idlist=join('&',@ids);
  878: 	$idlist=~tr/A-Z/a-z/; 
  879: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  880: 	my @answer=();
  881: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  882: 	    @answer=split(/\&/,$reply);
  883: 	}                    ;
  884: 	my $i;
  885: 	for ($i=0;$i<=$#ids;$i++) {
  886: 	    if ($answer[$i]) {
  887: 		$returnhash{$ids[$i]}=$answer[$i];
  888: 	    } 
  889: 	}
  890:     } 
  891:     return %returnhash;
  892: }
  893: 
  894: # ------------------------------------- Find the IDs behind a list of usernames
  895: 
  896: sub idrget {
  897:     my ($udom,@unames)=@_;
  898:     my %returnhash=();
  899:     foreach my $uname (@unames) {
  900:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  901:     }
  902:     return %returnhash;
  903: }
  904: 
  905: # ------------------------------- Store away a list of names and associated IDs
  906: 
  907: sub idput {
  908:     my ($udom,%ids)=@_;
  909:     my %servers=();
  910:     foreach my $uname (keys(%ids)) {
  911: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  912:         my $uhom=&homeserver($uname,$udom);
  913:         if ($uhom ne 'no_host') {
  914:             my $id=&escape($ids{$uname});
  915:             $id=~tr/A-Z/a-z/;
  916:             my $esc_unam=&escape($uname);
  917: 	    if ($servers{$uhom}) {
  918: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  919:             } else {
  920:                 $servers{$uhom}=$id.'='.$esc_unam;
  921:             }
  922:         }
  923:     }
  924:     foreach my $server (keys(%servers)) {
  925:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  926:     }
  927: }
  928: 
  929: # ------------------------------------------- get items from domain db files   
  930: 
  931: sub get_dom {
  932:     my ($namespace,$storearr,$udom,$uhome)=@_;
  933:     my $items='';
  934:     foreach my $item (@$storearr) {
  935:         $items.=&escape($item).'&';
  936:     }
  937:     $items=~s/\&$//;
  938:     if (!$udom) {
  939:         $udom=$env{'user.domain'};
  940:         if (defined(&domain($udom,'primary'))) {
  941:             $uhome=&domain($udom,'primary');
  942:         } else {
  943:             undef($uhome);
  944:         }
  945:     } else {
  946:         if (!$uhome) {
  947:             if (defined(&domain($udom,'primary'))) {
  948:                 $uhome=&domain($udom,'primary');
  949:             }
  950:         }
  951:     }
  952:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  953:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  954:         my %returnhash;
  955:         if ($rep eq '' || $rep =~ /^error: 2 /) {
  956:             return %returnhash;
  957:         }
  958:         my @pairs=split(/\&/,$rep);
  959:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  960:             return @pairs;
  961:         }
  962:         my $i=0;
  963:         foreach my $item (@$storearr) {
  964:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  965:             $i++;
  966:         }
  967:         return %returnhash;
  968:     } else {
  969:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
  970:     }
  971: }
  972: 
  973: # -------------------------------------------- put items in domain db files 
  974: 
  975: sub put_dom {
  976:     my ($namespace,$storehash,$udom,$uhome)=@_;
  977:     if (!$udom) {
  978:         $udom=$env{'user.domain'};
  979:         if (defined(&domain($udom,'primary'))) {
  980:             $uhome=&domain($udom,'primary');
  981:         } else {
  982:             undef($uhome);
  983:         }
  984:     } else {
  985:         if (!$uhome) {
  986:             if (defined(&domain($udom,'primary'))) {
  987:                 $uhome=&domain($udom,'primary');
  988:             }
  989:         }
  990:     } 
  991:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  992:         my $items='';
  993:         foreach my $item (keys(%$storehash)) {
  994:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  995:         }
  996:         $items=~s/\&$//;
  997:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  998:     } else {
  999:         &logthis("put_dom failed - no homeserver and/or domain");
 1000:     }
 1001: }
 1002: 
 1003: sub retrieve_inst_usertypes {
 1004:     my ($udom) = @_;
 1005:     my (%returnhash,@order);
 1006:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1007:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1008:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1009:         %returnhash = %{$domdefs{'inststatustypes'}};
 1010:         @order = @{$domdefs{'inststatusorder'}};
 1011:     } else {
 1012:         if (defined(&domain($udom,'primary'))) {
 1013:             my $uhome=&domain($udom,'primary');
 1014:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1015:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1016:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1017:                 return (\%returnhash,\@order);
 1018:             }
 1019:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1020:             my @pairs=split(/\&/,$hashitems);
 1021:             foreach my $item (@pairs) {
 1022:                 my ($key,$value)=split(/=/,$item,2);
 1023:                 $key = &unescape($key);
 1024:                 next if ($key =~ /^error: 2 /);
 1025:                 $returnhash{$key}=&thaw_unescape($value);
 1026:             }
 1027:             my @esc_order = split(/\&/,$orderitems);
 1028:             foreach my $item (@esc_order) {
 1029:                 push(@order,&unescape($item));
 1030:             }
 1031:         } else {
 1032:             &logthis("get_dom failed - no primary domain server for $udom");
 1033:         }
 1034:     }
 1035:     return (\%returnhash,\@order);
 1036: }
 1037: 
 1038: sub is_domainimage {
 1039:     my ($url) = @_;
 1040:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1041:         if (&domain($1) ne '') {
 1042:             return '1';
 1043:         }
 1044:     }
 1045:     return;
 1046: }
 1047: 
 1048: sub inst_directory_query {
 1049:     my ($srch) = @_;
 1050:     my $udom = $srch->{'srchdomain'};
 1051:     my %results;
 1052:     my $homeserver = &domain($udom,'primary');
 1053:     my $outcome;
 1054:     if ($homeserver ne '') {
 1055: 	my $queryid=&reply("querysend:instdirsearch:".
 1056: 			   &escape($srch->{'srchby'}).':'.
 1057: 			   &escape($srch->{'srchterm'}).':'.
 1058: 			   &escape($srch->{'srchtype'}),$homeserver);
 1059: 	my $host=&hostname($homeserver);
 1060: 	if ($queryid !~/^\Q$host\E\_/) {
 1061: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1062: 	    return;
 1063: 	}
 1064: 	my $response = &get_query_reply($queryid);
 1065: 	my $maxtries = 5;
 1066: 	my $tries = 1;
 1067: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1068: 	    $response = &get_query_reply($queryid);
 1069: 	    $tries ++;
 1070: 	}
 1071: 
 1072:         if (!&error($response) && $response ne 'refused') {
 1073:             if ($response eq 'unavailable') {
 1074:                 $outcome = $response;
 1075:             } else {
 1076:                 $outcome = 'ok';
 1077:                 my @matches = split(/\n/,$response);
 1078:                 foreach my $match (@matches) {
 1079:                     my ($key,$value) = split(/=/,$match);
 1080:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1081:                 }
 1082:             }
 1083:         }
 1084:     }
 1085:     return ($outcome,%results);
 1086: }
 1087: 
 1088: sub usersearch {
 1089:     my ($srch) = @_;
 1090:     my $dom = $srch->{'srchdomain'};
 1091:     my %results;
 1092:     my %libserv = &all_library();
 1093:     my $query = 'usersearch';
 1094:     foreach my $tryserver (keys(%libserv)) {
 1095:         if (&host_domain($tryserver) eq $dom) {
 1096:             my $host=&hostname($tryserver);
 1097:             my $queryid=
 1098:                 &reply("querysend:".&escape($query).':'.
 1099:                        &escape($srch->{'srchby'}).':'.
 1100:                        &escape($srch->{'srchtype'}).':'.
 1101:                        &escape($srch->{'srchterm'}),$tryserver);
 1102:             if ($queryid !~/^\Q$host\E\_/) {
 1103:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1104:                 next;
 1105:             }
 1106:             my $reply = &get_query_reply($queryid);
 1107:             my $maxtries = 1;
 1108:             my $tries = 1;
 1109:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1110:                 $reply = &get_query_reply($queryid);
 1111:                 $tries ++;
 1112:             }
 1113:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1114:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1115:             } else {
 1116:                 my @matches;
 1117:                 if ($reply =~ /\n/) {
 1118:                     @matches = split(/\n/,$reply);
 1119:                 } else {
 1120:                     @matches = split(/\&/,$reply);
 1121:                 }
 1122:                 foreach my $match (@matches) {
 1123:                     my ($uname,$udom,%userhash);
 1124:                     foreach my $entry (split(/:/,$match)) {
 1125:                         my ($key,$value) =
 1126:                             map {&unescape($_);} split(/=/,$entry);
 1127:                         $userhash{$key} = $value;
 1128:                         if ($key eq 'username') {
 1129:                             $uname = $value;
 1130:                         } elsif ($key eq 'domain') {
 1131:                             $udom = $value;
 1132:                         }
 1133:                     }
 1134:                     $results{$uname.':'.$udom} = \%userhash;
 1135:                 }
 1136:             }
 1137:         }
 1138:     }
 1139:     return %results;
 1140: }
 1141: 
 1142: sub get_instuser {
 1143:     my ($udom,$uname,$id) = @_;
 1144:     my $homeserver = &domain($udom,'primary');
 1145:     my ($outcome,%results);
 1146:     if ($homeserver ne '') {
 1147:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1148:                            &escape($id).':'.&escape($udom),$homeserver);
 1149:         my $host=&hostname($homeserver);
 1150:         if ($queryid !~/^\Q$host\E\_/) {
 1151:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1152:             return;
 1153:         }
 1154:         my $response = &get_query_reply($queryid);
 1155:         my $maxtries = 5;
 1156:         my $tries = 1;
 1157:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1158:             $response = &get_query_reply($queryid);
 1159:             $tries ++;
 1160:         }
 1161:         if (!&error($response) && $response ne 'refused') {
 1162:             if ($response eq 'unavailable') {
 1163:                 $outcome = $response;
 1164:             } else {
 1165:                 $outcome = 'ok';
 1166:                 my @matches = split(/\n/,$response);
 1167:                 foreach my $match (@matches) {
 1168:                     my ($key,$value) = split(/=/,$match);
 1169:                     $results{&unescape($key)} = &thaw_unescape($value);
 1170:                 }
 1171:             }
 1172:         }
 1173:     }
 1174:     my %userinfo;
 1175:     if (ref($results{$uname}) eq 'HASH') {
 1176:         %userinfo = %{$results{$uname}};
 1177:     } 
 1178:     return ($outcome,%userinfo);
 1179: }
 1180: 
 1181: sub inst_rulecheck {
 1182:     my ($udom,$uname,$id,$item,$rules) = @_;
 1183:     my %returnhash;
 1184:     if ($udom ne '') {
 1185:         if (ref($rules) eq 'ARRAY') {
 1186:             @{$rules} = map {&escape($_);} (@{$rules});
 1187:             my $rulestr = join(':',@{$rules});
 1188:             my $homeserver=&domain($udom,'primary');
 1189:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1190:                 my $response;
 1191:                 if ($item eq 'username') {                
 1192:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1193:                                               ':'.&escape($uname).':'.$rulestr,
 1194:                                               $homeserver));
 1195:                 } elsif ($item eq 'id') {
 1196:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1197:                                               ':'.&escape($id).':'.$rulestr,
 1198:                                               $homeserver));
 1199:                 } elsif ($item eq 'selfcreate') {
 1200:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1201:                                                &escape($udom).':'.&escape($uname).
 1202:                                               ':'.$rulestr,$homeserver));
 1203:                 }
 1204:                 if ($response ne 'refused') {
 1205:                     my @pairs=split(/\&/,$response);
 1206:                     foreach my $item (@pairs) {
 1207:                         my ($key,$value)=split(/=/,$item,2);
 1208:                         $key = &unescape($key);
 1209:                         next if ($key =~ /^error: 2 /);
 1210:                         $returnhash{$key}=&thaw_unescape($value);
 1211:                     }
 1212:                 }
 1213:             }
 1214:         }
 1215:     }
 1216:     return %returnhash;
 1217: }
 1218: 
 1219: sub inst_userrules {
 1220:     my ($udom,$check) = @_;
 1221:     my (%ruleshash,@ruleorder);
 1222:     if ($udom ne '') {
 1223:         my $homeserver=&domain($udom,'primary');
 1224:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1225:             my $response;
 1226:             if ($check eq 'id') {
 1227:                 $response=&reply('instidrules:'.&escape($udom),
 1228:                                  $homeserver);
 1229:             } elsif ($check eq 'email') {
 1230:                 $response=&reply('instemailrules:'.&escape($udom),
 1231:                                  $homeserver);
 1232:             } else {
 1233:                 $response=&reply('instuserrules:'.&escape($udom),
 1234:                                  $homeserver);
 1235:             }
 1236:             if (($response ne 'refused') && ($response ne 'error') && 
 1237:                 ($response ne 'unknown_cmd') && 
 1238:                 ($response ne 'no_such_host')) {
 1239:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1240:                 my @pairs=split(/\&/,$hashitems);
 1241:                 foreach my $item (@pairs) {
 1242:                     my ($key,$value)=split(/=/,$item,2);
 1243:                     $key = &unescape($key);
 1244:                     next if ($key =~ /^error: 2 /);
 1245:                     $ruleshash{$key}=&thaw_unescape($value);
 1246:                 }
 1247:                 my @esc_order = split(/\&/,$orderitems);
 1248:                 foreach my $item (@esc_order) {
 1249:                     push(@ruleorder,&unescape($item));
 1250:                 }
 1251:             }
 1252:         }
 1253:     }
 1254:     return (\%ruleshash,\@ruleorder);
 1255: }
 1256: 
 1257: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1258: 
 1259: sub get_domain_defaults {
 1260:     my ($domain) = @_;
 1261:     my $cachetime = 60*60*24;
 1262:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1263:     if (defined($cached)) {
 1264:         if (ref($result) eq 'HASH') {
 1265:             return %{$result};
 1266:         }
 1267:     }
 1268:     my %domdefaults;
 1269:     my %domconfig =
 1270:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1271:                                   'requestcourses','inststatus'],$domain);
 1272:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1273:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1274:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1275:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1276:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1277:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1278:     } else {
 1279:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1280:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1281:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1282:     }
 1283:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1284:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1285:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1286:         } else {
 1287:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1288:         } 
 1289:         my @usertools = ('aboutme','blog','portfolio');
 1290:         foreach my $item (@usertools) {
 1291:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1292:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1293:             }
 1294:         }
 1295:     }
 1296:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1297:         foreach my $item ('official','unofficial') {
 1298:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1299:         }
 1300:     }
 1301:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 1302:         foreach my $item ('inststatustypes','inststatusorder') {
 1303:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 1304:         }
 1305:     }
 1306:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1307:                                   $cachetime);
 1308:     return %domdefaults;
 1309: }
 1310: 
 1311: # --------------------------------------------------- Assign a key to a student
 1312: 
 1313: sub assign_access_key {
 1314: #
 1315: # a valid key looks like uname:udom#comments
 1316: # comments are being appended
 1317: #
 1318:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1319:     $kdom=
 1320:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1321:     $knum=
 1322:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1323:     $cdom=
 1324:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1325:     $cnum=
 1326:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1327:     $udom=$env{'user.name'} unless (defined($udom));
 1328:     $uname=$env{'user.domain'} unless (defined($uname));
 1329:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1330:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1331:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1332:                                                   # assigned to this person
 1333:                                                   # - this should not happen,
 1334:                                                   # unless something went wrong
 1335:                                                   # the first time around
 1336: # ready to assign
 1337:         $logentry=$1.'; '.$logentry;
 1338:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1339:                                                  $kdom,$knum) eq 'ok') {
 1340: # key now belongs to user
 1341: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1342:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1343:                 &appenv({'environment.'.$envkey => $ckey});
 1344:                 return 'ok';
 1345:             } else {
 1346:                 return 
 1347:   'error: Count not permanently assign key, will need to be re-entered later.';
 1348: 	    }
 1349:         } else {
 1350:             return 'error: Could not assign key, try again later.';
 1351:         }
 1352:     } elsif (!$existing{$ckey}) {
 1353: # the key does not exist
 1354: 	return 'error: The key does not exist';
 1355:     } else {
 1356: # the key is somebody else's
 1357: 	return 'error: The key is already in use';
 1358:     }
 1359: }
 1360: 
 1361: # ------------------------------------------ put an additional comment on a key
 1362: 
 1363: sub comment_access_key {
 1364: #
 1365: # a valid key looks like uname:udom#comments
 1366: # comments are being appended
 1367: #
 1368:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1369:     $cdom=
 1370:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1371:     $cnum=
 1372:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1373:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1374:     if ($existing{$ckey}) {
 1375:         $existing{$ckey}.='; '.$logentry;
 1376: # ready to assign
 1377:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1378:                                                  $cdom,$cnum) eq 'ok') {
 1379: 	    return 'ok';
 1380:         } else {
 1381: 	    return 'error: Count not store comment.';
 1382:         }
 1383:     } else {
 1384: # the key does not exist
 1385: 	return 'error: The key does not exist';
 1386:     }
 1387: }
 1388: 
 1389: # ------------------------------------------------------ Generate a set of keys
 1390: 
 1391: sub generate_access_keys {
 1392:     my ($number,$cdom,$cnum,$logentry)=@_;
 1393:     $cdom=
 1394:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1395:     $cnum=
 1396:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1397:     unless (&allowed('mky',$cdom)) { return 0; }
 1398:     unless (($cdom) && ($cnum)) { return 0; }
 1399:     if ($number>10000) { return 0; }
 1400:     sleep(2); # make sure don't get same seed twice
 1401:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1402:     my $total=0;
 1403:     for (my $i=1;$i<=$number;$i++) {
 1404:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1405:                   sprintf("%lx",int(100000*rand)).'-'.
 1406:                   sprintf("%lx",int(100000*rand));
 1407:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1408:        $newkey=~s/0/h/g; # and also 0 and O
 1409:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1410:        if ($existing{$newkey}) {
 1411:            $i--;
 1412:        } else {
 1413: 	  if (&put('accesskeys',
 1414:               { $newkey => '# generated '.localtime().
 1415:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1416:                            '; '.$logentry },
 1417: 		   $cdom,$cnum) eq 'ok') {
 1418:               $total++;
 1419: 	  }
 1420:        }
 1421:     }
 1422:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1423:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1424:     return $total;
 1425: }
 1426: 
 1427: # ------------------------------------------------------- Validate an accesskey
 1428: 
 1429: sub validate_access_key {
 1430:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1431:     $cdom=
 1432:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1433:     $cnum=
 1434:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1435:     $udom=$env{'user.domain'} unless (defined($udom));
 1436:     $uname=$env{'user.name'} unless (defined($uname));
 1437:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1438:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1439: }
 1440: 
 1441: # ------------------------------------- Find the section of student in a course
 1442: sub devalidate_getsection_cache {
 1443:     my ($udom,$unam,$courseid)=@_;
 1444:     my $hashid="$udom:$unam:$courseid";
 1445:     &devalidate_cache_new('getsection',$hashid);
 1446: }
 1447: 
 1448: sub courseid_to_courseurl {
 1449:     my ($courseid) = @_;
 1450:     #already url style courseid
 1451:     return $courseid if ($courseid =~ m{^/});
 1452: 
 1453:     if (exists($env{'course.'.$courseid.'.num'})) {
 1454: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1455: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1456: 	return "/$cdom/$cnum";
 1457:     }
 1458: 
 1459:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1460:     if (exists($courseinfo{'num'})) {
 1461: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1462:     }
 1463: 
 1464:     return undef;
 1465: }
 1466: 
 1467: sub getsection {
 1468:     my ($udom,$unam,$courseid)=@_;
 1469:     my $cachetime=1800;
 1470: 
 1471:     my $hashid="$udom:$unam:$courseid";
 1472:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1473:     if (defined($cached)) { return $result; }
 1474: 
 1475:     my %Pending; 
 1476:     my %Expired;
 1477:     #
 1478:     # Each role can either have not started yet (pending), be active, 
 1479:     #    or have expired.
 1480:     #
 1481:     # If there is an active role, we are done.
 1482:     #
 1483:     # If there is more than one role which has not started yet, 
 1484:     #     choose the one which will start sooner
 1485:     # If there is one role which has not started yet, return it.
 1486:     #
 1487:     # If there is more than one expired role, choose the one which ended last.
 1488:     # If there is a role which has expired, return it.
 1489:     #
 1490:     $courseid = &courseid_to_courseurl($courseid);
 1491:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1492:     foreach my $key (keys(%roleshash)) {
 1493:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1494:         my $section=$1;
 1495:         if ($key eq $courseid.'_st') { $section=''; }
 1496:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1497:         my $now=time;
 1498:         if (defined($end) && $end && ($now > $end)) {
 1499:             $Expired{$end}=$section;
 1500:             next;
 1501:         }
 1502:         if (defined($start) && $start && ($now < $start)) {
 1503:             $Pending{$start}=$section;
 1504:             next;
 1505:         }
 1506:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1507:     }
 1508:     #
 1509:     # Presumedly there will be few matching roles from the above
 1510:     # loop and the sorting time will be negligible.
 1511:     if (scalar(keys(%Pending))) {
 1512:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1513:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1514:     } 
 1515:     if (scalar(keys(%Expired))) {
 1516:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1517:         my $time = pop(@sorted);
 1518:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1519:     }
 1520:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1521: }
 1522: 
 1523: sub save_cache {
 1524:     &purge_remembered();
 1525:     #&Apache::loncommon::validate_page();
 1526:     undef(%env);
 1527:     undef($env_loaded);
 1528: }
 1529: 
 1530: my $to_remember=-1;
 1531: my %remembered;
 1532: my %accessed;
 1533: my $kicks=0;
 1534: my $hits=0;
 1535: sub make_key {
 1536:     my ($name,$id) = @_;
 1537:     if (length($id) > 65 
 1538: 	&& length(&escape($id)) > 200) {
 1539: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1540:     }
 1541:     return &escape($name.':'.$id);
 1542: }
 1543: 
 1544: sub devalidate_cache_new {
 1545:     my ($name,$id,$debug) = @_;
 1546:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1547:     $id=&make_key($name,$id);
 1548:     $memcache->delete($id);
 1549:     delete($remembered{$id});
 1550:     delete($accessed{$id});
 1551: }
 1552: 
 1553: sub is_cached_new {
 1554:     my ($name,$id,$debug) = @_;
 1555:     $id=&make_key($name,$id);
 1556:     if (exists($remembered{$id})) {
 1557: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1558: 	$accessed{$id}=[&gettimeofday()];
 1559: 	$hits++;
 1560: 	return ($remembered{$id},1);
 1561:     }
 1562:     my $value = $memcache->get($id);
 1563:     if (!(defined($value))) {
 1564: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1565: 	return (undef,undef);
 1566:     }
 1567:     if ($value eq '__undef__') {
 1568: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1569: 	$value=undef;
 1570:     }
 1571:     &make_room($id,$value,$debug);
 1572:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1573:     return ($value,1);
 1574: }
 1575: 
 1576: sub do_cache_new {
 1577:     my ($name,$id,$value,$time,$debug) = @_;
 1578:     $id=&make_key($name,$id);
 1579:     my $setvalue=$value;
 1580:     if (!defined($setvalue)) {
 1581: 	$setvalue='__undef__';
 1582:     }
 1583:     if (!defined($time) ) {
 1584: 	$time=600;
 1585:     }
 1586:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1587:     my $result = $memcache->set($id,$setvalue,$time);
 1588:     if (! $result) {
 1589: 	&logthis("caching of id -> $id  failed");
 1590: 	$memcache->disconnect_all();
 1591:     }
 1592:     # need to make a copy of $value
 1593:     &make_room($id,$value,$debug);
 1594:     return $value;
 1595: }
 1596: 
 1597: sub make_room {
 1598:     my ($id,$value,$debug)=@_;
 1599: 
 1600:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1601:                                     : $value;
 1602:     if ($to_remember<0) { return; }
 1603:     $accessed{$id}=[&gettimeofday()];
 1604:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1605:     my $to_kick;
 1606:     my $max_time=0;
 1607:     foreach my $other (keys(%accessed)) {
 1608: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1609: 	    $to_kick=$other;
 1610: 	    $max_time=&tv_interval($accessed{$other});
 1611: 	}
 1612:     }
 1613:     delete($remembered{$to_kick});
 1614:     delete($accessed{$to_kick});
 1615:     $kicks++;
 1616:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1617:     return;
 1618: }
 1619: 
 1620: sub purge_remembered {
 1621:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1622:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1623:     undef(%remembered);
 1624:     undef(%accessed);
 1625: }
 1626: # ------------------------------------- Read an entry from a user's environment
 1627: 
 1628: sub userenvironment {
 1629:     my ($udom,$unam,@what)=@_;
 1630:     my $items;
 1631:     foreach my $item (@what) {
 1632:         $items.=&escape($item).'&';
 1633:     }
 1634:     $items=~s/\&$//;
 1635:     my %returnhash=();
 1636:     my @answer=split(/\&/,
 1637:                 &reply('get:'.$udom.':'.$unam.':environment:'.$items,
 1638:                       &homeserver($unam,$udom)));
 1639:     my $i;
 1640:     for ($i=0;$i<=$#what;$i++) {
 1641: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1642:     }
 1643:     return %returnhash;
 1644: }
 1645: 
 1646: # ---------------------------------------------------------- Get a studentphoto
 1647: sub studentphoto {
 1648:     my ($udom,$unam,$ext) = @_;
 1649:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1650:     if (defined($env{'request.course.id'})) {
 1651:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1652:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1653:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1654:             } else {
 1655:                 my ($result,$perm_reqd)=
 1656: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1657:                 if ($result eq 'ok') {
 1658:                     if (!($perm_reqd eq 'yes')) {
 1659:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1660:                     }
 1661:                 }
 1662:             }
 1663:         }
 1664:     } else {
 1665:         my ($result,$perm_reqd) = 
 1666: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1667:         if ($result eq 'ok') {
 1668:             if (!($perm_reqd eq 'yes')) {
 1669:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1670:             }
 1671:         }
 1672:     }
 1673:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1674: }
 1675: 
 1676: sub retrievestudentphoto {
 1677:     my ($udom,$unam,$ext,$type) = @_;
 1678:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1679:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1680:     if ($ret eq 'ok') {
 1681:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1682:         if ($type eq 'thumbnail') {
 1683:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1684:         }
 1685:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1686:         return $tokenurl;
 1687:     } else {
 1688:         if ($type eq 'thumbnail') {
 1689:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1690:         } else { 
 1691:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1692:         }
 1693:     }
 1694: }
 1695: 
 1696: # -------------------------------------------------------------------- New chat
 1697: 
 1698: sub chatsend {
 1699:     my ($newentry,$anon,$group)=@_;
 1700:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1701:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1702:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1703:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1704: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1705: 		   &escape($newentry)).':'.$group,$chome);
 1706: }
 1707: 
 1708: # ------------------------------------------ Find current version of a resource
 1709: 
 1710: sub getversion {
 1711:     my $fname=&clutter(shift);
 1712:     unless ($fname=~/^\/res\//) { return -1; }
 1713:     return &currentversion(&filelocation('',$fname));
 1714: }
 1715: 
 1716: sub currentversion {
 1717:     my $fname=shift;
 1718:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1719:     if (defined($cached)) { return $result; }
 1720:     my $author=$fname;
 1721:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1722:     my ($udom,$uname)=split(/\//,$author);
 1723:     my $home=homeserver($uname,$udom);
 1724:     if ($home eq 'no_host') { 
 1725:         return -1; 
 1726:     }
 1727:     my $answer=reply("currentversion:$fname",$home);
 1728:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1729: 	return -1;
 1730:     }
 1731:     return &do_cache_new('resversion',$fname,$answer,600);
 1732: }
 1733: 
 1734: # ----------------------------- Subscribe to a resource, return URL if possible
 1735: 
 1736: sub subscribe {
 1737:     my $fname=shift;
 1738:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1739:     $fname=~s/[\n\r]//g;
 1740:     my $author=$fname;
 1741:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1742:     my ($udom,$uname)=split(/\//,$author);
 1743:     my $home=homeserver($uname,$udom);
 1744:     if ($home eq 'no_host') {
 1745:         return 'not_found';
 1746:     }
 1747:     my $answer=reply("sub:$fname",$home);
 1748:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1749: 	$answer.=' by '.$home;
 1750:     }
 1751:     return $answer;
 1752: }
 1753:     
 1754: # -------------------------------------------------------------- Replicate file
 1755: 
 1756: sub repcopy {
 1757:     my $filename=shift;
 1758:     $filename=~s/\/+/\//g;
 1759:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1760:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1761:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1762: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1763: 	return &repcopy_userfile($filename);
 1764:     }
 1765:     $filename=~s/[\n\r]//g;
 1766:     my $transname="$filename.in.transfer";
 1767: # FIXME: this should flock
 1768:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1769:     my $remoteurl=subscribe($filename);
 1770:     if ($remoteurl =~ /^con_lost by/) {
 1771: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1772:            return 'unavailable';
 1773:     } elsif ($remoteurl eq 'not_found') {
 1774: 	   #&logthis("Subscribe returned not_found: $filename");
 1775: 	   return 'not_found';
 1776:     } elsif ($remoteurl =~ /^rejected by/) {
 1777: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1778:            return 'forbidden';
 1779:     } elsif ($remoteurl eq 'directory') {
 1780:            return 'ok';
 1781:     } else {
 1782:         my $author=$filename;
 1783:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1784:         my ($udom,$uname)=split(/\//,$author);
 1785:         my $home=homeserver($uname,$udom);
 1786:         unless ($home eq $perlvar{'lonHostID'}) {
 1787:            my @parts=split(/\//,$filename);
 1788:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1789:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1790:                &logthis("Malconfiguration for replication: $filename");
 1791: 	       return 'bad_request';
 1792:            }
 1793:            my $count;
 1794:            for ($count=5;$count<$#parts;$count++) {
 1795:                $path.="/$parts[$count]";
 1796:                if ((-e $path)!=1) {
 1797: 		   mkdir($path,0777);
 1798:                }
 1799:            }
 1800:            my $ua=new LWP::UserAgent;
 1801:            my $request=new HTTP::Request('GET',"$remoteurl");
 1802:            my $response=$ua->request($request,$transname);
 1803:            if ($response->is_error()) {
 1804: 	       unlink($transname);
 1805:                my $message=$response->status_line;
 1806:                &logthis("<font color=\"blue\">WARNING:"
 1807:                        ." LWP get: $message: $filename</font>");
 1808:                return 'unavailable';
 1809:            } else {
 1810: 	       if ($remoteurl!~/\.meta$/) {
 1811:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1812:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1813:                   if ($mresponse->is_error()) {
 1814: 		      unlink($filename.'.meta');
 1815:                       &logthis(
 1816:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1817:                   }
 1818: 	       }
 1819:                rename($transname,$filename);
 1820:                return 'ok';
 1821:            }
 1822:        }
 1823:     }
 1824: }
 1825: 
 1826: # ------------------------------------------------ Get server side include body
 1827: sub ssi_body {
 1828:     my ($filelink,%form)=@_;
 1829:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1830:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1831:     }
 1832:     my $output='';
 1833:     my $response;
 1834:     if ($filelink=~/^https?\:/) {
 1835:        ($output,$response)=&externalssi($filelink);
 1836:     } else {
 1837:        ($output,$response)=&ssi($filelink,%form);
 1838:     }
 1839:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1840:     $output=~s/^.*?\<body[^\>]*\>//si;
 1841:     $output=~s/\<\/body\s*\>.*?$//si;
 1842:     if (wantarray) {
 1843:         return ($output, $response);
 1844:     } else {
 1845:         return $output;
 1846:     }
 1847: }
 1848: 
 1849: # --------------------------------------------------------- Server Side Include
 1850: 
 1851: sub absolute_url {
 1852:     my ($host_name) = @_;
 1853:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1854:     if ($host_name eq '') {
 1855: 	$host_name = $ENV{'SERVER_NAME'};
 1856:     }
 1857:     return $protocol.$host_name;
 1858: }
 1859: 
 1860: #
 1861: #   Server side include.
 1862: # Parameters:
 1863: #  fn     Possibly encrypted resource name/id.
 1864: #  form   Hash that describes how the rendering should be done
 1865: #         and other things.
 1866: # Returns:
 1867: #   Scalar context: The content of the response.
 1868: #   Array context:  2 element list of the content and the full response object.
 1869: #     
 1870: sub ssi {
 1871: 
 1872:     my ($fn,%form)=@_;
 1873:     my $ua=new LWP::UserAgent;
 1874:     my $request;
 1875: 
 1876:     $form{'no_update_last_known'}=1;
 1877:     &Apache::lonenc::check_encrypt(\$fn);
 1878:     if (%form) {
 1879:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1880:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1881:     } else {
 1882:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1883:     }
 1884: 
 1885:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1886:     my $response=$ua->request($request);
 1887: 
 1888:     if (wantarray) {
 1889: 	return ($response->content, $response);
 1890:     } else {
 1891: 	return $response->content;
 1892:     }
 1893: }
 1894: 
 1895: sub externalssi {
 1896:     my ($url)=@_;
 1897:     my $ua=new LWP::UserAgent;
 1898:     my $request=new HTTP::Request('GET',$url);
 1899:     my $response=$ua->request($request);
 1900:     if (wantarray) {
 1901:         return ($response->content, $response);
 1902:     } else {
 1903:         return $response->content;
 1904:     }
 1905: }
 1906: 
 1907: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1908: 
 1909: sub allowuploaded {
 1910:     my ($srcurl,$url)=@_;
 1911:     $url=&clutter(&declutter($url));
 1912:     my $dir=$url;
 1913:     $dir=~s/\/[^\/]+$//;
 1914:     my %httpref=();
 1915:     my $httpurl=&hreflocation('',$url);
 1916:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1917:     &Apache::lonnet::appenv(\%httpref);
 1918: }
 1919: 
 1920: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1921: # input: action, courseID, current domain, intended
 1922: #        path to file, source of file, instruction to parse file for objects,
 1923: #        ref to hash for embedded objects,
 1924: #        ref to hash for codebase of java objects.
 1925: #
 1926: # output: url to file (if action was uploaddoc), 
 1927: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1928: #
 1929: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1930: # course.
 1931: #
 1932: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1933: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1934: #          course's home server.
 1935: #
 1936: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1937: #          be copied from $source (current location) to 
 1938: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1939: #         and will then be copied to
 1940: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1941: #         course's home server.
 1942: #
 1943: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1944: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1945: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1946: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1947: #         in course's home server.
 1948: #
 1949: 
 1950: sub process_coursefile {
 1951:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1952:     my $fetchresult;
 1953:     my $home=&homeserver($docuname,$docudom);
 1954:     if ($action eq 'propagate') {
 1955:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1956: 			     $home);
 1957:     } else {
 1958:         my $fpath = '';
 1959:         my $fname = $file;
 1960:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1961:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1962:         my $filepath = &build_filepath($fpath);
 1963:         if ($action eq 'copy') {
 1964:             if ($source eq '') {
 1965:                 $fetchresult = 'no source file';
 1966:                 return $fetchresult;
 1967:             } else {
 1968:                 my $destination = $filepath.'/'.$fname;
 1969:                 rename($source,$destination);
 1970:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1971:                                  $home);
 1972:             }
 1973:         } elsif ($action eq 'uploaddoc') {
 1974:             open(my $fh,'>'.$filepath.'/'.$fname);
 1975:             print $fh $env{'form.'.$source};
 1976:             close($fh);
 1977:             if ($parser eq 'parse') {
 1978:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 1979:                 unless ($parse_result eq 'ok') {
 1980:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1981:                 }
 1982:             }
 1983:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1984:                                  $home);
 1985:             if ($fetchresult eq 'ok') {
 1986:                 return '/uploaded/'.$fpath.'/'.$fname;
 1987:             } else {
 1988:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1989:                         ' to host '.$home.': '.$fetchresult);
 1990:                 return '/adm/notfound.html';
 1991:             }
 1992:         }
 1993:     }
 1994:     unless ( $fetchresult eq 'ok') {
 1995:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1996:              ' to host '.$home.': '.$fetchresult);
 1997:     }
 1998:     return $fetchresult;
 1999: }
 2000: 
 2001: sub build_filepath {
 2002:     my ($fpath) = @_;
 2003:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2004:     unless ($fpath eq '') {
 2005:         my @parts=split('/',$fpath);
 2006:         foreach my $part (@parts) {
 2007:             $filepath.= '/'.$part;
 2008:             if ((-e $filepath)!=1) {
 2009:                 mkdir($filepath,0777);
 2010:             }
 2011:         }
 2012:     }
 2013:     return $filepath;
 2014: }
 2015: 
 2016: sub store_edited_file {
 2017:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2018:     my $file = $primary_url;
 2019:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2020:     my $fpath = '';
 2021:     my $fname = $file;
 2022:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2023:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2024:     my $filepath = &build_filepath($fpath);
 2025:     open(my $fh,'>'.$filepath.'/'.$fname);
 2026:     print $fh $content;
 2027:     close($fh);
 2028:     my $home=&homeserver($docuname,$docudom);
 2029:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2030: 			  $home);
 2031:     if ($$fetchresult eq 'ok') {
 2032:         return '/uploaded/'.$fpath.'/'.$fname;
 2033:     } else {
 2034:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2035: 		 ' to host '.$home.': '.$$fetchresult);
 2036:         return '/adm/notfound.html';
 2037:     }
 2038: }
 2039: 
 2040: sub clean_filename {
 2041:     my ($fname,$args)=@_;
 2042: # Replace Windows backslashes by forward slashes
 2043:     $fname=~s/\\/\//g;
 2044:     if (!$args->{'keep_path'}) {
 2045:         # Get rid of everything but the actual filename
 2046: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2047:     }
 2048: # Replace spaces by underscores
 2049:     $fname=~s/\s+/\_/g;
 2050: # Replace all other weird characters by nothing
 2051:     $fname=~s{[^/\w\.\-]}{}g;
 2052: # Replace all .\d. sequences with _\d. so they no longer look like version
 2053: # numbers
 2054:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2055:     return $fname;
 2056: }
 2057: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
 2058: sub resizeImage {
 2059: 	my($img_url) = @_;	
 2060: 	my $ima = Image::Magick->new;                       
 2061:         $ima->Read($img_url);
 2062: 	if($ima->Get('width') > 400)
 2063: 	{
 2064: 		my $factor = $ima->Get('width')/400;
 2065:              	$ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
 2066: 	}
 2067: 	if($ima->Get('height') > 500)
 2068:         {
 2069:         	my $factor = $ima->Get('height')/500;
 2070:                 $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
 2071:         } 
 2072: 		
 2073: 	$ima->Write($img_url);
 2074: }
 2075: 
 2076: #Wrapper function for userphotoupload
 2077: sub userphotoupload
 2078: {
 2079: 	my($formname,$subdir) = @_;
 2080: 	$upload_photo_form = 1;
 2081: 	return &userfileupload($formname,undef,$subdir);
 2082: }
 2083: 
 2084: # --------------- Take an uploaded file and put it into the userfiles directory
 2085: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2086: #                    the desired filenam is in $env{"form.$formname.filename"}
 2087: #        $coursedoc - if true up to the current course
 2088: #                     if false
 2089: #        $subdir - directory in userfile to store the file into
 2090: #        $parser - instruction to parse file for objects ($parser = parse)    
 2091: #        $allfiles - reference to hash for embedded objects
 2092: #        $codebase - reference to hash for codebase of java objects
 2093: #        $desuname - username for permanent storage of uploaded file
 2094: #        $dsetudom - domain for permanaent storage of uploaded file
 2095: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2096: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2097: # 
 2098: # output: url of file in userspace, or error: <message> 
 2099: #             or /adm/notfound.html if failure to upload occurse
 2100: 
 2101: 
 2102: sub userfileupload {
 2103:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 2104:         $destudom,$thumbwidth,$thumbheight)=@_;
 2105:     if (!defined($subdir)) { $subdir='unknown'; }
 2106:     my $fname=$env{'form.'.$formname.'.filename'};
 2107:     $fname=&clean_filename($fname);
 2108: # See if there is anything left
 2109:     unless ($fname) { return 'error: no uploaded file'; }
 2110:     chop($env{'form.'.$formname});
 2111:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 2112:         my $now = time;
 2113:         my $filepath = 'tmp/helprequests/'.$now;
 2114:         my @parts=split(/\//,$filepath);
 2115:         my $fullpath = $perlvar{'lonDaemons'};
 2116:         for (my $i=0;$i<@parts;$i++) {
 2117:             $fullpath .= '/'.$parts[$i];
 2118:             if ((-e $fullpath)!=1) {
 2119:                 mkdir($fullpath,0777);
 2120:             }
 2121:         }
 2122:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2123:         print $fh $env{'form.'.$formname};
 2124:         close($fh);
 2125:         return $fullpath.'/'.$fname;
 2126:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 2127:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2128:                        '_'.$env{'user.domain'}.'/pending';
 2129:         my @parts=split(/\//,$filepath);
 2130:         my $fullpath = $perlvar{'lonDaemons'};
 2131:         for (my $i=0;$i<@parts;$i++) {
 2132:             $fullpath .= '/'.$parts[$i];
 2133:             if ((-e $fullpath)!=1) {
 2134:                 mkdir($fullpath,0777);
 2135:             }
 2136:         }
 2137:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2138:         print $fh $env{'form.'.$formname};
 2139:         close($fh);
 2140:         return $fullpath.'/'.$fname;
 2141:     }
 2142:     
 2143: # Create the directory if not present
 2144:     $fname="$subdir/$fname";
 2145:     if ($coursedoc) {
 2146: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2147: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2148:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2149:             return &finishuserfileupload($docuname,$docudom,
 2150: 					 $formname,$fname,$parser,$allfiles,
 2151: 					 $codebase,$thumbwidth,$thumbheight);
 2152:         } else {
 2153:             $fname=$env{'form.folder'}.'/'.$fname;
 2154:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2155: 				       $fname,$formname,$parser,
 2156: 				       $allfiles,$codebase);
 2157:         }
 2158:     } elsif (defined($destuname)) {
 2159:         my $docuname=$destuname;
 2160:         my $docudom=$destudom;
 2161: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2162: 				     $parser,$allfiles,$codebase,
 2163:                                      $thumbwidth,$thumbheight);
 2164:         
 2165:     } else {
 2166:         my $docuname=$env{'user.name'};
 2167:         my $docudom=$env{'user.domain'};
 2168:         if (exists($env{'form.group'})) {
 2169:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2170:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2171:         }
 2172: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2173: 				     $parser,$allfiles,$codebase,
 2174:                                      $thumbwidth,$thumbheight);
 2175:     }
 2176: }
 2177: 
 2178: sub finishuserfileupload {
 2179:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2180:         $thumbwidth,$thumbheight) = @_;
 2181:     my $path=$docudom.'/'.$docuname.'/';
 2182:     my $filepath=$perlvar{'lonDocRoot'};
 2183:   
 2184:     my ($fnamepath,$file,$fetchthumb);
 2185:     $file=$fname;
 2186:     if ($fname=~m|/|) {
 2187:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2188: 	$path.=$fnamepath.'/';
 2189:     }
 2190:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2191:     my $count;
 2192:     for ($count=4;$count<=$#parts;$count++) {
 2193:         $filepath.="/$parts[$count]";
 2194:         if ((-e $filepath)!=1) {
 2195: 	    mkdir($filepath,0777);
 2196:         }
 2197:     }
 2198: 
 2199: # Save the file
 2200:     {
 2201: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2202: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2203: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2204: 	    return '/adm/notfound.html';
 2205: 	}
 2206: 	if (!print FH ($env{'form.'.$formname})) {
 2207: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2208: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2209: 	    return '/adm/notfound.html';
 2210: 	}
 2211: 	close(FH);
 2212: 	if($upload_photo_form==1)
 2213: 	{
 2214: 		resizeImage($filepath.'/'.$file);		
 2215: 		$upload_photo_form = 0;
 2216: 	}
 2217:     }
 2218:     if ($parser eq 'parse') {
 2219:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
 2220: 						   $codebase);
 2221:         unless ($parse_result eq 'ok') {
 2222:             &logthis('Failed to parse '.$filepath.$file.
 2223: 		     ' for embedded media: '.$parse_result); 
 2224:         }
 2225:     }
 2226:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2227:         my $input = $filepath.'/'.$file;
 2228:         my $output = $filepath.'/'.'tn-'.$file;
 2229:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2230:         system("convert -sample $thumbsize $input $output");
 2231:         if (-e $filepath.'/'.'tn-'.$file) {
 2232:             $fetchthumb  = 1; 
 2233:         }
 2234:     }
 2235:  
 2236: # Notify homeserver to grep it
 2237: #
 2238:     my $docuhome=&homeserver($docuname,$docudom);	
 2239:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2240:     if ($fetchresult eq 'ok') {
 2241:         if ($fetchthumb) {
 2242:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2243:             if ($thumbresult ne 'ok') {
 2244:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2245:                          $docuhome.': '.$thumbresult);
 2246:             }
 2247:         }
 2248: #
 2249: # Return the URL to it
 2250:         return '/uploaded/'.$path.$file;
 2251:     } else {
 2252:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2253: 		 ': '.$fetchresult);
 2254:         return '/adm/notfound.html';
 2255:     }
 2256: }
 2257: 
 2258: sub extract_embedded_items {
 2259:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 2260:     my @state = ();
 2261:     my %javafiles = (
 2262:                       codebase => '',
 2263:                       code => '',
 2264:                       archive => ''
 2265:                     );
 2266:     my %mediafiles = (
 2267:                       src => '',
 2268:                       movie => '',
 2269:                      );
 2270:     my $p;
 2271:     if ($content) {
 2272:         $p = HTML::LCParser->new($content);
 2273:     } else {
 2274:         $p = HTML::LCParser->new($fullpath);
 2275:     }
 2276:     while (my $t=$p->get_token()) {
 2277: 	if ($t->[0] eq 'S') {
 2278: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2279: 	    push(@state, $tagname);
 2280:             if (lc($tagname) eq 'allow') {
 2281:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2282:             }
 2283: 	    if (lc($tagname) eq 'img') {
 2284: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2285: 	    }
 2286: 	    if (lc($tagname) eq 'a') {
 2287: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2288: 	    }
 2289:             if (lc($tagname) eq 'script') {
 2290:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2291:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2292:                 } else {
 2293:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2294:                 }
 2295:             }
 2296:             if (lc($tagname) eq 'link') {
 2297:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2298:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2299:                 }
 2300:             }
 2301: 	    if (lc($tagname) eq 'object' ||
 2302: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2303: 		foreach my $item (keys(%javafiles)) {
 2304: 		    $javafiles{$item} = '';
 2305: 		}
 2306: 	    }
 2307: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2308: 		my $name = lc($attr->{'name'});
 2309: 		foreach my $item (keys(%javafiles)) {
 2310: 		    if ($name eq $item) {
 2311: 			$javafiles{$item} = $attr->{'value'};
 2312: 			last;
 2313: 		    }
 2314: 		}
 2315: 		foreach my $item (keys(%mediafiles)) {
 2316: 		    if ($name eq $item) {
 2317: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2318: 			last;
 2319: 		    }
 2320: 		}
 2321: 	    }
 2322: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2323: 		foreach my $item (keys(%javafiles)) {
 2324: 		    if ($attr->{$item}) {
 2325: 			$javafiles{$item} = $attr->{$item};
 2326: 			last;
 2327: 		    }
 2328: 		}
 2329: 		foreach my $item (keys(%mediafiles)) {
 2330: 		    if ($attr->{$item}) {
 2331: 			&add_filetype($allfiles,$attr->{$item},$item);
 2332: 			last;
 2333: 		    }
 2334: 		}
 2335: 	    }
 2336: 	} elsif ($t->[0] eq 'E') {
 2337: 	    my ($tagname) = ($t->[1]);
 2338: 	    if ($javafiles{'codebase'} ne '') {
 2339: 		$javafiles{'codebase'} .= '/';
 2340: 	    }  
 2341: 	    if (lc($tagname) eq 'applet' ||
 2342: 		lc($tagname) eq 'object' ||
 2343: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2344: 		) {
 2345: 		foreach my $item (keys(%javafiles)) {
 2346: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2347: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2348: 			&add_filetype($allfiles,$file,$item);
 2349: 		    }
 2350: 		}
 2351: 	    } 
 2352: 	    pop @state;
 2353: 	}
 2354:     }
 2355:     return 'ok';
 2356: }
 2357: 
 2358: sub add_filetype {
 2359:     my ($allfiles,$file,$type)=@_;
 2360:     if (exists($allfiles->{$file})) {
 2361: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2362: 	    push(@{$allfiles->{$file}}, &escape($type));
 2363: 	}
 2364:     } else {
 2365: 	@{$allfiles->{$file}} = (&escape($type));
 2366:     }
 2367: }
 2368: 
 2369: sub removeuploadedurl {
 2370:     my ($url)=@_;	
 2371:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 2372:     return &removeuserfile($uname,$udom,$fname);
 2373: }
 2374: 
 2375: sub removeuserfile {
 2376:     my ($docuname,$docudom,$fname)=@_;
 2377:     my $home=&homeserver($docuname,$docudom);    
 2378:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2379:     if ($result eq 'ok') {	
 2380:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2381:             my $metafile = $fname.'.meta';
 2382:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2383: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2384:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 2385:             my $sqlresult = 
 2386:                 &update_portfolio_table($docuname,$docudom,$file,
 2387:                                         'portfolio_metadata',$group,
 2388:                                         'delete');
 2389:         }
 2390:     }
 2391:     return $result;
 2392: }
 2393: 
 2394: sub mkdiruserfile {
 2395:     my ($docuname,$docudom,$dir)=@_;
 2396:     my $home=&homeserver($docuname,$docudom);
 2397:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2398: }
 2399: 
 2400: sub renameuserfile {
 2401:     my ($docuname,$docudom,$old,$new)=@_;
 2402:     my $home=&homeserver($docuname,$docudom);
 2403:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2404:                         &escape("$old").':'.&escape("$new"),$home);
 2405:     if ($result eq 'ok') {
 2406:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2407:             my $oldmeta = $old.'.meta';
 2408:             my $newmeta = $new.'.meta';
 2409:             my $metaresult = 
 2410:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2411: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2412:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2413:             my $sqlresult = 
 2414:                 &update_portfolio_table($docuname,$docudom,$file,
 2415:                                         'portfolio_metadata',$group,
 2416:                                         'delete');
 2417:         }
 2418:     }
 2419:     return $result;
 2420: }
 2421: 
 2422: # ------------------------------------------------------------------------- Log
 2423: 
 2424: sub log {
 2425:     my ($dom,$nam,$hom,$what)=@_;
 2426:     return critical("log:$dom:$nam:$what",$hom);
 2427: }
 2428: 
 2429: # ------------------------------------------------------------------ Course Log
 2430: #
 2431: # This routine flushes several buffers of non-mission-critical nature
 2432: #
 2433: 
 2434: sub flushcourselogs {
 2435:     &logthis('Flushing log buffers');
 2436: #
 2437: # course logs
 2438: # This is a log of all transactions in a course, which can be used
 2439: # for data mining purposes
 2440: #
 2441: # It also collects the courseid database, which lists last transaction
 2442: # times and course titles for all courseids
 2443: #
 2444:     my %courseidbuffer=();
 2445:     foreach my $crsid (keys(%courselogs)) {
 2446:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2447: 		          &escape($courselogs{$crsid}),
 2448: 		          $coursehombuf{$crsid}) eq 'ok') {
 2449: 	    delete $courselogs{$crsid};
 2450:         } else {
 2451:             &logthis('Failed to flush log buffer for '.$crsid);
 2452:             if (length($courselogs{$crsid})>40000) {
 2453:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2454:                         " exceeded maximum size, deleting.</font>");
 2455:                delete $courselogs{$crsid};
 2456:             }
 2457:         }
 2458:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2459:             'description' => $coursedescrbuf{$crsid},
 2460:             'inst_code'    => $courseinstcodebuf{$crsid},
 2461:             'type'        => $coursetypebuf{$crsid},
 2462:             'owner'       => $courseownerbuf{$crsid},
 2463:         };
 2464:     }
 2465: #
 2466: # Write course id database (reverse lookup) to homeserver of courses 
 2467: # Is used in pickcourse
 2468: #
 2469:     foreach my $crs_home (keys(%courseidbuffer)) {
 2470:         my $response = &courseidput(&host_domain($crs_home),
 2471:                                     $courseidbuffer{$crs_home},
 2472:                                     $crs_home,'timeonly');
 2473:     }
 2474: #
 2475: # File accesses
 2476: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2477: #
 2478:     foreach my $entry (keys(%accesshash)) {
 2479:         if ($entry =~ /___count$/) {
 2480:             my ($dom,$name);
 2481:             ($dom,$name,undef)=
 2482: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2483:             if (! defined($dom) || $dom eq '' || 
 2484:                 ! defined($name) || $name eq '') {
 2485:                 my $cid = $env{'request.course.id'};
 2486:                 $dom  = $env{'request.'.$cid.'.domain'};
 2487:                 $name = $env{'request.'.$cid.'.num'};
 2488:             }
 2489:             my $value = $accesshash{$entry};
 2490:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2491:             my %temphash=($url => $value);
 2492:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2493:             if ($result eq 'ok') {
 2494:                 delete $accesshash{$entry};
 2495:             } elsif ($result eq 'unknown_cmd') {
 2496:                 # Target server has old code running on it.
 2497:                 my %temphash=($entry => $value);
 2498:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2499:                     delete $accesshash{$entry};
 2500:                 }
 2501:             }
 2502:         } else {
 2503:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2504:             my %temphash=($entry => $accesshash{$entry});
 2505:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2506:                 delete $accesshash{$entry};
 2507:             }
 2508:         }
 2509:     }
 2510: #
 2511: # Roles
 2512: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2513: #
 2514:     foreach my $entry (keys(%userrolehash)) {
 2515:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2516: 	    split(/\:/,$entry);
 2517:         if (&Apache::lonnet::put('nohist_userroles',
 2518:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2519:                 $rudom,$runame) eq 'ok') {
 2520: 	    delete $userrolehash{$entry};
 2521:         }
 2522:     }
 2523: #
 2524: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2525: #
 2526:     my %domrolebuffer = ();
 2527:     foreach my $entry (keys %domainrolehash) {
 2528:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2529:         if ($domrolebuffer{$rudom}) {
 2530:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2531:                       '='.&escape($domainrolehash{$entry});
 2532:         } else {
 2533:             $domrolebuffer{$rudom}.=&escape($entry).
 2534:                       '='.&escape($domainrolehash{$entry});
 2535:         }
 2536:         delete $domainrolehash{$entry};
 2537:     }
 2538:     foreach my $dom (keys(%domrolebuffer)) {
 2539: 	my %servers = &get_servers($dom,'library');
 2540: 	foreach my $tryserver (keys(%servers)) {
 2541: 	    unless (&reply('domroleput:'.$dom.':'.
 2542: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2543: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2544: 	    }
 2545:         }
 2546:     }
 2547:     $dumpcount++;
 2548: }
 2549: 
 2550: sub courselog {
 2551:     my $what=shift;
 2552:     $what=time.':'.$what;
 2553:     unless ($env{'request.course.id'}) { return ''; }
 2554:     $coursedombuf{$env{'request.course.id'}}=
 2555:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2556:     $coursenumbuf{$env{'request.course.id'}}=
 2557:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2558:     $coursehombuf{$env{'request.course.id'}}=
 2559:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2560:     $coursedescrbuf{$env{'request.course.id'}}=
 2561:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2562:     $courseinstcodebuf{$env{'request.course.id'}}=
 2563:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2564:     $courseownerbuf{$env{'request.course.id'}}=
 2565:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2566:     $coursetypebuf{$env{'request.course.id'}}=
 2567:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2568:     if (defined $courselogs{$env{'request.course.id'}}) {
 2569: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2570:     } else {
 2571: 	$courselogs{$env{'request.course.id'}}.=$what;
 2572:     }
 2573:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2574: 	&flushcourselogs();
 2575:     }
 2576: }
 2577: 
 2578: sub courseacclog {
 2579:     my $fnsymb=shift;
 2580:     unless ($env{'request.course.id'}) { return ''; }
 2581:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2582:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2583:         $what.=':POST';
 2584:         # FIXME: Probably ought to escape things....
 2585: 	foreach my $key (keys(%env)) {
 2586:             if ($key=~/^form\.(.*)/) {
 2587:                 my $formitem = $1;
 2588:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 2589:                     $what.=':'.$formitem.'='.$env{$key};
 2590:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 2591:                     $what.=':'.$formitem.'='.$env{$key};
 2592:                 }
 2593:             }
 2594:         }
 2595:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2596:         # FIXME: We should not be depending on a form parameter that someone
 2597:         # editing lonsearchcat.pm might change in the future.
 2598:         if ($env{'form.phase'} eq 'course_search') {
 2599:             $what.= ':POST';
 2600:             # FIXME: Probably ought to escape things....
 2601:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2602:                                  'crsdiscuss') {
 2603:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2604:             }
 2605:         }
 2606:     }
 2607:     &courselog($what);
 2608: }
 2609: 
 2610: sub countacc {
 2611:     my $url=&declutter(shift);
 2612:     return if (! defined($url) || $url eq '');
 2613:     unless ($env{'request.course.id'}) { return ''; }
 2614:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2615:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2616:     $accesshash{$key}++;
 2617: }
 2618: 
 2619: sub linklog {
 2620:     my ($from,$to)=@_;
 2621:     $from=&declutter($from);
 2622:     $to=&declutter($to);
 2623:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2624:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2625: }
 2626:   
 2627: sub userrolelog {
 2628:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2629:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2630:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2631:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2632:         ($trole=~/^ta/)) {
 2633:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2634:        $userrolehash
 2635:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2636:                     =$tend.':'.$tstart;
 2637:     }
 2638:     if (($env{'request.role'} =~ /dc\./) &&
 2639: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2640: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2641: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
 2642:        $userrolehash
 2643:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2644:                     =$tend.':'.$tstart;
 2645:     }
 2646:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2647:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2648:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2649:         ($trole=~/^sc/)) {
 2650:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2651:        $domainrolehash
 2652:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2653:                     = $tend.':'.$tstart;
 2654:     }
 2655: }
 2656: 
 2657: sub courserolelog {
 2658:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 2659:     if (($trole eq 'cc') || ($trole eq 'in') ||
 2660:         ($trole eq 'ep') || ($trole eq 'ad') ||
 2661:         ($trole eq 'ta') || ($trole eq 'st') ||
 2662:         ($trole=~/^cr/) || ($trole eq 'gr')) {
 2663:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 2664:             my $cdom = $1;
 2665:             my $cnum = $2;
 2666:             my $sec = $3;
 2667:             my $namespace = 'rolelog';
 2668:             my %storehash = (
 2669:                                role    => $trole,
 2670:                                start   => $tstart,
 2671:                                end     => $tend,
 2672:                                selfenroll => $selfenroll,
 2673:                                context    => $context,
 2674:                             );
 2675:             if ($trole eq 'gr') {
 2676:                 $namespace = 'groupslog';
 2677:                 $storehash{'group'} = $sec;
 2678:             } else {
 2679:                 $storehash{'section'} = $sec;
 2680:             }
 2681:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 2682:         }
 2683:     }
 2684:     return;
 2685: }
 2686: 
 2687: sub get_course_adv_roles {
 2688:     my ($cid,$codes) = @_;
 2689:     $cid=$env{'request.course.id'} unless (defined($cid));
 2690:     my %coursehash=&coursedescription($cid);
 2691:     my $crstype = &Apache::loncommon::course_type($cid);
 2692:     my %nothide=();
 2693:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2694:         if ($user !~ /:/) {
 2695: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2696:         } else {
 2697:             $nothide{$user}=1;
 2698:         }
 2699:     }
 2700:     my %returnhash=();
 2701:     my %dumphash=
 2702:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2703:     my $now=time;
 2704:     foreach my $entry (keys %dumphash) {
 2705: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2706:         if (($tstart) && ($tstart<0)) { next; }
 2707:         if (($tend) && ($tend<$now)) { next; }
 2708:         if (($tstart) && ($now<$tstart)) { next; }
 2709:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2710: 	if ($username eq '' || $domain eq '') { next; }
 2711: 	if ((&privileged($username,$domain)) && 
 2712: 	    (!$nothide{$username.':'.$domain})) { next; }
 2713: 	if ($role eq 'cr') { next; }
 2714:         if ($codes) {
 2715:             if ($section) { $role .= ':'.$section; }
 2716:             if ($returnhash{$role}) {
 2717:                 $returnhash{$role}.=','.$username.':'.$domain;
 2718:             } else {
 2719:                 $returnhash{$role}=$username.':'.$domain;
 2720:             }
 2721:         } else {
 2722:             my $key=&plaintext($role,$crstype);
 2723:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 2724:             if ($returnhash{$key}) {
 2725: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2726:             } else {
 2727:                 $returnhash{$key}=$username.':'.$domain;
 2728:             }
 2729:         }
 2730:     }
 2731:     return %returnhash;
 2732: }
 2733: 
 2734: sub get_my_roles {
 2735:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2736:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2737:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2738:     my (%dumphash,%nothide);
 2739:     if ($context eq 'userroles') { 
 2740:         %dumphash = &dump('roles',$udom,$uname);
 2741:     } else {
 2742:         %dumphash=
 2743:             &dump('nohist_userroles',$udom,$uname);
 2744:         if ($hidepriv) {
 2745:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2746:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2747:                 if ($user !~ /:/) {
 2748:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2749:                 } else {
 2750:                     $nothide{$user} = 1;
 2751:                 }
 2752:             }
 2753:         }
 2754:     }
 2755:     my %returnhash=();
 2756:     my $now=time;
 2757:     foreach my $entry (keys(%dumphash)) {
 2758:         my ($role,$tend,$tstart);
 2759:         if ($context eq 'userroles') {
 2760: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2761:         } else {
 2762:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2763:         }
 2764:         if (($tstart) && ($tstart<0)) { next; }
 2765:         my $status = 'active';
 2766:         if (($tend) && ($tend<=$now)) {
 2767:             $status = 'previous';
 2768:         } 
 2769:         if (($tstart) && ($now<$tstart)) {
 2770:             $status = 'future';
 2771:         }
 2772:         if (ref($types) eq 'ARRAY') {
 2773:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2774:                 next;
 2775:             } 
 2776:         } else {
 2777:             if ($status ne 'active') {
 2778:                 next;
 2779:             }
 2780:         }
 2781:         my ($rolecode,$username,$domain,$section,$area);
 2782:         if ($context eq 'userroles') {
 2783:             ($area,$rolecode) = split(/_/,$entry);
 2784:             (undef,$domain,$username,$section) = split(/\//,$area);
 2785:         } else {
 2786:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2787:         }
 2788:         if (ref($roledoms) eq 'ARRAY') {
 2789:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2790:                 next;
 2791:             }
 2792:         }
 2793:         if (ref($roles) eq 'ARRAY') {
 2794:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2795:                 if ($role =~ /^cr\//) {
 2796:                     if (!grep(/^cr$/,@{$roles})) {
 2797:                         next;
 2798:                     }
 2799:                 } else {
 2800:                     next;
 2801:                 }
 2802:             }
 2803:         }
 2804:         if ($hidepriv) {
 2805:             if ((&privileged($username,$domain)) &&
 2806:                 (!$nothide{$username.':'.$domain})) { 
 2807:                 next;
 2808:             }
 2809:         }
 2810:         if ($withsec) {
 2811:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2812:                 $tstart.':'.$tend;
 2813:         } else {
 2814:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2815:         }
 2816:     }
 2817:     return %returnhash;
 2818: }
 2819: 
 2820: # ----------------------------------------------------- Frontpage Announcements
 2821: #
 2822: #
 2823: 
 2824: sub postannounce {
 2825:     my ($server,$text)=@_;
 2826:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2827:     unless ($text=~/\w/) { $text=''; }
 2828:     return &reply('setannounce:'.&escape($text),$server);
 2829: }
 2830: 
 2831: sub getannounce {
 2832: 
 2833:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2834: 	my $announcement='';
 2835: 	while (my $line = <$fh>) { $announcement .= $line; }
 2836: 	close($fh);
 2837: 	if ($announcement=~/\w/) { 
 2838: 	    return 
 2839:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2840:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2841: 	} else {
 2842: 	    return '';
 2843: 	}
 2844:     } else {
 2845: 	return '';
 2846:     }
 2847: }
 2848: 
 2849: # ---------------------------------------------------------- Course ID routines
 2850: # Deal with domain's nohist_courseid.db files
 2851: #
 2852: 
 2853: sub courseidput {
 2854:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2855:     my $outcome;
 2856:     if ($caller eq 'timeonly') {
 2857:         my $cids = '';
 2858:         foreach my $item (keys(%$storehash)) {
 2859:             $cids.=&escape($item).'&';
 2860:         }
 2861:         $cids=~s/\&$//;
 2862:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 2863:                           $coursehome);       
 2864:     } else {
 2865:         my $items = '';
 2866:         foreach my $item (keys(%$storehash)) {
 2867:             $items.= &escape($item).'='.
 2868:                      &freeze_escape($$storehash{$item}).'&';
 2869:         }
 2870:         $items=~s/\&$//;
 2871:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 2872:                           $coursehome);
 2873:     }
 2874:     if ($outcome eq 'unknown_cmd') {
 2875:         my $what;
 2876:         foreach my $cid (keys(%$storehash)) {
 2877:             $what .= &escape($cid).'=';
 2878:             foreach my $item ('description','inst_code','owner','type') {
 2879:                 $what .= &escape($storehash->{$cid}{$item}).':';
 2880:             }
 2881:             $what =~ s/\:$/&/;
 2882:         }
 2883:         $what =~ s/\&$//;  
 2884:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2885:     } else {
 2886:         return $outcome;
 2887:     }
 2888: }
 2889: 
 2890: sub courseiddump {
 2891:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 2892:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 2893:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
 2894:     my $as_hash = 1;
 2895:     my %returnhash;
 2896:     if (!$domfilter) { $domfilter=''; }
 2897:     my %libserv = &all_library();
 2898:     foreach my $tryserver (keys(%libserv)) {
 2899:         if ( (  $hostidflag == 1 
 2900: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2901: 	     || (!defined($hostidflag)) ) {
 2902: 
 2903: 	    if (($domfilter eq '') ||
 2904: 		(&host_domain($tryserver) eq $domfilter)) {
 2905:                 my $rep = 
 2906:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 2907:                          $sincefilter.':'.&escape($descfilter).':'.
 2908:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 2909:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 2910:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 2911:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 2912:                          $showhidden.':'.$caller,$tryserver);
 2913:                 my @pairs=split(/\&/,$rep);
 2914:                 foreach my $item (@pairs) {
 2915:                     my ($key,$value)=split(/\=/,$item,2);
 2916:                     $key = &unescape($key);
 2917:                     next if ($key =~ /^error: 2 /);
 2918:                     my $result = &thaw_unescape($value);
 2919:                     if (ref($result) eq 'HASH') {
 2920:                         $returnhash{$key}=$result;
 2921:                     } else {
 2922:                         my @responses = split(/:/,$value);
 2923:                         my @items = ('description','inst_code','owner','type');
 2924:                         for (my $i=0; $i<@responses; $i++) {
 2925:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 2926:                         }
 2927:                     } 
 2928:                 }
 2929:             }
 2930:         }
 2931:     }
 2932:     return %returnhash;
 2933: }
 2934: 
 2935: # ---------------------------------------------------------- DC e-mail
 2936: 
 2937: sub dcmailput {
 2938:     my ($domain,$msgid,$message,$server)=@_;
 2939:     my $status = &Apache::lonnet::critical(
 2940:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2941:        &escape($message),$server);
 2942:     return $status;
 2943: }
 2944: 
 2945: sub dcmaildump {
 2946:     my ($dom,$startdate,$enddate,$senders) = @_;
 2947:     my %returnhash=();
 2948: 
 2949:     if (defined(&domain($dom,'primary'))) {
 2950:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2951:                                                          &escape($enddate).':';
 2952: 	my @esc_senders=map { &escape($_)} @$senders;
 2953: 	$cmd.=&escape(join('&',@esc_senders));
 2954: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2955:             my ($key,$value) = split(/\=/,$line,2);
 2956:             if (($key) && ($value)) {
 2957:                 $returnhash{&unescape($key)} = &unescape($value);
 2958:             }
 2959:         }
 2960:     }
 2961:     return %returnhash;
 2962: }
 2963: # ---------------------------------------------------------- Domain roles
 2964: 
 2965: sub get_domain_roles {
 2966:     my ($dom,$roles,$startdate,$enddate)=@_;
 2967:     if (undef($startdate) || $startdate eq '') {
 2968:         $startdate = '.';
 2969:     }
 2970:     if (undef($enddate) || $enddate eq '') {
 2971:         $enddate = '.';
 2972:     }
 2973:     my $rolelist;
 2974:     if (ref($roles) eq 'ARRAY') {
 2975:         $rolelist = join(':',@{$roles});
 2976:     }
 2977:     my %personnel = ();
 2978: 
 2979:     my %servers = &get_servers($dom,'library');
 2980:     foreach my $tryserver (keys(%servers)) {
 2981: 	%{$personnel{$tryserver}}=();
 2982: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2983: 					    &escape($startdate).':'.
 2984: 					    &escape($enddate).':'.
 2985: 					    &escape($rolelist), $tryserver))) {
 2986: 	    my ($key,$value) = split(/\=/,$line,2);
 2987: 	    if (($key) && ($value)) {
 2988: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2989: 	    }
 2990: 	}
 2991:     }
 2992:     return %personnel;
 2993: }
 2994: 
 2995: # ----------------------------------------------------------- Check out an item
 2996: 
 2997: sub get_first_access {
 2998:     my ($type,$argsymb)=@_;
 2999:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3000:     if ($argsymb) { $symb=$argsymb; }
 3001:     my ($map,$id,$res)=&decode_symb($symb);
 3002:     if ($type eq 'course') {
 3003: 	$res='course';
 3004:     } elsif ($type eq 'map') {
 3005: 	$res=&symbread($map);
 3006:     } else {
 3007: 	$res=$symb;
 3008:     }
 3009:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 3010:     return $times{"$courseid\0$res"};
 3011: }
 3012: 
 3013: sub set_first_access {
 3014:     my ($type)=@_;
 3015:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3016:     my ($map,$id,$res)=&decode_symb($symb);
 3017:     if ($type eq 'course') {
 3018: 	$res='course';
 3019:     } elsif ($type eq 'map') {
 3020: 	$res=&symbread($map);
 3021:     } else {
 3022: 	$res=$symb;
 3023:     }
 3024:     my $firstaccess=&get_first_access($type,$symb);
 3025:     if (!$firstaccess) {
 3026: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 3027:     }
 3028:     return 'already_set';
 3029: }
 3030: 
 3031: sub checkout {
 3032:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 3033:     my $now=time;
 3034:     my $lonhost=$perlvar{'lonHostID'};
 3035:     my $infostr=&escape(
 3036:                  'CHECKOUTTOKEN&'.
 3037:                  $tuname.'&'.
 3038:                  $tudom.'&'.
 3039:                  $tcrsid.'&'.
 3040:                  $symb.'&'.
 3041: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 3042:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 3043:     if ($token=~/^error\:/) { 
 3044:         &logthis("<font color=\"blue\">WARNING: ".
 3045:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 3046:                  "</font>");
 3047:         return ''; 
 3048:     }
 3049: 
 3050:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 3051:     $token=~tr/a-z/A-Z/;
 3052: 
 3053:     my %infohash=('resource.0.outtoken' => $token,
 3054:                   'resource.0.checkouttime' => $now,
 3055:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 3056: 
 3057:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3058:        return '';
 3059:     } else {
 3060:         &logthis("<font color=\"blue\">WARNING: ".
 3061:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 3062:                  "</font>");
 3063:     }    
 3064: 
 3065:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3066:                          &escape('Checkout '.$infostr.' - '.
 3067:                                                  $token)) ne 'ok') {
 3068: 	return '';
 3069:     } else {
 3070:         &logthis("<font color=\"blue\">WARNING: ".
 3071:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 3072:                  "</font>");
 3073:     }
 3074:     return $token;
 3075: }
 3076: 
 3077: # ------------------------------------------------------------ Check in an item
 3078: 
 3079: sub checkin {
 3080:     my $token=shift;
 3081:     my $now=time;
 3082:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 3083:     $lonhost=~tr/A-Z/a-z/;
 3084:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 3085:     $dtoken=~s/\W/\_/g;
 3086:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 3087:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 3088: 
 3089:     unless (($tuname) && ($tudom)) {
 3090:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 3091:         return '';
 3092:     }
 3093:     
 3094:     unless (&allowed('mgr',$tcrsid)) {
 3095:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 3096:                  $env{'user.name'}.' - '.$env{'user.domain'});
 3097:         return '';
 3098:     }
 3099: 
 3100:     my %infohash=('resource.0.intoken' => $token,
 3101:                   'resource.0.checkintime' => $now,
 3102:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 3103: 
 3104:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3105:        return '';
 3106:     }    
 3107: 
 3108:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3109:                          &escape('Checkin - '.$token)) ne 'ok') {
 3110: 	return '';
 3111:     }
 3112: 
 3113:     return ($symb,$tuname,$tudom,$tcrsid);    
 3114: }
 3115: 
 3116: # --------------------------------------------- Set Expire Date for Spreadsheet
 3117: 
 3118: sub expirespread {
 3119:     my ($uname,$udom,$stype,$usymb)=@_;
 3120:     my $cid=$env{'request.course.id'}; 
 3121:     if ($cid) {
 3122:        my $now=time;
 3123:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3124:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3125:                             $env{'course.'.$cid.'.num'}.
 3126: 	        	    ':nohist_expirationdates:'.
 3127:                             &escape($key).'='.$now,
 3128:                             $env{'course.'.$cid.'.home'})
 3129:     }
 3130:     return 'ok';
 3131: }
 3132: 
 3133: # ----------------------------------------------------- Devalidate Spreadsheets
 3134: 
 3135: sub devalidate {
 3136:     my ($symb,$uname,$udom)=@_;
 3137:     my $cid=$env{'request.course.id'}; 
 3138:     if ($cid) {
 3139:         # delete the stored spreadsheets for
 3140:         # - the student level sheet of this user in course's homespace
 3141:         # - the assessment level sheet for this resource 
 3142:         #   for this user in user's homespace
 3143: 	# - current conditional state info
 3144: 	my $key=$uname.':'.$udom.':';
 3145:         my $status=
 3146: 	    &del('nohist_calculatedsheets',
 3147: 		 [$key.'studentcalc:'],
 3148: 		 $env{'course.'.$cid.'.domain'},
 3149: 		 $env{'course.'.$cid.'.num'})
 3150: 		.' '.
 3151: 	    &del('nohist_calculatedsheets_'.$cid,
 3152: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3153:         unless ($status eq 'ok ok') {
 3154:            &logthis('Could not devalidate spreadsheet '.
 3155:                     $uname.' at '.$udom.' for '.
 3156: 		    $symb.': '.$status);
 3157:         }
 3158: 	&delenv('user.state.'.$cid);
 3159:     }
 3160: }
 3161: 
 3162: sub get_scalar {
 3163:     my ($string,$end) = @_;
 3164:     my $value;
 3165:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3166: 	$value = $1;
 3167:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3168: 	$value = $1;
 3169:     }
 3170:     return &unescape($value);
 3171: }
 3172: 
 3173: sub array2str {
 3174:   my (@array) = @_;
 3175:   my $result=&arrayref2str(\@array);
 3176:   $result=~s/^__ARRAY_REF__//;
 3177:   $result=~s/__END_ARRAY_REF__$//;
 3178:   return $result;
 3179: }
 3180: 
 3181: sub arrayref2str {
 3182:   my ($arrayref) = @_;
 3183:   my $result='__ARRAY_REF__';
 3184:   foreach my $elem (@$arrayref) {
 3185:     if(ref($elem) eq 'ARRAY') {
 3186:       $result.=&arrayref2str($elem).'&';
 3187:     } elsif(ref($elem) eq 'HASH') {
 3188:       $result.=&hashref2str($elem).'&';
 3189:     } elsif(ref($elem)) {
 3190:       #print("Got a ref of ".(ref($elem))." skipping.");
 3191:     } else {
 3192:       $result.=&escape($elem).'&';
 3193:     }
 3194:   }
 3195:   $result=~s/\&$//;
 3196:   $result .= '__END_ARRAY_REF__';
 3197:   return $result;
 3198: }
 3199: 
 3200: sub hash2str {
 3201:   my (%hash) = @_;
 3202:   my $result=&hashref2str(\%hash);
 3203:   $result=~s/^__HASH_REF__//;
 3204:   $result=~s/__END_HASH_REF__$//;
 3205:   return $result;
 3206: }
 3207: 
 3208: sub hashref2str {
 3209:   my ($hashref)=@_;
 3210:   my $result='__HASH_REF__';
 3211:   foreach my $key (sort(keys(%$hashref))) {
 3212:     if (ref($key) eq 'ARRAY') {
 3213:       $result.=&arrayref2str($key).'=';
 3214:     } elsif (ref($key) eq 'HASH') {
 3215:       $result.=&hashref2str($key).'=';
 3216:     } elsif (ref($key)) {
 3217:       $result.='=';
 3218:       #print("Got a ref of ".(ref($key))." skipping.");
 3219:     } else {
 3220: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3221:     }
 3222: 
 3223:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3224:       $result.=&arrayref2str($hashref->{$key}).'&';
 3225:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3226:       $result.=&hashref2str($hashref->{$key}).'&';
 3227:     } elsif(ref($hashref->{$key})) {
 3228:        $result.='&';
 3229:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3230:     } else {
 3231:       $result.=&escape($hashref->{$key}).'&';
 3232:     }
 3233:   }
 3234:   $result=~s/\&$//;
 3235:   $result .= '__END_HASH_REF__';
 3236:   return $result;
 3237: }
 3238: 
 3239: sub str2hash {
 3240:     my ($string)=@_;
 3241:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3242:     return %$hash;
 3243: }
 3244: 
 3245: sub str2hashref {
 3246:   my ($string) = @_;
 3247: 
 3248:   my %hash;
 3249: 
 3250:   if($string !~ /^__HASH_REF__/) {
 3251:       if (! ($string eq '' || !defined($string))) {
 3252: 	  $hash{'error'}='Not hash reference';
 3253:       }
 3254:       return (\%hash, $string);
 3255:   }
 3256: 
 3257:   $string =~ s/^__HASH_REF__//;
 3258: 
 3259:   while($string !~ /^__END_HASH_REF__/) {
 3260:       #key
 3261:       my $key='';
 3262:       if($string =~ /^__HASH_REF__/) {
 3263:           ($key, $string)=&str2hashref($string);
 3264:           if(defined($key->{'error'})) {
 3265:               $hash{'error'}='Bad data';
 3266:               return (\%hash, $string);
 3267:           }
 3268:       } elsif($string =~ /^__ARRAY_REF__/) {
 3269:           ($key, $string)=&str2arrayref($string);
 3270:           if($key->[0] eq 'Array reference error') {
 3271:               $hash{'error'}='Bad data';
 3272:               return (\%hash, $string);
 3273:           }
 3274:       } else {
 3275:           $string =~ s/^(.*?)=//;
 3276: 	  $key=&unescape($1);
 3277:       }
 3278:       $string =~ s/^=//;
 3279: 
 3280:       #value
 3281:       my $value='';
 3282:       if($string =~ /^__HASH_REF__/) {
 3283:           ($value, $string)=&str2hashref($string);
 3284:           if(defined($value->{'error'})) {
 3285:               $hash{'error'}='Bad data';
 3286:               return (\%hash, $string);
 3287:           }
 3288:       } elsif($string =~ /^__ARRAY_REF__/) {
 3289:           ($value, $string)=&str2arrayref($string);
 3290:           if($value->[0] eq 'Array reference error') {
 3291:               $hash{'error'}='Bad data';
 3292:               return (\%hash, $string);
 3293:           }
 3294:       } else {
 3295: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3296:       }
 3297:       $string =~ s/^&//;
 3298: 
 3299:       $hash{$key}=$value;
 3300:   }
 3301: 
 3302:   $string =~ s/^__END_HASH_REF__//;
 3303: 
 3304:   return (\%hash, $string);
 3305: }
 3306: 
 3307: sub str2array {
 3308:     my ($string)=@_;
 3309:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3310:     return @$array;
 3311: }
 3312: 
 3313: sub str2arrayref {
 3314:   my ($string) = @_;
 3315:   my @array;
 3316: 
 3317:   if($string !~ /^__ARRAY_REF__/) {
 3318:       if (! ($string eq '' || !defined($string))) {
 3319: 	  $array[0]='Array reference error';
 3320:       }
 3321:       return (\@array, $string);
 3322:   }
 3323: 
 3324:   $string =~ s/^__ARRAY_REF__//;
 3325: 
 3326:   while($string !~ /^__END_ARRAY_REF__/) {
 3327:       my $value='';
 3328:       if($string =~ /^__HASH_REF__/) {
 3329:           ($value, $string)=&str2hashref($string);
 3330:           if(defined($value->{'error'})) {
 3331:               $array[0] ='Array reference error';
 3332:               return (\@array, $string);
 3333:           }
 3334:       } elsif($string =~ /^__ARRAY_REF__/) {
 3335:           ($value, $string)=&str2arrayref($string);
 3336:           if($value->[0] eq 'Array reference error') {
 3337:               $array[0] ='Array reference error';
 3338:               return (\@array, $string);
 3339:           }
 3340:       } else {
 3341: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3342:       }
 3343:       $string =~ s/^&//;
 3344: 
 3345:       push(@array, $value);
 3346:   }
 3347: 
 3348:   $string =~ s/^__END_ARRAY_REF__//;
 3349: 
 3350:   return (\@array, $string);
 3351: }
 3352: 
 3353: # -------------------------------------------------------------------Temp Store
 3354: 
 3355: sub tmpreset {
 3356:   my ($symb,$namespace,$domain,$stuname) = @_;
 3357:   if (!$symb) {
 3358:     $symb=&symbread();
 3359:     if (!$symb) { $symb= $env{'request.url'}; }
 3360:   }
 3361:   $symb=escape($symb);
 3362: 
 3363:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3364:   $namespace=~s/\//\_/g;
 3365:   $namespace=~s/\W//g;
 3366: 
 3367:   if (!$domain) { $domain=$env{'user.domain'}; }
 3368:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3369:   if ($domain eq 'public' && $stuname eq 'public') {
 3370:       $stuname=$ENV{'REMOTE_ADDR'};
 3371:   }
 3372:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3373:   my %hash;
 3374:   if (tie(%hash,'GDBM_File',
 3375: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3376: 	  &GDBM_WRCREAT(),0640)) {
 3377:     foreach my $key (keys %hash) {
 3378:       if ($key=~ /:$symb/) {
 3379: 	delete($hash{$key});
 3380:       }
 3381:     }
 3382:   }
 3383: }
 3384: 
 3385: sub tmpstore {
 3386:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3387: 
 3388:   if (!$symb) {
 3389:     $symb=&symbread();
 3390:     if (!$symb) { $symb= $env{'request.url'}; }
 3391:   }
 3392:   $symb=escape($symb);
 3393: 
 3394:   if (!$namespace) {
 3395:     # I don't think we would ever want to store this for a course.
 3396:     # it seems this will only be used if we don't have a course.
 3397:     #$namespace=$env{'request.course.id'};
 3398:     #if (!$namespace) {
 3399:       $namespace=$env{'request.state'};
 3400:     #}
 3401:   }
 3402:   $namespace=~s/\//\_/g;
 3403:   $namespace=~s/\W//g;
 3404:   if (!$domain) { $domain=$env{'user.domain'}; }
 3405:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3406:   if ($domain eq 'public' && $stuname eq 'public') {
 3407:       $stuname=$ENV{'REMOTE_ADDR'};
 3408:   }
 3409:   my $now=time;
 3410:   my %hash;
 3411:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3412:   if (tie(%hash,'GDBM_File',
 3413: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3414: 	  &GDBM_WRCREAT(),0640)) {
 3415:     $hash{"version:$symb"}++;
 3416:     my $version=$hash{"version:$symb"};
 3417:     my $allkeys=''; 
 3418:     foreach my $key (keys(%$storehash)) {
 3419:       $allkeys.=$key.':';
 3420:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3421:     }
 3422:     $hash{"$version:$symb:timestamp"}=$now;
 3423:     $allkeys.='timestamp';
 3424:     $hash{"$version:keys:$symb"}=$allkeys;
 3425:     if (untie(%hash)) {
 3426:       return 'ok';
 3427:     } else {
 3428:       return "error:$!";
 3429:     }
 3430:   } else {
 3431:     return "error:$!";
 3432:   }
 3433: }
 3434: 
 3435: # -----------------------------------------------------------------Temp Restore
 3436: 
 3437: sub tmprestore {
 3438:   my ($symb,$namespace,$domain,$stuname) = @_;
 3439: 
 3440:   if (!$symb) {
 3441:     $symb=&symbread();
 3442:     if (!$symb) { $symb= $env{'request.url'}; }
 3443:   }
 3444:   $symb=escape($symb);
 3445: 
 3446:   if (!$namespace) { $namespace=$env{'request.state'}; }
 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 %returnhash;
 3454:   $namespace=~s/\//\_/g;
 3455:   $namespace=~s/\W//g;
 3456:   my %hash;
 3457:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3458:   if (tie(%hash,'GDBM_File',
 3459: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3460: 	  &GDBM_READER(),0640)) {
 3461:     my $version=$hash{"version:$symb"};
 3462:     $returnhash{'version'}=$version;
 3463:     my $scope;
 3464:     for ($scope=1;$scope<=$version;$scope++) {
 3465:       my $vkeys=$hash{"$scope:keys:$symb"};
 3466:       my @keys=split(/:/,$vkeys);
 3467:       my $key;
 3468:       $returnhash{"$scope:keys"}=$vkeys;
 3469:       foreach $key (@keys) {
 3470: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3471: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3472:       }
 3473:     }
 3474:     if (!(untie(%hash))) {
 3475:       return "error:$!";
 3476:     }
 3477:   } else {
 3478:     return "error:$!";
 3479:   }
 3480:   return %returnhash;
 3481: }
 3482: 
 3483: # ----------------------------------------------------------------------- Store
 3484: 
 3485: sub store {
 3486:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3487:     my $home='';
 3488: 
 3489:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3490: 
 3491:     $symb=&symbclean($symb);
 3492:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3493: 
 3494:     if (!$domain) { $domain=$env{'user.domain'}; }
 3495:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3496: 
 3497:     &devalidate($symb,$stuname,$domain);
 3498: 
 3499:     $symb=escape($symb);
 3500:     if (!$namespace) { 
 3501:        unless ($namespace=$env{'request.course.id'}) { 
 3502:           return ''; 
 3503:        } 
 3504:     }
 3505:     if (!$home) { $home=$env{'user.home'}; }
 3506: 
 3507:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3508:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3509: 
 3510:     my $namevalue='';
 3511:     foreach my $key (keys(%$storehash)) {
 3512:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3513:     }
 3514:     $namevalue=~s/\&$//;
 3515:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3516:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3517: }
 3518: 
 3519: # -------------------------------------------------------------- Critical Store
 3520: 
 3521: sub cstore {
 3522:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3523:     my $home='';
 3524: 
 3525:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3526: 
 3527:     $symb=&symbclean($symb);
 3528:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3529: 
 3530:     if (!$domain) { $domain=$env{'user.domain'}; }
 3531:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3532: 
 3533:     &devalidate($symb,$stuname,$domain);
 3534: 
 3535:     $symb=escape($symb);
 3536:     if (!$namespace) { 
 3537:        unless ($namespace=$env{'request.course.id'}) { 
 3538:           return ''; 
 3539:        } 
 3540:     }
 3541:     if (!$home) { $home=$env{'user.home'}; }
 3542: 
 3543:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3544:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3545: 
 3546:     my $namevalue='';
 3547:     foreach my $key (keys(%$storehash)) {
 3548:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3549:     }
 3550:     $namevalue=~s/\&$//;
 3551:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3552:     return critical
 3553:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3554: }
 3555: 
 3556: # --------------------------------------------------------------------- Restore
 3557: 
 3558: sub restore {
 3559:     my ($symb,$namespace,$domain,$stuname) = @_;
 3560:     my $home='';
 3561: 
 3562:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3563: 
 3564:     if (!$symb) {
 3565:       unless ($symb=escape(&symbread())) { return ''; }
 3566:     } else {
 3567:       $symb=&escape(&symbclean($symb));
 3568:     }
 3569:     if (!$namespace) { 
 3570:        unless ($namespace=$env{'request.course.id'}) { 
 3571:           return ''; 
 3572:        } 
 3573:     }
 3574:     if (!$domain) { $domain=$env{'user.domain'}; }
 3575:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3576:     if (!$home) { $home=$env{'user.home'}; }
 3577:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3578: 
 3579:     my %returnhash=();
 3580:     foreach my $line (split(/\&/,$answer)) {
 3581: 	my ($name,$value)=split(/\=/,$line);
 3582:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3583:     }
 3584:     my $version;
 3585:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3586:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3587:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3588:        }
 3589:     }
 3590:     return %returnhash;
 3591: }
 3592: 
 3593: # ---------------------------------------------------------- Course Description
 3594: 
 3595: sub coursedescription {
 3596:     my ($courseid,$args)=@_;
 3597:     $courseid=~s/^\///;
 3598:     $courseid=~s/\_/\//g;
 3599:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3600:     my $chome=&homeserver($cnum,$cdomain);
 3601:     my $normalid=$cdomain.'_'.$cnum;
 3602:     # need to always cache even if we get errors otherwise we keep 
 3603:     # trying and trying and trying to get the course description.
 3604:     my %envhash=();
 3605:     my %returnhash=();
 3606:     
 3607:     my $expiretime=600;
 3608:     if ($env{'request.course.id'} eq $normalid) {
 3609: 	$expiretime=120;
 3610:     }
 3611: 
 3612:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3613:     if (!$args->{'freshen_cache'}
 3614: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3615: 	foreach my $key (keys(%env)) {
 3616: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3617: 	    my ($setting) = $1;
 3618: 	    $returnhash{$setting} = $env{$key};
 3619: 	}
 3620: 	return %returnhash;
 3621:     }
 3622: 
 3623:     # get the data agin
 3624:     if (!$args->{'one_time'}) {
 3625: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3626:     }
 3627: 
 3628:     if ($chome ne 'no_host') {
 3629:        %returnhash=&dump('environment',$cdomain,$cnum);
 3630:        if (!exists($returnhash{'con_lost'})) {
 3631:            $returnhash{'home'}= $chome;
 3632: 	   $returnhash{'domain'} = $cdomain;
 3633: 	   $returnhash{'num'} = $cnum;
 3634:            if (!defined($returnhash{'type'})) {
 3635:                $returnhash{'type'} = 'Course';
 3636:            }
 3637:            while (my ($name,$value) = each %returnhash) {
 3638:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3639:            }
 3640:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3641:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3642: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3643:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3644:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3645:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3646:        }
 3647:     }
 3648:     if (!$args->{'one_time'}) {
 3649: 	&appenv(\%envhash);
 3650:     }
 3651:     return %returnhash;
 3652: }
 3653: 
 3654: # -------------------------------------------------See if a user is privileged
 3655: 
 3656: sub privileged {
 3657:     my ($username,$domain)=@_;
 3658:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3659: 			&homeserver($username,$domain));
 3660:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3661:     my $now=time;
 3662:     if ($rolesdump ne '') {
 3663:         foreach my $entry (split(/&/,$rolesdump)) {
 3664: 	    if ($entry!~/^rolesdef_/) {
 3665: 		my ($area,$role)=split(/=/,$entry);
 3666: 		$area=~s/\_\w\w$//;
 3667: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3668: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3669: 		    my $active=1;
 3670: 		    if ($tend) {
 3671: 			if ($tend<$now) { $active=0; }
 3672: 		    }
 3673: 		    if ($tstart) {
 3674: 			if ($tstart>$now) { $active=0; }
 3675: 		    }
 3676: 		    if ($active) { return 1; }
 3677: 		}
 3678: 	    }
 3679: 	}
 3680:     }
 3681:     return 0;
 3682: }
 3683: 
 3684: # -------------------------------------------------------- Get user privileges
 3685: 
 3686: sub rolesinit {
 3687:     my ($domain,$username,$authhost)=@_;
 3688:     my %userroles;
 3689:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3690:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
 3691:     my %allroles=();
 3692:     my %allgroups=();   
 3693:     my $now=time;
 3694:     %userroles = ('user.login.time' => $now);
 3695:     my $group_privs;
 3696: 
 3697:     if ($rolesdump ne '') {
 3698:         foreach my $entry (split(/&/,$rolesdump)) {
 3699: 	  if ($entry!~/^rolesdef_/) {
 3700:             my ($area,$role)=split(/=/,$entry);
 3701: 	    $area=~s/\_\w\w$//;
 3702:             my ($trole,$tend,$tstart,$group_privs);
 3703: 	    if ($role=~/^cr/) { 
 3704: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3705: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3706: 		    ($tend,$tstart)=split('_',$trest);
 3707: 		} else {
 3708: 		    $trole=$role;
 3709: 		}
 3710:             } elsif ($role =~ m|^gr/|) {
 3711:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3712:                 ($trole,$group_privs) = split(/\//,$trole);
 3713:                 $group_privs = &unescape($group_privs);
 3714: 	    } else {
 3715: 		($trole,$tend,$tstart)=split(/_/,$role);
 3716: 	    }
 3717: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3718: 					 $username);
 3719: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3720:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3721:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3722:             if (($area ne '') && ($trole ne '')) {
 3723: 		my $spec=$trole.'.'.$area;
 3724: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3725: 		if ($trole =~ /^cr\//) {
 3726:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3727:                 } elsif ($trole eq 'gr') {
 3728:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3729: 		} else {
 3730:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3731: 		}
 3732:             }
 3733:           }
 3734:         }
 3735:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3736:         $userroles{'user.adv'}    = $adv;
 3737: 	$userroles{'user.author'} = $author;
 3738:         $env{'user.adv'}=$adv;
 3739:     }
 3740:     return \%userroles;  
 3741: }
 3742: 
 3743: sub set_arearole {
 3744:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3745: # log the associated role with the area
 3746:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3747:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3748: }
 3749: 
 3750: sub custom_roleprivs {
 3751:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3752:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3753:     my $homsvr=homeserver($rauthor,$rdomain);
 3754:     if (&hostname($homsvr) ne '') {
 3755:         my ($rdummy,$roledef)=
 3756:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3757:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3758:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3759:             if (defined($syspriv)) {
 3760:                 $$allroles{'cm./'}.=':'.$syspriv;
 3761:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3762:             }
 3763:             if ($tdomain ne '') {
 3764:                 if (defined($dompriv)) {
 3765:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3766:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3767:                 }
 3768:                 if (($trest ne '') && (defined($coursepriv))) {
 3769:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3770:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3771:                 }
 3772:             }
 3773:         }
 3774:     }
 3775: }
 3776: 
 3777: sub group_roleprivs {
 3778:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3779:     my $access = 1;
 3780:     my $now = time;
 3781:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3782:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3783:     if ($access) {
 3784:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3785:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3786:     }
 3787: }
 3788: 
 3789: sub standard_roleprivs {
 3790:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3791:     if (defined($pr{$trole.':s'})) {
 3792:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3793:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3794:     }
 3795:     if ($tdomain ne '') {
 3796:         if (defined($pr{$trole.':d'})) {
 3797:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3798:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3799:         }
 3800:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3801:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3802:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3803:         }
 3804:     }
 3805: }
 3806: 
 3807: sub set_userprivs {
 3808:     my ($userroles,$allroles,$allgroups) = @_; 
 3809:     my $author=0;
 3810:     my $adv=0;
 3811:     my %grouproles = ();
 3812:     if (keys(%{$allgroups}) > 0) {
 3813:         foreach my $role (keys %{$allroles}) {
 3814:             my ($trole,$area,$sec,$extendedarea);
 3815:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3816:                 $trole = $1;
 3817:                 $area = $2;
 3818:                 $sec = $3;
 3819:                 $extendedarea = $area.$sec;
 3820:                 if (exists($$allgroups{$area})) {
 3821:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3822:                         my $spec = $trole.'.'.$extendedarea;
 3823:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3824:                                                 $$allgroups{$area}{$group};
 3825:                     }
 3826:                 }
 3827:             }
 3828:         }
 3829:     }
 3830:     foreach my $group (keys(%grouproles)) {
 3831:         $$allroles{$group} = $grouproles{$group};
 3832:     }
 3833:     foreach my $role (keys(%{$allroles})) {
 3834:         my %thesepriv;
 3835:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3836:         foreach my $item (split(/:/,$$allroles{$role})) {
 3837:             if ($item ne '') {
 3838:                 my ($privilege,$restrictions)=split(/&/,$item);
 3839:                 if ($restrictions eq '') {
 3840:                     $thesepriv{$privilege}='F';
 3841:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3842:                     $thesepriv{$privilege}.=$restrictions;
 3843:                 }
 3844:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3845:             }
 3846:         }
 3847:         my $thesestr='';
 3848:         foreach my $priv (keys(%thesepriv)) {
 3849: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3850: 	}
 3851:         $userroles->{'user.priv.'.$role} = $thesestr;
 3852:     }
 3853:     return ($author,$adv);
 3854: }
 3855: 
 3856: # --------------------------------------------------------------- get interface
 3857: 
 3858: sub get {
 3859:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3860:    my $items='';
 3861:    foreach my $item (@$storearr) {
 3862:        $items.=&escape($item).'&';
 3863:    }
 3864:    $items=~s/\&$//;
 3865:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3866:    if (!$uname) { $uname=$env{'user.name'}; }
 3867:    my $uhome=&homeserver($uname,$udomain);
 3868: 
 3869:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3870:    my @pairs=split(/\&/,$rep);
 3871:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3872:      return @pairs;
 3873:    }
 3874:    my %returnhash=();
 3875:    my $i=0;
 3876:    foreach my $item (@$storearr) {
 3877:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3878:       $i++;
 3879:    }
 3880:    return %returnhash;
 3881: }
 3882: 
 3883: # --------------------------------------------------------------- del interface
 3884: 
 3885: sub del {
 3886:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3887:    my $items='';
 3888:    foreach my $item (@$storearr) {
 3889:        $items.=&escape($item).'&';
 3890:    }
 3891: 
 3892:    $items=~s/\&$//;
 3893:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3894:    if (!$uname) { $uname=$env{'user.name'}; }
 3895:    my $uhome=&homeserver($uname,$udomain);
 3896:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3897: }
 3898: 
 3899: # -------------------------------------------------------------- dump interface
 3900: 
 3901: sub dump {
 3902:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3903:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3904:     if (!$uname) { $uname=$env{'user.name'}; }
 3905:     my $uhome=&homeserver($uname,$udomain);
 3906:     if ($regexp) {
 3907: 	$regexp=&escape($regexp);
 3908:     } else {
 3909: 	$regexp='.';
 3910:     }
 3911:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3912:     my @pairs=split(/\&/,$rep);
 3913:     my %returnhash=();
 3914:     foreach my $item (@pairs) {
 3915: 	my ($key,$value)=split(/=/,$item,2);
 3916: 	$key = &unescape($key);
 3917: 	next if ($key =~ /^error: 2 /);
 3918: 	$returnhash{$key}=&thaw_unescape($value);
 3919:     }
 3920:     return %returnhash;
 3921: }
 3922: 
 3923: # --------------------------------------------------------- dumpstore interface
 3924: 
 3925: sub dumpstore {
 3926:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3927:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3928:    if (!$uname) { $uname=$env{'user.name'}; }
 3929:    my $uhome=&homeserver($uname,$udomain);
 3930:    if ($regexp) {
 3931:        $regexp=&escape($regexp);
 3932:    } else {
 3933:        $regexp='.';
 3934:    }
 3935:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3936:    my @pairs=split(/\&/,$rep);
 3937:    my %returnhash=();
 3938:    foreach my $item (@pairs) {
 3939:        my ($key,$value)=split(/=/,$item,2);
 3940:        next if ($key =~ /^error: 2 /);
 3941:        $returnhash{$key}=&thaw_unescape($value);
 3942:    }
 3943:    return %returnhash;
 3944: }
 3945: 
 3946: # -------------------------------------------------------------- keys interface
 3947: 
 3948: sub getkeys {
 3949:    my ($namespace,$udomain,$uname)=@_;
 3950:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3951:    if (!$uname) { $uname=$env{'user.name'}; }
 3952:    my $uhome=&homeserver($uname,$udomain);
 3953:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3954:    my @keyarray=();
 3955:    foreach my $key (split(/\&/,$rep)) {
 3956:       next if ($key =~ /^error: 2 /);
 3957:       push(@keyarray,&unescape($key));
 3958:    }
 3959:    return @keyarray;
 3960: }
 3961: 
 3962: # --------------------------------------------------------------- currentdump
 3963: sub currentdump {
 3964:    my ($courseid,$sdom,$sname)=@_;
 3965:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3966:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3967:    $sname    = $env{'user.name'}         if (! defined($sname));
 3968:    my $uhome = &homeserver($sname,$sdom);
 3969:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3970:    return if ($rep =~ /^(error:|no_such_host)/);
 3971:    #
 3972:    my %returnhash=();
 3973:    #
 3974:    if ($rep eq "unknown_cmd") { 
 3975:        # an old lond will not know currentdump
 3976:        # Do a dump and make it look like a currentdump
 3977:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3978:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3979:        my %hash = @tmp;
 3980:        @tmp=();
 3981:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3982:    } else {
 3983:        my @pairs=split(/\&/,$rep);
 3984:        foreach my $pair (@pairs) {
 3985:            my ($key,$value)=split(/=/,$pair,2);
 3986:            my ($symb,$param) = split(/:/,$key);
 3987:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3988:                                                         &thaw_unescape($value);
 3989:        }
 3990:    }
 3991:    return %returnhash;
 3992: }
 3993: 
 3994: sub convert_dump_to_currentdump{
 3995:     my %hash = %{shift()};
 3996:     my %returnhash;
 3997:     # Code ripped from lond, essentially.  The only difference
 3998:     # here is the unescaping done by lonnet::dump().  Conceivably
 3999:     # we might run in to problems with parameter names =~ /^v\./
 4000:     while (my ($key,$value) = each(%hash)) {
 4001:         my ($v,$symb,$param) = split(/:/,$key);
 4002: 	$symb  = &unescape($symb);
 4003: 	$param = &unescape($param);
 4004:         next if ($v eq 'version' || $symb eq 'keys');
 4005:         next if (exists($returnhash{$symb}) &&
 4006:                  exists($returnhash{$symb}->{$param}) &&
 4007:                  $returnhash{$symb}->{'v.'.$param} > $v);
 4008:         $returnhash{$symb}->{$param}=$value;
 4009:         $returnhash{$symb}->{'v.'.$param}=$v;
 4010:     }
 4011:     #
 4012:     # Remove all of the keys in the hashes which keep track of
 4013:     # the version of the parameter.
 4014:     while (my ($symb,$param_hash) = each(%returnhash)) {
 4015:         # use a foreach because we are going to delete from the hash.
 4016:         foreach my $key (keys(%$param_hash)) {
 4017:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 4018:         }
 4019:     }
 4020:     return \%returnhash;
 4021: }
 4022: 
 4023: # ------------------------------------------------------ critical inc interface
 4024: 
 4025: sub cinc {
 4026:     return &inc(@_,'critical');
 4027: }
 4028: 
 4029: # --------------------------------------------------------------- inc interface
 4030: 
 4031: sub inc {
 4032:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 4033:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4034:     if (!$uname) { $uname=$env{'user.name'}; }
 4035:     my $uhome=&homeserver($uname,$udomain);
 4036:     my $items='';
 4037:     if (! ref($store)) {
 4038:         # got a single value, so use that instead
 4039:         $items = &escape($store).'=&';
 4040:     } elsif (ref($store) eq 'SCALAR') {
 4041:         $items = &escape($$store).'=&';        
 4042:     } elsif (ref($store) eq 'ARRAY') {
 4043:         $items = join('=&',map {&escape($_);} @{$store});
 4044:     } elsif (ref($store) eq 'HASH') {
 4045:         while (my($key,$value) = each(%{$store})) {
 4046:             $items.= &escape($key).'='.&escape($value).'&';
 4047:         }
 4048:     }
 4049:     $items=~s/\&$//;
 4050:     if ($critical) {
 4051: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 4052:     } else {
 4053: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 4054:     }
 4055: }
 4056: 
 4057: # --------------------------------------------------------------- put interface
 4058: 
 4059: sub put {
 4060:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4061:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4062:    if (!$uname) { $uname=$env{'user.name'}; }
 4063:    my $uhome=&homeserver($uname,$udomain);
 4064:    my $items='';
 4065:    foreach my $item (keys(%$storehash)) {
 4066:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4067:    }
 4068:    $items=~s/\&$//;
 4069:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4070: }
 4071: 
 4072: # ------------------------------------------------------------ newput interface
 4073: 
 4074: sub newput {
 4075:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4076:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4077:    if (!$uname) { $uname=$env{'user.name'}; }
 4078:    my $uhome=&homeserver($uname,$udomain);
 4079:    my $items='';
 4080:    foreach my $key (keys(%$storehash)) {
 4081:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4082:    }
 4083:    $items=~s/\&$//;
 4084:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 4085: }
 4086: 
 4087: # ---------------------------------------------------------  putstore interface
 4088: 
 4089: sub putstore {
 4090:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4091:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4092:    if (!$uname) { $uname=$env{'user.name'}; }
 4093:    my $uhome=&homeserver($uname,$udomain);
 4094:    my $items='';
 4095:    foreach my $key (keys(%$storehash)) {
 4096:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 4097:    }
 4098:    $items=~s/\&$//;
 4099:    my $esc_symb=&escape($symb);
 4100:    my $esc_v=&escape($version);
 4101:    my $reply =
 4102:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 4103: 	      $uhome);
 4104:    if ($reply eq 'unknown_cmd') {
 4105:        # gfall back to way things use to be done
 4106:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 4107: 			    $uname);
 4108:    }
 4109:    return $reply;
 4110: }
 4111: 
 4112: sub old_putstore {
 4113:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4114:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4115:     if (!$uname) { $uname=$env{'user.name'}; }
 4116:     my $uhome=&homeserver($uname,$udomain);
 4117:     my %newstorehash;
 4118:     foreach my $item (keys(%$storehash)) {
 4119: 	my $key = $version.':'.&escape($symb).':'.$item;
 4120: 	$newstorehash{$key} = $storehash->{$item};
 4121:     }
 4122:     my $items='';
 4123:     my %allitems = ();
 4124:     foreach my $item (keys(%newstorehash)) {
 4125: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 4126: 	    my $key = $1.':keys:'.$2;
 4127: 	    $allitems{$key} .= $3.':';
 4128: 	}
 4129: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 4130:     }
 4131:     foreach my $item (keys(%allitems)) {
 4132: 	$allitems{$item} =~ s/\:$//;
 4133: 	$items.= $item.'='.$allitems{$item}.'&';
 4134:     }
 4135:     $items=~s/\&$//;
 4136:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4137: }
 4138: 
 4139: # ------------------------------------------------------ critical put interface
 4140: 
 4141: sub cput {
 4142:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4143:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4144:    if (!$uname) { $uname=$env{'user.name'}; }
 4145:    my $uhome=&homeserver($uname,$udomain);
 4146:    my $items='';
 4147:    foreach my $item (keys(%$storehash)) {
 4148:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4149:    }
 4150:    $items=~s/\&$//;
 4151:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 4152: }
 4153: 
 4154: # -------------------------------------------------------------- eget interface
 4155: 
 4156: sub eget {
 4157:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4158:    my $items='';
 4159:    foreach my $item (@$storearr) {
 4160:        $items.=&escape($item).'&';
 4161:    }
 4162:    $items=~s/\&$//;
 4163:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4164:    if (!$uname) { $uname=$env{'user.name'}; }
 4165:    my $uhome=&homeserver($uname,$udomain);
 4166:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 4167:    my @pairs=split(/\&/,$rep);
 4168:    my %returnhash=();
 4169:    my $i=0;
 4170:    foreach my $item (@$storearr) {
 4171:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4172:       $i++;
 4173:    }
 4174:    return %returnhash;
 4175: }
 4176: 
 4177: # ------------------------------------------------------------ tmpput interface
 4178: sub tmpput {
 4179:     my ($storehash,$server,$context)=@_;
 4180:     my $items='';
 4181:     foreach my $item (keys(%$storehash)) {
 4182: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4183:     }
 4184:     $items=~s/\&$//;
 4185:     if (defined($context)) {
 4186:         $items .= ':'.&escape($context);
 4187:     }
 4188:     return &reply("tmpput:$items",$server);
 4189: }
 4190: 
 4191: # ------------------------------------------------------------ tmpget interface
 4192: sub tmpget {
 4193:     my ($token,$server)=@_;
 4194:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4195:     my $rep=&reply("tmpget:$token",$server);
 4196:     my %returnhash;
 4197:     foreach my $item (split(/\&/,$rep)) {
 4198: 	my ($key,$value)=split(/=/,$item);
 4199:         next if ($key =~ /^error: 2 /);
 4200: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 4201:     }
 4202:     return %returnhash;
 4203: }
 4204: 
 4205: # ------------------------------------------------------------ tmpget interface
 4206: sub tmpdel {
 4207:     my ($token,$server)=@_;
 4208:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4209:     return &reply("tmpdel:$token",$server);
 4210: }
 4211: 
 4212: # -------------------------------------------------- portfolio access checking
 4213: 
 4214: sub portfolio_access {
 4215:     my ($requrl) = @_;
 4216:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4217:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4218:     if ($result) {
 4219:         my %setters;
 4220:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4221:             my ($startblock,$endblock) =
 4222:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4223:             if ($startblock && $endblock) {
 4224:                 return 'B';
 4225:             }
 4226:         } else {
 4227:             my ($startblock,$endblock) =
 4228:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4229:             if ($startblock && $endblock) {
 4230:                 return 'B';
 4231:             }
 4232:         }
 4233:     }
 4234:     if ($result eq 'ok') {
 4235:        return 'F';
 4236:     } elsif ($result =~ /^[^:]+:guest_/) {
 4237:        return 'A';
 4238:     }
 4239:     return '';
 4240: }
 4241: 
 4242: sub get_portfolio_access {
 4243:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4244: 
 4245:     if (!ref($access_hash)) {
 4246: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4247: 	my %access_controls = &get_access_controls($current_perms,$group,
 4248: 						   $file_name);
 4249: 	$access_hash = $access_controls{$file_name};
 4250:     }
 4251: 
 4252:     my ($public,$guest,@domains,@users,@courses,@groups);
 4253:     my $now = time;
 4254:     if (ref($access_hash) eq 'HASH') {
 4255:         foreach my $key (keys(%{$access_hash})) {
 4256:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4257:             if ($start > $now) {
 4258:                 next;
 4259:             }
 4260:             if ($end && $end<$now) {
 4261:                 next;
 4262:             }
 4263:             if ($scope eq 'public') {
 4264:                 $public = $key;
 4265:                 last;
 4266:             } elsif ($scope eq 'guest') {
 4267:                 $guest = $key;
 4268:             } elsif ($scope eq 'domains') {
 4269:                 push(@domains,$key);
 4270:             } elsif ($scope eq 'users') {
 4271:                 push(@users,$key);
 4272:             } elsif ($scope eq 'course') {
 4273:                 push(@courses,$key);
 4274:             } elsif ($scope eq 'group') {
 4275:                 push(@groups,$key);
 4276:             }
 4277:         }
 4278:         if ($public) {
 4279:             return 'ok';
 4280:         }
 4281:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4282:             if ($guest) {
 4283:                 return $guest;
 4284:             }
 4285:         } else {
 4286:             if (@domains > 0) {
 4287:                 foreach my $domkey (@domains) {
 4288:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4289:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4290:                             return 'ok';
 4291:                         }
 4292:                     }
 4293:                 }
 4294:             }
 4295:             if (@users > 0) {
 4296:                 foreach my $userkey (@users) {
 4297:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4298:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4299:                             if (ref($item) eq 'HASH') {
 4300:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4301:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4302:                                     return 'ok';
 4303:                                 }
 4304:                             }
 4305:                         }
 4306:                     } 
 4307:                 }
 4308:             }
 4309:             my %roleshash;
 4310:             my @courses_and_groups = @courses;
 4311:             push(@courses_and_groups,@groups); 
 4312:             if (@courses_and_groups > 0) {
 4313:                 my (%allgroups,%allroles); 
 4314:                 my ($start,$end,$role,$sec,$group);
 4315:                 foreach my $envkey (%env) {
 4316:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4317:                         my $cid = $2.'_'.$3; 
 4318:                         if ($1 eq 'gr') {
 4319:                             $group = $4;
 4320:                             $allgroups{$cid}{$group} = $env{$envkey};
 4321:                         } else {
 4322:                             if ($4 eq '') {
 4323:                                 $sec = 'none';
 4324:                             } else {
 4325:                                 $sec = $4;
 4326:                             }
 4327:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4328:                         }
 4329:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4330:                         my $cid = $2.'_'.$3;
 4331:                         if ($4 eq '') {
 4332:                             $sec = 'none';
 4333:                         } else {
 4334:                             $sec = $4;
 4335:                         }
 4336:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4337:                     }
 4338:                 }
 4339:                 if (keys(%allroles) == 0) {
 4340:                     return;
 4341:                 }
 4342:                 foreach my $key (@courses_and_groups) {
 4343:                     my %content = %{$$access_hash{$key}};
 4344:                     my $cnum = $content{'number'};
 4345:                     my $cdom = $content{'domain'};
 4346:                     my $cid = $cdom.'_'.$cnum;
 4347:                     if (!exists($allroles{$cid})) {
 4348:                         next;
 4349:                     }    
 4350:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4351:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4352:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4353:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4354:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4355:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4356:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4357:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4358:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4359:                                         if (grep/^all$/,@sections) {
 4360:                                             return 'ok';
 4361:                                         } else {
 4362:                                             if (grep/^$sec$/,@sections) {
 4363:                                                 return 'ok';
 4364:                                             }
 4365:                                         }
 4366:                                     }
 4367:                                 }
 4368:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4369:                                     if (grep/^none$/,@groups) {
 4370:                                         return 'ok';
 4371:                                     }
 4372:                                 } else {
 4373:                                     if (grep/^all$/,@groups) {
 4374:                                         return 'ok';
 4375:                                     } 
 4376:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4377:                                         if (grep/^$group$/,@groups) {
 4378:                                             return 'ok';
 4379:                                         }
 4380:                                     }
 4381:                                 } 
 4382:                             }
 4383:                         }
 4384:                     }
 4385:                 }
 4386:             }
 4387:             if ($guest) {
 4388:                 return $guest;
 4389:             }
 4390:         }
 4391:     }
 4392:     return;
 4393: }
 4394: 
 4395: sub course_group_datechecker {
 4396:     my ($dates,$now,$status) = @_;
 4397:     my ($start,$end) = split(/\./,$dates);
 4398:     if (!$start && !$end) {
 4399:         return 'ok';
 4400:     }
 4401:     if (grep/^active$/,@{$status}) {
 4402:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4403:             return 'ok';
 4404:         }
 4405:     }
 4406:     if (grep/^previous$/,@{$status}) {
 4407:         if ($end > $now ) {
 4408:             return 'ok';
 4409:         }
 4410:     }
 4411:     if (grep/^future$/,@{$status}) {
 4412:         if ($start > $now) {
 4413:             return 'ok';
 4414:         }
 4415:     }
 4416:     return; 
 4417: }
 4418: 
 4419: sub parse_portfolio_url {
 4420:     my ($url) = @_;
 4421: 
 4422:     my ($type,$udom,$unum,$group,$file_name);
 4423:     
 4424:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4425: 	$type = 1;
 4426:         $udom = $1;
 4427:         $unum = $2;
 4428:         $file_name = $3;
 4429:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4430: 	$type = 2;
 4431:         $udom = $1;
 4432:         $unum = $2;
 4433:         $group = $3;
 4434:         $file_name = $3.'/'.$4;
 4435:     }
 4436:     if (wantarray) {
 4437: 	return ($type,$udom,$unum,$file_name,$group);
 4438:     }
 4439:     return $type;
 4440: }
 4441: 
 4442: sub is_portfolio_url {
 4443:     my ($url) = @_;
 4444:     return scalar(&parse_portfolio_url($url));
 4445: }
 4446: 
 4447: sub is_portfolio_file {
 4448:     my ($file) = @_;
 4449:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4450:         return 1;
 4451:     }
 4452:     return;
 4453: }
 4454: 
 4455: sub usertools_access {
 4456:     my ($uname,$udom,$tool,$action,$context) = @_;
 4457:     my ($access,%tools);
 4458:     if ($context eq '') {
 4459:         $context = 'tools';
 4460:     }
 4461:     if ($context eq 'requestcourses') {
 4462:         %tools = (
 4463:                       official   => 1,
 4464:                       unofficial => 1,
 4465:                  );
 4466:     } else {
 4467:         %tools = (
 4468:                       aboutme   => 1,
 4469:                       blog      => 1,
 4470:                       portfolio => 1,
 4471:                  );
 4472:     }
 4473:     return if (!defined($tools{$tool}));
 4474: 
 4475:     if ((!defined($udom)) || (!defined($uname))) {
 4476:         $udom = $env{'user.domain'};
 4477:         $uname = $env{'user.name'};
 4478:     }
 4479: 
 4480:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4481:         if ($action ne 'reload') {
 4482:             if ($context eq 'requestcourses') {
 4483:                 return $env{'environment.canrequest.'.$tool};
 4484:             } else {
 4485:                 return $env{'environment.availabletools.'.$tool};
 4486:             }
 4487:         }
 4488:     }
 4489: 
 4490:     my ($toolstatus,$inststatus);
 4491: 
 4492:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 4493:          ($action ne 'reload')) {
 4494:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 4495:         $inststatus = $env{'environment.inststatus'};
 4496:     } else {
 4497:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool);
 4498:         $toolstatus = $userenv{$context.'.'.$tool};
 4499:         $inststatus = $userenv{'inststatus'};
 4500:     }
 4501: 
 4502:     if ($toolstatus ne '') {
 4503:         if ($toolstatus) {
 4504:             $access = 1;
 4505:         } else {
 4506:             $access = 0;
 4507:         }
 4508:         return $access;
 4509:     }
 4510: 
 4511:     my $is_adv = &is_advanced_user($udom,$uname);
 4512:     my %domdef = &get_domain_defaults($udom);
 4513:     if (ref($domdef{$tool}) eq 'HASH') {
 4514:         if ($is_adv) {
 4515:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 4516:                 if ($domdef{$tool}{'_LC_adv'}) { 
 4517:                     $access = 1;
 4518:                 } else {
 4519:                     $access = 0;
 4520:                 }
 4521:                 return $access;
 4522:             }
 4523:         }
 4524:         if ($inststatus ne '') {
 4525:             my ($hasaccess,$hasnoaccess);
 4526:             foreach my $affiliation (split(/:/,$inststatus)) {
 4527:                 if ($domdef{$tool}{$affiliation} ne '') { 
 4528:                     if ($domdef{$tool}{$affiliation}) {
 4529:                         $hasaccess = 1;
 4530:                     } else {
 4531:                         $hasnoaccess = 1;
 4532:                     }
 4533:                 }
 4534:             }
 4535:             if ($hasaccess || $hasnoaccess) {
 4536:                 if ($hasaccess) {
 4537:                     $access = 1;
 4538:                 } elsif ($hasnoaccess) {
 4539:                     $access = 0; 
 4540:                 }
 4541:                 return $access;
 4542:             }
 4543:         } else {
 4544:             if ($domdef{$tool}{'default'} ne '') {
 4545:                 if ($domdef{$tool}{'default'}) {
 4546:                     $access = 1;
 4547:                 } elsif ($domdef{$tool}{'default'} == 0) {
 4548:                     $access = 0;
 4549:                 }
 4550:                 return $access;
 4551:             }
 4552:         }
 4553:     } else {
 4554:         if ($context eq 'tools') {
 4555:             $access = 1;
 4556:         } else {
 4557:             $access = 0;
 4558:         }
 4559:         return $access;
 4560:     }
 4561: }
 4562: 
 4563: sub is_advanced_user {
 4564:     my ($udom,$uname) = @_;
 4565:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 4566:     my %allroles;
 4567:     my $is_adv;
 4568:     foreach my $role (keys(%roleshash)) {
 4569:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 4570:         my $area = '/'.$tdomain.'/'.$trest;
 4571:         if ($sec ne '') {
 4572:             $area .= '/'.$sec;
 4573:         }
 4574:         if (($area ne '') && ($trole ne '')) {
 4575:             my $spec=$trole.'.'.$area;
 4576:             if ($trole =~ /^cr\//) {
 4577:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4578:             } elsif ($trole ne 'gr') {
 4579:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4580:             }
 4581:         }
 4582:     }
 4583:     foreach my $role (keys(%allroles)) {
 4584:         last if ($is_adv);
 4585:         foreach my $item (split(/:/,$allroles{$role})) {
 4586:             if ($item ne '') {
 4587:                 my ($privilege,$restrictions)=split(/&/,$item);
 4588:                 if ($privilege eq 'adv') {
 4589:                     $is_adv = 1;
 4590:                     last;
 4591:                 }
 4592:             }
 4593:         }
 4594:     }
 4595:     return $is_adv;
 4596: }
 4597: 
 4598: # ---------------------------------------------- Custom access rule evaluation
 4599: 
 4600: sub customaccess {
 4601:     my ($priv,$uri)=@_;
 4602:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4603:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4604:     $udom = &LONCAPA::clean_domain($udom);
 4605:     $ucrs = &LONCAPA::clean_username($ucrs);
 4606:     my $access=0;
 4607:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4608: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4609: 	if ($type eq 'user') {
 4610: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4611: 		my ($tdom,$tuname)=split(m{/},$scope);
 4612: 		if ($tdom) {
 4613: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4614: 		}
 4615: 		if ($tuname) {
 4616: 		    if ($tuname ne $env{'user.name'}) { next; }
 4617: 		}
 4618: 		$access=($effect eq 'allow');
 4619: 		last;
 4620: 	    }
 4621: 	} else {
 4622: 	    if ($role) {
 4623: 		if ($role ne $urole) { next; }
 4624: 	    }
 4625: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4626: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4627: 		if ($tdom) {
 4628: 		    if ($tdom ne $udom) { next; }
 4629: 		}
 4630: 		if ($tcrs) {
 4631: 		    if ($tcrs ne $ucrs) { next; }
 4632: 		}
 4633: 		if ($tsec) {
 4634: 		    if ($tsec ne $usec) { next; }
 4635: 		}
 4636: 		$access=($effect eq 'allow');
 4637: 		last;
 4638: 	    }
 4639: 	    if ($realm eq '' && $role eq '') {
 4640: 		$access=($effect eq 'allow');
 4641: 	    }
 4642: 	}
 4643:     }
 4644:     return $access;
 4645: }
 4646: 
 4647: # ------------------------------------------------- Check for a user privilege
 4648: 
 4649: sub allowed {
 4650:     my ($priv,$uri,$symb,$role)=@_;
 4651:     my $ver_orguri=$uri;
 4652:     $uri=&deversion($uri);
 4653:     my $orguri=$uri;
 4654:     $uri=&declutter($uri);
 4655: 
 4656:     if ($priv eq 'evb') {
 4657: # Evade communication block restrictions for specified role in a course
 4658:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4659:             return $1;
 4660:         } else {
 4661:             return;
 4662:         }
 4663:     }
 4664: 
 4665:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4666: # Free bre access to adm and meta resources
 4667:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4668: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4669: 	&& ($priv eq 'bre')) {
 4670: 	return 'F';
 4671:     }
 4672: 
 4673: # Free bre access to user's own portfolio contents
 4674:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4675:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4676: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4677:         my %setters;
 4678:         my ($startblock,$endblock) = 
 4679:             &Apache::loncommon::blockcheck(\%setters,'port');
 4680:         if ($startblock && $endblock) {
 4681:             return 'B';
 4682:         } else {
 4683:             return 'F';
 4684:         }
 4685:     }
 4686: 
 4687: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4688:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4689:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4690:         if (exists($env{'request.course.id'})) {
 4691:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4692:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4693:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4694:                 my $courseprivid=$env{'request.course.id'};
 4695:                 $courseprivid=~s/\_/\//;
 4696:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4697:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4698:                     return $1; 
 4699:                 } else {
 4700:                     if ($env{'request.course.sec'}) {
 4701:                         $courseprivid.='/'.$env{'request.course.sec'};
 4702:                     }
 4703:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4704:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4705:                         return $2;
 4706:                     }
 4707:                 }
 4708:             }
 4709:         }
 4710:     }
 4711: 
 4712: # Free bre to public access
 4713: 
 4714:     if ($priv eq 'bre') {
 4715:         my $copyright=&metadata($uri,'copyright');
 4716: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4717:            return 'F'; 
 4718:         }
 4719:         if ($copyright eq 'priv') {
 4720:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4721: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4722: 		return '';
 4723:             }
 4724:         }
 4725:         if ($copyright eq 'domain') {
 4726:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4727: 	    unless (($env{'user.domain'} eq $1) ||
 4728:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4729: 		return '';
 4730:             }
 4731:         }
 4732:         if ($env{'request.role'}=~ /li\.\//) {
 4733:             # Library role, so allow browsing of resources in this domain.
 4734:             return 'F';
 4735:         }
 4736:         if ($copyright eq 'custom') {
 4737: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4738:         }
 4739:     }
 4740:     # Domain coordinator is trying to create a course
 4741:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4742:         # uri is the requested domain in this case.
 4743:         # comparison to 'request.role.domain' shows if the user has selected
 4744:         # a role of dc for the domain in question.
 4745:         return 'F' if ($uri eq $env{'request.role.domain'});
 4746:     }
 4747: 
 4748:     my $thisallowed='';
 4749:     my $statecond=0;
 4750:     my $courseprivid='';
 4751: 
 4752: # Course
 4753: 
 4754:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4755:        $thisallowed.=$1;
 4756:     }
 4757: 
 4758: # Domain
 4759: 
 4760:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4761:        =~/\Q$priv\E\&([^\:]*)/) {
 4762:        $thisallowed.=$1;
 4763:     }
 4764: 
 4765: # Course: uri itself is a course
 4766:     my $courseuri=$uri;
 4767:     $courseuri=~s/\_(\d)/\/$1/;
 4768:     $courseuri=~s/^([^\/])/\/$1/;
 4769: 
 4770:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 4771:        =~/\Q$priv\E\&([^\:]*)/) {
 4772:        $thisallowed.=$1;
 4773:     }
 4774: 
 4775: # URI is an uploaded document for this course, default permissions don't matter
 4776: # not allowing 'edit' access (editupload) to uploaded course docs
 4777:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 4778: 	$thisallowed='';
 4779:         my ($match)=&is_on_map($uri);
 4780:         if ($match) {
 4781:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 4782:                   =~/\Q$priv\E\&([^\:]*)/) {
 4783:                 $thisallowed.=$1;
 4784:             }
 4785:         } else {
 4786:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 4787:             if ($refuri) {
 4788:                 if ($refuri =~ m|^/adm/|) {
 4789:                     $thisallowed='F';
 4790:                 } else {
 4791:                     $refuri=&declutter($refuri);
 4792:                     my ($match) = &is_on_map($refuri);
 4793:                     if ($match) {
 4794:                         $thisallowed='F';
 4795:                     }
 4796:                 }
 4797:             }
 4798:         }
 4799:     }
 4800: 
 4801:     if ($priv eq 'bre'
 4802: 	&& $thisallowed ne 'F' 
 4803: 	&& $thisallowed ne '2'
 4804: 	&& &is_portfolio_url($uri)) {
 4805: 	$thisallowed = &portfolio_access($uri);
 4806:     }
 4807:     
 4808: # Full access at system, domain or course-wide level? Exit.
 4809:     if ($thisallowed=~/F/) {
 4810: 	return 'F';
 4811:     }
 4812: 
 4813: # If this is generating or modifying users, exit with special codes
 4814: 
 4815:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4816: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4817: 	    my ($audom,$auname)=split('/',$uri);
 4818: # no author name given, so this just checks on the general right to make a co-author in this domain
 4819: 	    unless ($auname) { return $thisallowed; }
 4820: # an author name is given, so we are about to actually make a co-author for a certain account
 4821: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4822: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 4823: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 4824: 	}
 4825: 	return $thisallowed;
 4826:     }
 4827: #
 4828: # Gathered so far: system, domain and course wide privileges
 4829: #
 4830: # Course: See if uri or referer is an individual resource that is part of 
 4831: # the course
 4832: 
 4833:     if ($env{'request.course.id'}) {
 4834: 
 4835:        $courseprivid=$env{'request.course.id'};
 4836:        if ($env{'request.course.sec'}) {
 4837:           $courseprivid.='/'.$env{'request.course.sec'};
 4838:        }
 4839:        $courseprivid=~s/\_/\//;
 4840:        my $checkreferer=1;
 4841:        my ($match,$cond)=&is_on_map($uri);
 4842:        if ($match) {
 4843:            $statecond=$cond;
 4844:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4845:                =~/\Q$priv\E\&([^\:]*)/) {
 4846:                $thisallowed.=$1;
 4847:                $checkreferer=0;
 4848:            }
 4849:        }
 4850:        
 4851:        if ($checkreferer) {
 4852: 	  my $refuri=$env{'httpref.'.$orguri};
 4853:             unless ($refuri) {
 4854:                 foreach my $key (keys(%env)) {
 4855: 		    if ($key=~/^httpref\..*\*/) {
 4856: 			my $pattern=$key;
 4857:                         $pattern=~s/^httpref\.\/res\///;
 4858:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4859:                         $pattern=~s/\//\\\//g;
 4860:                         if ($orguri=~/$pattern/) {
 4861: 			    $refuri=$env{$key};
 4862:                         }
 4863:                     }
 4864:                 }
 4865:             }
 4866: 
 4867:          if ($refuri) { 
 4868: 	  $refuri=&declutter($refuri);
 4869:           my ($match,$cond)=&is_on_map($refuri);
 4870:             if ($match) {
 4871:               my $refstatecond=$cond;
 4872:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4873:                   =~/\Q$priv\E\&([^\:]*)/) {
 4874:                   $thisallowed.=$1;
 4875:                   $uri=$refuri;
 4876:                   $statecond=$refstatecond;
 4877:               }
 4878:           }
 4879:         }
 4880:        }
 4881:    }
 4882: 
 4883: #
 4884: # Gathered now: all privileges that could apply, and condition number
 4885: # 
 4886: #
 4887: # Full or no access?
 4888: #
 4889: 
 4890:     if ($thisallowed=~/F/) {
 4891: 	return 'F';
 4892:     }
 4893: 
 4894:     unless ($thisallowed) {
 4895:         return '';
 4896:     }
 4897: 
 4898: # Restrictions exist, deal with them
 4899: #
 4900: #   C:according to course preferences
 4901: #   R:according to resource settings
 4902: #   L:unless locked
 4903: #   X:according to user session state
 4904: #
 4905: 
 4906: # Possibly locked functionality, check all courses
 4907: # Locks might take effect only after 10 minutes cache expiration for other
 4908: # courses, and 2 minutes for current course
 4909: 
 4910:     my $envkey;
 4911:     if ($thisallowed=~/L/) {
 4912:         foreach $envkey (keys %env) {
 4913:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 4914:                my $courseid=$2;
 4915:                my $roleid=$1.'.'.$2;
 4916:                $courseid=~s/^\///;
 4917:                my $expiretime=600;
 4918:                if ($env{'request.role'} eq $roleid) {
 4919: 		  $expiretime=120;
 4920:                }
 4921: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 4922:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 4923:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 4924: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 4925:                }
 4926:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4927:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4928: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4929:                        &log($env{'user.domain'},$env{'user.name'},
 4930:                             $env{'user.home'},
 4931:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4932:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4933:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4934: 		       return '';
 4935:                    }
 4936:                }
 4937:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4938:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4939: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4940:                        &log($env{'user.domain'},$env{'user.name'},
 4941:                             $env{'user.home'},
 4942:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4943:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4944:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4945: 		       return '';
 4946:                    }
 4947:                }
 4948: 	   }
 4949:        }
 4950:     }
 4951:    
 4952: #
 4953: # Rest of the restrictions depend on selected course
 4954: #
 4955: 
 4956:     unless ($env{'request.course.id'}) {
 4957: 	if ($thisallowed eq 'A') {
 4958: 	    return 'A';
 4959:         } elsif ($thisallowed eq 'B') {
 4960:             return 'B';
 4961: 	} else {
 4962: 	    return '1';
 4963: 	}
 4964:     }
 4965: 
 4966: #
 4967: # Now user is definitely in a course
 4968: #
 4969: 
 4970: 
 4971: # Course preferences
 4972: 
 4973:    if ($thisallowed=~/C/) {
 4974:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4975:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4976:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4977: 	   =~/\Q$rolecode\E/) {
 4978: 	   if ($priv ne 'pch') { 
 4979: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4980: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4981: 			$env{'request.course.id'});
 4982: 	   }
 4983:            return '';
 4984:        }
 4985: 
 4986:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4987: 	   =~/\Q$unamedom\E/) {
 4988: 	   if ($priv ne 'pch') { 
 4989: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4990: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4991: 			$env{'request.course.id'});
 4992: 	   }
 4993:            return '';
 4994:        }
 4995:    }
 4996: 
 4997: # Resource preferences
 4998: 
 4999:    if ($thisallowed=~/R/) {
 5000:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5001:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 5002: 	   if ($priv ne 'pch') { 
 5003: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5004: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 5005: 	   }
 5006: 	   return '';
 5007:        }
 5008:    }
 5009: 
 5010: # Restricted by state or randomout?
 5011: 
 5012:    if ($thisallowed=~/X/) {
 5013:       if ($env{'acc.randomout'}) {
 5014: 	 if (!$symb) { $symb=&symbread($uri,1); }
 5015:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 5016:             return ''; 
 5017:          }
 5018:       }
 5019:       if (&condval($statecond)) {
 5020: 	 return '2';
 5021:       } else {
 5022:          return '';
 5023:       }
 5024:    }
 5025: 
 5026:     if ($thisallowed eq 'A') {
 5027: 	return 'A';
 5028:     } elsif ($thisallowed eq 'B') {
 5029:         return 'B';
 5030:     }
 5031:    return 'F';
 5032: }
 5033: 
 5034: sub split_uri_for_cond {
 5035:     my $uri=&deversion(&declutter(shift));
 5036:     my @uriparts=split(/\//,$uri);
 5037:     my $filename=pop(@uriparts);
 5038:     my $pathname=join('/',@uriparts);
 5039:     return ($pathname,$filename);
 5040: }
 5041: # --------------------------------------------------- Is a resource on the map?
 5042: 
 5043: sub is_on_map {
 5044:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 5045:     #Trying to find the conditional for the file
 5046:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 5047: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 5048:     if ($match) {
 5049: 	return (1,$1);
 5050:     } else {
 5051: 	return (0,0);
 5052:     }
 5053: }
 5054: 
 5055: # --------------------------------------------------------- Get symb from alias
 5056: 
 5057: sub get_symb_from_alias {
 5058:     my $symb=shift;
 5059:     my ($map,$resid,$url)=&decode_symb($symb);
 5060: # Already is a symb
 5061:     if ($url) { return $symb; }
 5062: # Must be an alias
 5063:     my $aliassymb='';
 5064:     my %bighash;
 5065:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5066:                             &GDBM_READER(),0640)) {
 5067:         my $rid=$bighash{'mapalias_'.$symb};
 5068: 	if ($rid) {
 5069: 	    my ($mapid,$resid)=split(/\./,$rid);
 5070: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 5071: 				    $resid,$bighash{'src_'.$rid});
 5072: 	}
 5073:         untie %bighash;
 5074:     }
 5075:     return $aliassymb;
 5076: }
 5077: 
 5078: # ----------------------------------------------------------------- Define Role
 5079: 
 5080: sub definerole {
 5081:   if (allowed('mcr','/')) {
 5082:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 5083:     foreach my $role (split(':',$sysrole)) {
 5084: 	my ($crole,$cqual)=split(/\&/,$role);
 5085:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 5086:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 5087: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5088:                return "refused:s:$crole&$cqual"; 
 5089:             }
 5090:         }
 5091:     }
 5092:     foreach my $role (split(':',$domrole)) {
 5093: 	my ($crole,$cqual)=split(/\&/,$role);
 5094:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 5095:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 5096: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 5097:                return "refused:d:$crole&$cqual"; 
 5098:             }
 5099:         }
 5100:     }
 5101:     foreach my $role (split(':',$courole)) {
 5102: 	my ($crole,$cqual)=split(/\&/,$role);
 5103:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 5104:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 5105: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5106:                return "refused:c:$crole&$cqual"; 
 5107:             }
 5108:         }
 5109:     }
 5110:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5111:                 "$env{'user.domain'}:$env{'user.name'}:".
 5112: 	        "rolesdef_$rolename=".
 5113:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 5114:     return reply($command,$env{'user.home'});
 5115:   } else {
 5116:     return 'refused';
 5117:   }
 5118: }
 5119: 
 5120: # ---------------- Make a metadata query against the network of library servers
 5121: 
 5122: sub metadata_query {
 5123:     my ($query,$custom,$customshow,$server_array)=@_;
 5124:     my %rhash;
 5125:     my %libserv = &all_library();
 5126:     my @server_list = (defined($server_array) ? @$server_array
 5127:                                               : keys(%libserv) );
 5128:     for my $server (@server_list) {
 5129: 	unless ($custom or $customshow) {
 5130: 	    my $reply=&reply("querysend:".&escape($query),$server);
 5131: 	    $rhash{$server}=$reply;
 5132: 	}
 5133: 	else {
 5134: 	    my $reply=&reply("querysend:".&escape($query).':'.
 5135: 			     &escape($custom).':'.&escape($customshow),
 5136: 			     $server);
 5137: 	    $rhash{$server}=$reply;
 5138: 	}
 5139:     }
 5140:     return \%rhash;
 5141: }
 5142: 
 5143: # ----------------------------------------- Send log queries and wait for reply
 5144: 
 5145: sub log_query {
 5146:     my ($uname,$udom,$query,%filters)=@_;
 5147:     my $uhome=&homeserver($uname,$udom);
 5148:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 5149:     my $uhost=&hostname($uhome);
 5150:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 5151:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 5152:                        $uhome);
 5153:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 5154:     return get_query_reply($queryid);
 5155: }
 5156: 
 5157: # -------------------------- Update MySQL table for portfolio file
 5158: 
 5159: sub update_portfolio_table {
 5160:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 5161:     if ($group ne '') {
 5162:         $file_name =~s /^\Q$group\E//;
 5163:     }
 5164:     my $homeserver = &homeserver($uname,$udom);
 5165:     my $queryid=
 5166:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 5167:                ':'.&escape($file_name).':'.$action,$homeserver);
 5168:     my $reply = &get_query_reply($queryid);
 5169:     return $reply;
 5170: }
 5171: 
 5172: # -------------------------- Update MySQL allusers table
 5173: 
 5174: sub update_allusers_table {
 5175:     my ($uname,$udom,$names) = @_;
 5176:     my $homeserver = &homeserver($uname,$udom);
 5177:     my $queryid=
 5178:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 5179:                'lastname='.&escape($names->{'lastname'}).'%%'.
 5180:                'firstname='.&escape($names->{'firstname'}).'%%'.
 5181:                'middlename='.&escape($names->{'middlename'}).'%%'.
 5182:                'generation='.&escape($names->{'generation'}).'%%'.
 5183:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 5184:                'id='.&escape($names->{'id'}),$homeserver);
 5185:     my $reply = &get_query_reply($queryid);
 5186:     return $reply;
 5187: }
 5188: 
 5189: # ------- Request retrieval of institutional classlists for course(s)
 5190: 
 5191: sub fetch_enrollment_query {
 5192:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 5193:     my $homeserver;
 5194:     my $maxtries = 1;
 5195:     if ($context eq 'automated') {
 5196:         $homeserver = $perlvar{'lonHostID'};
 5197:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 5198:     } else {
 5199:         $homeserver = &homeserver($cnum,$dom);
 5200:     }
 5201:     my $host=&hostname($homeserver);
 5202:     my $cmd = '';
 5203:     foreach my $affiliate (keys %{$affiliatesref}) {
 5204:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5205:     }
 5206:     $cmd =~ s/%%$//;
 5207:     $cmd = &escape($cmd);
 5208:     my $query = 'fetchenrollment';
 5209:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 5210:     unless ($queryid=~/^\Q$host\E\_/) { 
 5211:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 5212:         return 'error: '.$queryid;
 5213:     }
 5214:     my $reply = &get_query_reply($queryid);
 5215:     my $tries = 1;
 5216:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5217:         $reply = &get_query_reply($queryid);
 5218:         $tries ++;
 5219:     }
 5220:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5221:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5222:     } else {
 5223:         my @responses = split(/:/,$reply);
 5224:         if ($homeserver eq $perlvar{'lonHostID'}) {
 5225:             foreach my $line (@responses) {
 5226:                 my ($key,$value) = split(/=/,$line,2);
 5227:                 $$replyref{$key} = $value;
 5228:             }
 5229:         } else {
 5230:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 5231:             foreach my $line (@responses) {
 5232:                 my ($key,$value) = split(/=/,$line);
 5233:                 $$replyref{$key} = $value;
 5234:                 if ($value > 0) {
 5235:                     foreach my $item (@{$$affiliatesref{$key}}) {
 5236:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 5237:                         my $destname = $pathname.'/'.$filename;
 5238:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 5239:                         if ($xml_classlist =~ /^error/) {
 5240:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 5241:                         } else {
 5242:                             if ( open(FILE,">$destname") ) {
 5243:                                 print FILE &unescape($xml_classlist);
 5244:                                 close(FILE);
 5245:                             } else {
 5246:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 5247:                             }
 5248:                         }
 5249:                     }
 5250:                 }
 5251:             }
 5252:         }
 5253:         return 'ok';
 5254:     }
 5255:     return 'error';
 5256: }
 5257: 
 5258: sub get_query_reply {
 5259:     my $queryid=shift;
 5260:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 5261:     my $reply='';
 5262:     for (1..100) {
 5263: 	sleep 2;
 5264:         if (-e $replyfile.'.end') {
 5265: 	    if (open(my $fh,$replyfile)) {
 5266: 		$reply = join('',<$fh>);
 5267: 		close($fh);
 5268: 	   } else { return 'error: reply_file_error'; }
 5269:            return &unescape($reply);
 5270: 	}
 5271:     }
 5272:     return 'timeout:'.$queryid;
 5273: }
 5274: 
 5275: sub courselog_query {
 5276: #
 5277: # possible filters:
 5278: # url: url or symb
 5279: # username
 5280: # domain
 5281: # action: view, submit, grade
 5282: # start: timestamp
 5283: # end: timestamp
 5284: #
 5285:     my (%filters)=@_;
 5286:     unless ($env{'request.course.id'}) { return 'no_course'; }
 5287:     if ($filters{'url'}) {
 5288: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 5289:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 5290:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 5291:     }
 5292:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5293:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5294:     return &log_query($cname,$cdom,'courselog',%filters);
 5295: }
 5296: 
 5297: sub userlog_query {
 5298: #
 5299: # possible filters:
 5300: # action: log check role
 5301: # start: timestamp
 5302: # end: timestamp
 5303: #
 5304:     my ($uname,$udom,%filters)=@_;
 5305:     return &log_query($uname,$udom,'userlog',%filters);
 5306: }
 5307: 
 5308: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 5309: 
 5310: sub auto_run {
 5311:     my ($cnum,$cdom) = @_;
 5312:     my $response = 0;
 5313:     my $settings;
 5314:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 5315:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5316:         $settings = $domconfig{'autoenroll'};
 5317:         if ($settings->{'run'} eq '1') {
 5318:             $response = 1;
 5319:         }
 5320:     } else {
 5321:         my $homeserver;
 5322:         if (&is_course($cdom,$cnum)) {
 5323:             $homeserver = &homeserver($cnum,$cdom);
 5324:         } else {
 5325:             $homeserver = &domain($cdom,'primary');
 5326:         }
 5327:         if ($homeserver ne 'no_host') {
 5328:             $response = &reply('autorun:'.$cdom,$homeserver);
 5329:         }
 5330:     }
 5331:     return $response;
 5332: }
 5333: 
 5334: sub auto_get_sections {
 5335:     my ($cnum,$cdom,$inst_coursecode) = @_;
 5336:     my $homeserver = &homeserver($cnum,$cdom);
 5337:     my @secs = ();
 5338:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 5339:     unless ($response eq 'refused') {
 5340:         @secs = split(/:/,$response);
 5341:     }
 5342:     return @secs;
 5343: }
 5344: 
 5345: sub auto_new_course {
 5346:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 5347:     my $homeserver = &homeserver($cnum,$cdom);
 5348:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 5349:     return $response;
 5350: }
 5351: 
 5352: sub auto_validate_courseID {
 5353:     my ($cnum,$cdom,$inst_course_id) = @_;
 5354:     my $homeserver = &homeserver($cnum,$cdom);
 5355:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5356:     return $response;
 5357: }
 5358: 
 5359: sub auto_create_password {
 5360:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5361:     my ($homeserver,$response);
 5362:     my $create_passwd = 0;
 5363:     my $authchk = '';
 5364:     if ($udom =~ /^$match_domain$/) {
 5365:         $homeserver = &domain($udom,'primary');
 5366:     }
 5367:     if ($homeserver eq '') {
 5368:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5369:             $homeserver = &homeserver($cnum,$cdom);
 5370:         }
 5371:     }
 5372:     if ($homeserver eq '') {
 5373:         $authchk = 'nodomain';
 5374:     } else {
 5375:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5376:         if ($response eq 'refused') {
 5377:             $authchk = 'refused';
 5378:         } else {
 5379:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5380:         }
 5381:     }
 5382:     return ($authparam,$create_passwd,$authchk);
 5383: }
 5384: 
 5385: sub auto_photo_permission {
 5386:     my ($cnum,$cdom,$students) = @_;
 5387:     my $homeserver = &homeserver($cnum,$cdom);
 5388:     my ($outcome,$perm_reqd,$conditions) = 
 5389: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5390:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5391: 	return (undef,undef);
 5392:     }
 5393:     return ($outcome,$perm_reqd,$conditions);
 5394: }
 5395: 
 5396: sub auto_checkphotos {
 5397:     my ($uname,$udom,$pid) = @_;
 5398:     my $homeserver = &homeserver($uname,$udom);
 5399:     my ($result,$resulttype);
 5400:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5401: 				   &escape($uname).':'.&escape($pid),
 5402: 				   $homeserver));
 5403:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5404: 	return (undef,undef);
 5405:     }
 5406:     if ($outcome) {
 5407:         ($result,$resulttype) = split(/:/,$outcome);
 5408:     } 
 5409:     return ($result,$resulttype);
 5410: }
 5411: 
 5412: sub auto_photochoice {
 5413:     my ($cnum,$cdom) = @_;
 5414:     my $homeserver = &homeserver($cnum,$cdom);
 5415:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5416: 						       &escape($cdom),
 5417: 						       $homeserver)));
 5418:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5419: 	return (undef,undef);
 5420:     }
 5421:     return ($update,$comment);
 5422: }
 5423: 
 5424: sub auto_photoupdate {
 5425:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5426:     my $homeserver = &homeserver($cnum,$dom);
 5427:     my $host=&hostname($homeserver);
 5428:     my $cmd = '';
 5429:     my $maxtries = 1;
 5430:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5431:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5432:     }
 5433:     $cmd =~ s/%%$//;
 5434:     $cmd = &escape($cmd);
 5435:     my $query = 'institutionalphotos';
 5436:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5437:     unless ($queryid=~/^\Q$host\E\_/) {
 5438:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5439:         return 'error: '.$queryid;
 5440:     }
 5441:     my $reply = &get_query_reply($queryid);
 5442:     my $tries = 1;
 5443:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5444:         $reply = &get_query_reply($queryid);
 5445:         $tries ++;
 5446:     }
 5447:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5448:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5449:     } else {
 5450:         my @responses = split(/:/,$reply);
 5451:         my $outcome = shift(@responses); 
 5452:         foreach my $item (@responses) {
 5453:             my ($key,$value) = split(/=/,$item);
 5454:             $$photo{$key} = $value;
 5455:         }
 5456:         return $outcome;
 5457:     }
 5458:     return 'error';
 5459: }
 5460: 
 5461: sub auto_instcode_format {
 5462:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5463: 	$cat_order) = @_;
 5464:     my $courses = '';
 5465:     my @homeservers;
 5466:     if ($caller eq 'global') {
 5467: 	my %servers = &get_servers($codedom,'library');
 5468: 	foreach my $tryserver (keys(%servers)) {
 5469: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5470: 		push(@homeservers,$tryserver);
 5471: 	    }
 5472:         }
 5473:     } else {
 5474:         push(@homeservers,&homeserver($caller,$codedom));
 5475:     }
 5476:     foreach my $code (keys(%{$instcodes})) {
 5477:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5478:     }
 5479:     chop($courses);
 5480:     my $ok_response = 0;
 5481:     my $response;
 5482:     while (@homeservers > 0 && $ok_response == 0) {
 5483:         my $server = shift(@homeservers); 
 5484:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5485:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5486:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5487: 		split(/:/,$response);
 5488:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5489:             push(@{$codetitles},&str2array($codetitles_str));
 5490:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5491:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5492:             $ok_response = 1;
 5493:         }
 5494:     }
 5495:     if ($ok_response) {
 5496:         return 'ok';
 5497:     } else {
 5498:         return $response;
 5499:     }
 5500: }
 5501: 
 5502: sub auto_instcode_defaults {
 5503:     my ($domain,$returnhash,$code_order) = @_;
 5504:     my @homeservers;
 5505: 
 5506:     my %servers = &get_servers($domain,'library');
 5507:     foreach my $tryserver (keys(%servers)) {
 5508: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5509: 	    push(@homeservers,$tryserver);
 5510: 	}
 5511:     }
 5512: 
 5513:     my $response;
 5514:     foreach my $server (@homeservers) {
 5515:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5516:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5517: 	
 5518: 	foreach my $pair (split(/\&/,$response)) {
 5519: 	    my ($name,$value)=split(/\=/,$pair);
 5520: 	    if ($name eq 'code_order') {
 5521: 		@{$code_order} = split(/\&/,&unescape($value));
 5522: 	    } else {
 5523: 		$returnhash->{&unescape($name)}=&unescape($value);
 5524: 	    }
 5525: 	}
 5526: 	return 'ok';
 5527:     }
 5528: 
 5529:     return $response;
 5530: } 
 5531: 
 5532: sub auto_validate_class_sec {
 5533:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5534:     my $homeserver = &homeserver($cnum,$cdom);
 5535:     my $ownerlist;
 5536:     if (ref($owners) eq 'ARRAY') {
 5537:         $ownerlist = join(',',@{$owners});
 5538:     } else {
 5539:         $ownerlist = $owners;
 5540:     }
 5541:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 5542:                         &escape($ownerlist).':'.$cdom,$homeserver);
 5543:     return $response;
 5544: }
 5545: 
 5546: # ------------------------------------------------------- Course Group routines
 5547: 
 5548: sub get_coursegroups {
 5549:     my ($cdom,$cnum,$group,$namespace) = @_;
 5550:     return(&dump($namespace,$cdom,$cnum,$group));
 5551: }
 5552: 
 5553: sub modify_coursegroup {
 5554:     my ($cdom,$cnum,$groupsettings) = @_;
 5555:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 5556: }
 5557: 
 5558: sub toggle_coursegroup_status {
 5559:     my ($cdom,$cnum,$group,$action) = @_;
 5560:     my ($from_namespace,$to_namespace);
 5561:     if ($action eq 'delete') {
 5562:         $from_namespace = 'coursegroups';
 5563:         $to_namespace = 'deleted_groups';
 5564:     } else {
 5565:         $from_namespace = 'deleted_groups';
 5566:         $to_namespace = 'coursegroups';
 5567:     }
 5568:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 5569:     if (my $tmp = &error(%curr_group)) {
 5570:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 5571:         return ('read error',$tmp);
 5572:     } else {
 5573:         my %savedsettings = %curr_group; 
 5574:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 5575:         my $deloutcome;
 5576:         if ($result eq 'ok') {
 5577:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 5578:         } else {
 5579:             return ('write error',$result);
 5580:         }
 5581:         if ($deloutcome eq 'ok') {
 5582:             return 'ok';
 5583:         } else {
 5584:             return ('delete error',$deloutcome);
 5585:         }
 5586:     }
 5587: }
 5588: 
 5589: sub modify_group_roles {
 5590:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 5591:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 5592:     my $role = 'gr/'.&escape($userprivs);
 5593:     my ($uname,$udom) = split(/:/,$user);
 5594:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 5595:     if ($result eq 'ok') {
 5596:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 5597:     }
 5598:     return $result;
 5599: }
 5600: 
 5601: sub modify_coursegroup_membership {
 5602:     my ($cdom,$cnum,$membership) = @_;
 5603:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 5604:     return $result;
 5605: }
 5606: 
 5607: sub get_active_groups {
 5608:     my ($udom,$uname,$cdom,$cnum) = @_;
 5609:     my $now = time;
 5610:     my %groups = ();
 5611:     foreach my $key (keys(%env)) {
 5612:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 5613:             my ($start,$end) = split(/\./,$env{$key});
 5614:             if (($end!=0) && ($end<$now)) { next; }
 5615:             if (($start!=0) && ($start>$now)) { next; }
 5616:             if ($1 eq $cdom && $2 eq $cnum) {
 5617:                 $groups{$3} = $env{$key} ;
 5618:             }
 5619:         }
 5620:     }
 5621:     return %groups;
 5622: }
 5623: 
 5624: sub get_group_membership {
 5625:     my ($cdom,$cnum,$group) = @_;
 5626:     return(&dump('groupmembership',$cdom,$cnum,$group));
 5627: }
 5628: 
 5629: sub get_users_groups {
 5630:     my ($udom,$uname,$courseid) = @_;
 5631:     my @usersgroups;
 5632:     my $cachetime=1800;
 5633: 
 5634:     my $hashid="$udom:$uname:$courseid";
 5635:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 5636:     if (defined($cached)) {
 5637:         @usersgroups = split(/:/,$grouplist);
 5638:     } else {  
 5639:         $grouplist = '';
 5640:         my $courseurl = &courseid_to_courseurl($courseid);
 5641:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 5642:         my $access_end = $env{'course.'.$courseid.
 5643:                               '.default_enrollment_end_date'};
 5644:         my $now = time;
 5645:         foreach my $key (keys(%roleshash)) {
 5646:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 5647:                 my $group = $1;
 5648:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 5649:                     my $start = $2;
 5650:                     my $end = $1;
 5651:                     if ($start == -1) { next; } # deleted from group
 5652:                     if (($start!=0) && ($start>$now)) { next; }
 5653:                     if (($end!=0) && ($end<$now)) {
 5654:                         if ($access_end && $access_end < $now) {
 5655:                             if ($access_end - $end < 86400) {
 5656:                                 push(@usersgroups,$group);
 5657:                             }
 5658:                         }
 5659:                         next;
 5660:                     }
 5661:                     push(@usersgroups,$group);
 5662:                 }
 5663:             }
 5664:         }
 5665:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 5666:         $grouplist = join(':',@usersgroups);
 5667:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 5668:     }
 5669:     return @usersgroups;
 5670: }
 5671: 
 5672: sub devalidate_getgroups_cache {
 5673:     my ($udom,$uname,$cdom,$cnum)=@_;
 5674:     my $courseid = $cdom.'_'.$cnum;
 5675: 
 5676:     my $hashid="$udom:$uname:$courseid";
 5677:     &devalidate_cache_new('getgroups',$hashid);
 5678: }
 5679: 
 5680: # ------------------------------------------------------------------ Plain Text
 5681: 
 5682: sub plaintext {
 5683:     my ($short,$type,$cid,$forcedefault) = @_;
 5684:     if ($short =~ /^cr/) {
 5685: 	return (split('/',$short))[-1];
 5686:     }
 5687:     if (!defined($cid)) {
 5688:         $cid = $env{'request.course.id'};
 5689:     }
 5690:     if (defined($cid) && ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '')) {
 5691:         unless ($forcedefault) {
 5692:             my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 5693:             &Apache::lonlocal::mt_escape(\$roletext);
 5694:             return &Apache::lonlocal::mt($roletext);
 5695:         }
 5696:     }
 5697:     my %rolenames = (
 5698:                       Course => 'std',
 5699:                       Group => 'alt1',
 5700:                     );
 5701:     if (defined($type) && 
 5702:          defined($rolenames{$type}) && 
 5703:          defined($prp{$short}{$rolenames{$type}})) {
 5704:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 5705:     } else {
 5706:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 5707:     }
 5708: }
 5709: 
 5710: # ----------------------------------------------------------------- Assign Role
 5711: 
 5712: sub assignrole {
 5713:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 5714:         $context)=@_;
 5715:     my $mrole;
 5716:     if ($role =~ /^cr\//) {
 5717:         my $cwosec=$url;
 5718:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5719: 	unless (&allowed('ccr',$cwosec)) {
 5720:            &logthis('Refused custom assignrole: '.
 5721:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5722: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 5723:            return 'refused'; 
 5724:         }
 5725:         $mrole='cr';
 5726:     } elsif ($role =~ /^gr\//) {
 5727:         my $cwogrp=$url;
 5728:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 5729:         unless (&allowed('mdg',$cwogrp)) {
 5730:             &logthis('Refused group assignrole: '.
 5731:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5732:                     $env{'user.name'}.' at '.$env{'user.domain'});
 5733:             return 'refused';
 5734:         }
 5735:         $mrole='gr';
 5736:     } else {
 5737:         my $cwosec=$url;
 5738:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5739:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 5740:             my $refused;
 5741:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 5742:                 if (!(&allowed('c'.$role,$url))) {
 5743:                     $refused = 1;
 5744:                 }
 5745:             } else {
 5746:                 $refused = 1;
 5747:             }
 5748:             if ($refused) {
 5749:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5750:                     $refused = '';
 5751:                 } else {
 5752:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 5753:                              ' '.$role.' '.$end.' '.$start.' by '.
 5754: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 5755:                     return 'refused';
 5756:                 }
 5757:             }
 5758:         }
 5759:         $mrole=$role;
 5760:     }
 5761:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5762:                 "$udom:$uname:$url".'_'."$mrole=$role";
 5763:     if ($end) { $command.='_'.$end; }
 5764:     if ($start) {
 5765: 	if ($end) { 
 5766:            $command.='_'.$start; 
 5767:         } else {
 5768:            $command.='_0_'.$start;
 5769:         }
 5770:     }
 5771:     my $origstart = $start;
 5772:     my $origend = $end;
 5773:     my $delflag;
 5774: # actually delete
 5775:     if ($deleteflag) {
 5776: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 5777: # modify command to delete the role
 5778:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 5779:                 "$udom:$uname:$url".'_'."$mrole";
 5780: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 5781: # set start and finish to negative values for userrolelog
 5782:            $start=-1;
 5783:            $end=-1;
 5784:            $delflag = 1;
 5785:         }
 5786:     }
 5787: # send command
 5788:     my $answer=&reply($command,&homeserver($uname,$udom));
 5789: # log new user role if status is ok
 5790:     if ($answer eq 'ok') {
 5791: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 5792: # for course roles, perform group memberships changes triggered by role change.
 5793:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 5794:         unless ($role =~ /^gr/) {
 5795:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 5796:                                              $origstart,$selfenroll,$context);
 5797:         }
 5798:     }
 5799:     return $answer;
 5800: }
 5801: 
 5802: # -------------------------------------------------- Modify user authentication
 5803: # Overrides without validation
 5804: 
 5805: sub modifyuserauth {
 5806:     my ($udom,$uname,$umode,$upass)=@_;
 5807:     my $uhome=&homeserver($uname,$udom);
 5808:     unless (&allowed('mau',$udom)) { return 'refused'; }
 5809:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 5810:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5811:              ' in domain '.$env{'request.role.domain'});  
 5812:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 5813: 		     &escape($upass),$uhome);
 5814:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 5815:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 5816:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5817:     &log($udom,,$uname,$uhome,
 5818:         'Authentication changed by '.$env{'user.domain'}.', '.
 5819:                                      $env{'user.name'}.', '.$umode.
 5820:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5821:     unless ($reply eq 'ok') {
 5822:         &logthis('Authentication mode error: '.$reply);
 5823: 	return 'error: '.$reply;
 5824:     }   
 5825:     return 'ok';
 5826: }
 5827: 
 5828: # --------------------------------------------------------------- Modify a user
 5829: 
 5830: sub modifyuser {
 5831:     my ($udom,    $uname, $uid,
 5832:         $umode,   $upass, $first,
 5833:         $middle,  $last,  $gene,
 5834:         $forceid, $desiredhome, $email, $inststatus)=@_;
 5835:     $udom= &LONCAPA::clean_domain($udom);
 5836:     $uname=&LONCAPA::clean_username($uname);
 5837:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 5838:              $umode.', '.$first.', '.$middle.', '.
 5839: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 5840:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 5841:                                      ' desiredhome not specified'). 
 5842:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5843:              ' in domain '.$env{'request.role.domain'});
 5844:     my $uhome=&homeserver($uname,$udom,'true');
 5845: # ----------------------------------------------------------------- Create User
 5846:     if (($uhome eq 'no_host') && 
 5847: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 5848:         my $unhome='';
 5849:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 5850:             $unhome = $desiredhome;
 5851: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 5852: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 5853:         } else { # load balancing routine for determining $unhome
 5854:             my $loadm=10000000;
 5855: 	    my %servers = &get_servers($udom,'library');
 5856: 	    foreach my $tryserver (keys(%servers)) {
 5857: 		my $answer=reply('load',$tryserver);
 5858: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 5859: 		    $loadm=$answer;
 5860: 		    $unhome=$tryserver;
 5861: 		}
 5862: 	    }
 5863:         }
 5864:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 5865: 	    return 'error: unable to find a home server for '.$uname.
 5866:                    ' in domain '.$udom;
 5867:         }
 5868:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 5869:                          &escape($upass),$unhome);
 5870: 	unless ($reply eq 'ok') {
 5871:             return 'error: '.$reply;
 5872:         }   
 5873:         $uhome=&homeserver($uname,$udom,'true');
 5874:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 5875: 	    return 'error: unable verify users home machine.';
 5876:         }
 5877:     }   # End of creation of new user
 5878: # ---------------------------------------------------------------------- Add ID
 5879:     if ($uid) {
 5880:        $uid=~tr/A-Z/a-z/;
 5881:        my %uidhash=&idrget($udom,$uname);
 5882:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 5883:          && (!$forceid)) {
 5884: 	  unless ($uid eq $uidhash{$uname}) {
 5885: 	      return 'error: user id "'.$uid.'" does not match '.
 5886:                   'current user id "'.$uidhash{$uname}.'".';
 5887:           }
 5888:        } else {
 5889: 	  &idput($udom,($uname => $uid));
 5890:        }
 5891:     }
 5892: # -------------------------------------------------------------- Add names, etc
 5893:     my @tmp=&get('environment',
 5894: 		   ['firstname','middlename','lastname','generation','id',
 5895:                     'permanentemail','inststatus'],
 5896: 		   $udom,$uname);
 5897:     my %names;
 5898:     if ($tmp[0] =~ m/^error:.*/) { 
 5899:         %names=(); 
 5900:     } else {
 5901:         %names = @tmp;
 5902:     }
 5903: #
 5904: # Make sure to not trash student environment if instructor does not bother
 5905: # to supply name and email information
 5906: #
 5907:     if ($first)  { $names{'firstname'}  = $first; }
 5908:     if (defined($middle)) { $names{'middlename'} = $middle; }
 5909:     if ($last)   { $names{'lastname'}   = $last; }
 5910:     if (defined($gene))   { $names{'generation'} = $gene; }
 5911:     if ($email) {
 5912:        $email=~s/[^\w\@\.\-\,]//gs;
 5913:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 5914:     }
 5915:     if ($uid) { $names{'id'}  = $uid; }
 5916:     if (defined($inststatus)) {
 5917:         $names{'inststatus'} = '';
 5918:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 5919:         if (ref($usertypes) eq 'HASH') {
 5920:             my @okstatuses; 
 5921:             foreach my $item (split(/:/,$inststatus)) {
 5922:                 if (defined($usertypes->{$item})) {
 5923:                     push(@okstatuses,$item);  
 5924:                 }
 5925:             }
 5926:             if (@okstatuses) {
 5927:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 5928:             }
 5929:         }
 5930:     }
 5931:     my $reply = &put('environment', \%names, $udom,$uname);
 5932:     if ($reply ne 'ok') { return 'error: '.$reply; }
 5933:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 5934:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 5935:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 5936:                  $umode.', '.$first.', '.$middle.', '.
 5937: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
 5938:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 5939:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 5940:     } else {
 5941:         $logmsg .= ' during self creation';
 5942:     }
 5943:     &logthis($logmsg);
 5944:     return 'ok';
 5945: }
 5946: 
 5947: # -------------------------------------------------------------- Modify student
 5948: 
 5949: sub modifystudent {
 5950:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 5951:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 5952:         $selfenroll,$context,$inststatus)=@_;
 5953:     if (!$cid) {
 5954: 	unless ($cid=$env{'request.course.id'}) {
 5955: 	    return 'not_in_class';
 5956: 	}
 5957:     }
 5958: # --------------------------------------------------------------- Make the user
 5959:     my $reply=&modifyuser
 5960: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 5961:          $desiredhome,$email,$inststatus);
 5962:     unless ($reply eq 'ok') { return $reply; }
 5963:     # This will cause &modify_student_enrollment to get the uid from the
 5964:     # students environment
 5965:     $uid = undef if (!$forceid);
 5966:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 5967: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 5968:     return $reply;
 5969: }
 5970: 
 5971: sub modify_student_enrollment {
 5972:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 5973:     my ($cdom,$cnum,$chome);
 5974:     if (!$cid) {
 5975: 	unless ($cid=$env{'request.course.id'}) {
 5976: 	    return 'not_in_class';
 5977: 	}
 5978: 	$cdom=$env{'course.'.$cid.'.domain'};
 5979: 	$cnum=$env{'course.'.$cid.'.num'};
 5980:     } else {
 5981: 	($cdom,$cnum)=split(/_/,$cid);
 5982:     }
 5983:     $chome=$env{'course.'.$cid.'.home'};
 5984:     if (!$chome) {
 5985: 	$chome=&homeserver($cnum,$cdom);
 5986:     }
 5987:     if (!$chome) { return 'unknown_course'; }
 5988:     # Make sure the user exists
 5989:     my $uhome=&homeserver($uname,$udom);
 5990:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5991: 	return 'error: no such user';
 5992:     }
 5993:     # Get student data if we were not given enough information
 5994:     if (!defined($first)  || $first  eq '' || 
 5995:         !defined($last)   || $last   eq '' || 
 5996:         !defined($uid)    || $uid    eq '' || 
 5997:         !defined($middle) || $middle eq '' || 
 5998:         !defined($gene)   || $gene   eq '') {
 5999:         # They did not supply us with enough data to enroll the student, so
 6000:         # we need to pick up more information.
 6001:         my %tmp = &get('environment',
 6002:                        ['firstname','middlename','lastname', 'generation','id']
 6003:                        ,$udom,$uname);
 6004: 
 6005:         #foreach my $key (keys(%tmp)) {
 6006:         #    &logthis("key $key = ".$tmp{$key});
 6007:         #}
 6008:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 6009:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 6010:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 6011:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 6012:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 6013:     }
 6014:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 6015:     my $reply=cput('classlist',
 6016: 		   {"$uname:$udom" => 
 6017: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 6018: 		   $cdom,$cnum);
 6019:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 6020: 	return 'error: '.$reply;
 6021:     } else {
 6022: 	&devalidate_getsection_cache($udom,$uname,$cid);
 6023:     }
 6024:     # Add student role to user
 6025:     my $uurl='/'.$cid;
 6026:     $uurl=~s/\_/\//g;
 6027:     if ($usec) {
 6028: 	$uurl.='/'.$usec;
 6029:     }
 6030:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 6031: }
 6032: 
 6033: sub format_name {
 6034:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 6035:     my $name;
 6036:     if ($first ne 'lastname') {
 6037: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 6038:     } else {
 6039: 	if ($lastname=~/\S/) {
 6040: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 6041: 	    $name=~s/\s+,/,/;
 6042: 	} else {
 6043: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 6044: 	}
 6045:     }
 6046:     $name=~s/^\s+//;
 6047:     $name=~s/\s+$//;
 6048:     $name=~s/\s+/ /g;
 6049:     return $name;
 6050: }
 6051: 
 6052: # ------------------------------------------------- Write to course preferences
 6053: 
 6054: sub writecoursepref {
 6055:     my ($courseid,%prefs)=@_;
 6056:     $courseid=~s/^\///;
 6057:     $courseid=~s/\_/\//g;
 6058:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6059:     my $chome=homeserver($cnum,$cdomain);
 6060:     if (($chome eq '') || ($chome eq 'no_host')) { 
 6061: 	return 'error: no such course';
 6062:     }
 6063:     my $cstring='';
 6064:     foreach my $pref (keys(%prefs)) {
 6065: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 6066:     }
 6067:     $cstring=~s/\&$//;
 6068:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 6069: }
 6070: 
 6071: # ---------------------------------------------------------- Make/modify course
 6072: 
 6073: sub createcourse {
 6074:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 6075:         $course_owner,$crstype)=@_;
 6076:     $url=&declutter($url);
 6077:     my $cid='';
 6078:     unless (&allowed('ccc',$udom)) {
 6079:         return 'refused';
 6080:     }
 6081: # ------------------------------------------------------------------- Create ID
 6082:    my $uname=int(1+rand(9)).
 6083:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6084:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6085:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6086: # ----------------------------------------------- Make sure that does not exist
 6087:    my $uhome=&homeserver($uname,$udom,'true');
 6088:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6089:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6090:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6091:        $uhome=&homeserver($uname,$udom,'true');       
 6092:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6093:            return 'error: unable to generate unique course-ID';
 6094:        } 
 6095:    }
 6096: # ------------------------------------------------ Check supplied server name
 6097:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 6098:     if (! &is_library($course_server)) {
 6099:         return 'error:bad server name '.$course_server;
 6100:     }
 6101: # ------------------------------------------------------------- Make the course
 6102:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 6103:                       $course_server);
 6104:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 6105:     $uhome=&homeserver($uname,$udom,'true');
 6106:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6107: 	return 'error: no such course';
 6108:     }
 6109: # ----------------------------------------------------------------- Course made
 6110: # log existence
 6111:     my $newcourse = {
 6112:                     $udom.'_'.$uname => {
 6113:                                      description => $description,
 6114:                                      inst_code   => $inst_code,
 6115:                                      owner       => $course_owner,
 6116:                                      type        => $crstype,
 6117:                                                 },
 6118:                     };
 6119:     &courseidput($udom,$newcourse,$uhome,'notime');
 6120: # set toplevel url
 6121:     my $topurl=$url;
 6122:     unless ($nonstandard) {
 6123: # ------------------------------------------ For standard courses, make top url
 6124:         my $mapurl=&clutter($url);
 6125:         if ($mapurl eq '/res/') { $mapurl=''; }
 6126:         $env{'form.initmap'}=(<<ENDINITMAP);
 6127: <map>
 6128: <resource id="1" type="start"></resource>
 6129: <resource id="2" src="$mapurl"></resource>
 6130: <resource id="3" type="finish"></resource>
 6131: <link index="1" from="1" to="2"></link>
 6132: <link index="2" from="2" to="3"></link>
 6133: </map>
 6134: ENDINITMAP
 6135:         $topurl=&declutter(
 6136:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 6137:                           );
 6138:     }
 6139: # ----------------------------------------------------------- Write preferences
 6140:     &writecoursepref($udom.'_'.$uname,
 6141:                      ('description' => $description,
 6142:                       'url'         => $topurl));
 6143:     return '/'.$udom.'/'.$uname;
 6144: }
 6145: 
 6146: sub is_course {
 6147:     my ($cdom,$cnum) = @_;
 6148:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 6149: 				undef,'.');
 6150:     if (exists($courses{$cdom.'_'.$cnum})) {
 6151:         return 1;
 6152:     }
 6153:     return 0;
 6154: }
 6155: 
 6156: # ---------------------------------------------------------- Assign Custom Role
 6157: 
 6158: sub assigncustomrole {
 6159:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 6160:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 6161:                        $end,$start,$deleteflag,$selfenroll,$context);
 6162: }
 6163: 
 6164: # ----------------------------------------------------------------- Revoke Role
 6165: 
 6166: sub revokerole {
 6167:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 6168:     my $now=time;
 6169:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 6170: }
 6171: 
 6172: # ---------------------------------------------------------- Revoke Custom Role
 6173: 
 6174: sub revokecustomrole {
 6175:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 6176:     my $now=time;
 6177:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 6178:            $deleteflag,$selfenroll,$context);
 6179: }
 6180: 
 6181: # ------------------------------------------------------------ Disk usage
 6182: sub diskusage {
 6183:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 6184:     $directorypath =~ s/\/$//;
 6185:     my $listing=&reply('du2:'.&escape($directorypath).':'
 6186:                        .&escape($getpropath).':'.&escape($uname).':'
 6187:                        .&escape($udom),homeserver($uname,$udom));
 6188:     if ($listing eq 'unknown_cmd') {
 6189:         if ($getpropath) {
 6190:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 6191:         }
 6192:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 6193:     }
 6194:     return $listing;
 6195: }
 6196: 
 6197: sub is_locked {
 6198:     my ($file_name, $domain, $user) = @_;
 6199:     my @check;
 6200:     my $is_locked;
 6201:     push @check, $file_name;
 6202:     my %locked = &get('file_permissions',\@check,
 6203: 		      $env{'user.domain'},$env{'user.name'});
 6204:     my ($tmp)=keys(%locked);
 6205:     if ($tmp=~/^error:/) { undef(%locked); }
 6206:     
 6207:     if (ref($locked{$file_name}) eq 'ARRAY') {
 6208:         $is_locked = 'false';
 6209:         foreach my $entry (@{$locked{$file_name}}) {
 6210:            if (ref($entry) eq 'ARRAY') { 
 6211:                $is_locked = 'true';
 6212:                last;
 6213:            }
 6214:        }
 6215:     } else {
 6216:         $is_locked = 'false';
 6217:     }
 6218: }
 6219: 
 6220: sub declutter_portfile {
 6221:     my ($file) = @_;
 6222:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 6223:     return $file;
 6224: }
 6225: 
 6226: # ------------------------------------------------------------- Mark as Read Only
 6227: 
 6228: sub mark_as_readonly {
 6229:     my ($domain,$user,$files,$what) = @_;
 6230:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6231:     my ($tmp)=keys(%current_permissions);
 6232:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6233:     foreach my $file (@{$files}) {
 6234: 	$file = &declutter_portfile($file);
 6235:         push(@{$current_permissions{$file}},$what);
 6236:     }
 6237:     &put('file_permissions',\%current_permissions,$domain,$user);
 6238:     return;
 6239: }
 6240: 
 6241: # ------------------------------------------------------------Save Selected Files
 6242: 
 6243: sub save_selected_files {
 6244:     my ($user, $path, @files) = @_;
 6245:     my $filename = $user."savedfiles";
 6246:     my @other_files = &files_not_in_path($user, $path);
 6247:     open (OUT, '>'.$tmpdir.$filename);
 6248:     foreach my $file (@files) {
 6249:         print (OUT $env{'form.currentpath'}.$file."\n");
 6250:     }
 6251:     foreach my $file (@other_files) {
 6252:         print (OUT $file."\n");
 6253:     }
 6254:     close (OUT);
 6255:     return 'ok';
 6256: }
 6257: 
 6258: sub clear_selected_files {
 6259:     my ($user) = @_;
 6260:     my $filename = $user."savedfiles";
 6261:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6262:     print (OUT undef);
 6263:     close (OUT);
 6264:     return ("ok");    
 6265: }
 6266: 
 6267: sub files_in_path {
 6268:     my ($user, $path) = @_;
 6269:     my $filename = $user."savedfiles";
 6270:     my %return_files;
 6271:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6272:     while (my $line_in = <IN>) {
 6273:         chomp ($line_in);
 6274:         my @paths_and_file = split (m!/!, $line_in);
 6275:         my $file_part = pop (@paths_and_file);
 6276:         my $path_part = join ('/', @paths_and_file);
 6277:         $path_part.='/';
 6278:         my $path_and_file = $path_part.$file_part;
 6279:         if ($path_part eq $path) {
 6280:             $return_files{$file_part}= 'selected';
 6281:         }
 6282:     }
 6283:     close (IN);
 6284:     return (\%return_files);
 6285: }
 6286: 
 6287: # called in portfolio select mode, to show files selected NOT in current directory
 6288: sub files_not_in_path {
 6289:     my ($user, $path) = @_;
 6290:     my $filename = $user."savedfiles";
 6291:     my @return_files;
 6292:     my $path_part;
 6293:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6294:     while (my $line = <IN>) {
 6295:         #ok, I know it's clunky, but I want it to work
 6296:         my @paths_and_file = split(m|/|, $line);
 6297:         my $file_part = pop(@paths_and_file);
 6298:         chomp($file_part);
 6299:         my $path_part = join('/', @paths_and_file);
 6300:         $path_part .= '/';
 6301:         my $path_and_file = $path_part.$file_part;
 6302:         if ($path_part ne $path) {
 6303:             push(@return_files, ($path_and_file));
 6304:         }
 6305:     }
 6306:     close(OUT);
 6307:     return (@return_files);
 6308: }
 6309: 
 6310: #----------------------------------------------Get portfolio file permissions
 6311: 
 6312: sub get_portfile_permissions {
 6313:     my ($domain,$user) = @_;
 6314:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6315:     my ($tmp)=keys(%current_permissions);
 6316:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6317:     return \%current_permissions;
 6318: }
 6319: 
 6320: #---------------------------------------------Get portfolio file access controls
 6321: 
 6322: sub get_access_controls {
 6323:     my ($current_permissions,$group,$file) = @_;
 6324:     my %access;
 6325:     my $real_file = $file;
 6326:     $file =~ s/\.meta$//;
 6327:     if (defined($file)) {
 6328:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 6329:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 6330:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 6331:             }
 6332:         }
 6333:     } else {
 6334:         foreach my $key (keys(%{$current_permissions})) {
 6335:             if ($key =~ /\0accesscontrol$/) {
 6336:                 if (defined($group)) {
 6337:                     if ($key !~ m-^\Q$group\E/-) {
 6338:                         next;
 6339:                     }
 6340:                 }
 6341:                 my ($fullpath) = split(/\0/,$key);
 6342:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 6343:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 6344:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 6345:                     }
 6346:                 }
 6347:             }
 6348:         }
 6349:     }
 6350:     return %access;
 6351: }
 6352: 
 6353: sub modify_access_controls {
 6354:     my ($file_name,$changes,$domain,$user)=@_;
 6355:     my ($outcome,$deloutcome);
 6356:     my %store_permissions;
 6357:     my %new_values;
 6358:     my %new_control;
 6359:     my %translation;
 6360:     my @deletions = ();
 6361:     my $now = time;
 6362:     if (exists($$changes{'activate'})) {
 6363:         if (ref($$changes{'activate'}) eq 'HASH') {
 6364:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 6365:             my $numnew = scalar(@newitems);
 6366:             for (my $i=0; $i<$numnew; $i++) {
 6367:                 my $newkey = $newitems[$i];
 6368:                 my $newid = &Apache::loncommon::get_cgi_id();
 6369:                 if ($newkey =~ /^\d+:/) { 
 6370:                     $newkey =~ s/^(\d+)/$newid/;
 6371:                     $translation{$1} = $newid;
 6372:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 6373:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 6374:                     $translation{$1} = $newid;
 6375:                 }
 6376:                 $new_values{$file_name."\0".$newkey} = 
 6377:                                           $$changes{'activate'}{$newitems[$i]};
 6378:                 $new_control{$newkey} = $now;
 6379:             }
 6380:         }
 6381:     }
 6382:     my %todelete;
 6383:     my %changed_items;
 6384:     foreach my $action ('delete','update') {
 6385:         if (exists($$changes{$action})) {
 6386:             if (ref($$changes{$action}) eq 'HASH') {
 6387:                 foreach my $key (keys(%{$$changes{$action}})) {
 6388:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 6389:                     if ($action eq 'delete') { 
 6390:                         $todelete{$itemnum} = 1;
 6391:                     } else {
 6392:                         $changed_items{$itemnum} = $key;
 6393:                     }
 6394:                 }
 6395:             }
 6396:         }
 6397:     }
 6398:     # get lock on access controls for file.
 6399:     my $lockhash = {
 6400:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 6401:                                                        ':'.$env{'user.domain'},
 6402:                    }; 
 6403:     my $tries = 0;
 6404:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6405:    
 6406:     while (($gotlock ne 'ok') && $tries <3) {
 6407:         $tries ++;
 6408:         sleep 1;
 6409:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6410:     }
 6411:     if ($gotlock eq 'ok') {
 6412:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 6413:         my ($tmp)=keys(%curr_permissions);
 6414:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 6415:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 6416:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 6417:             if (ref($curr_controls) eq 'HASH') {
 6418:                 foreach my $control_item (keys(%{$curr_controls})) {
 6419:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 6420:                     if (defined($todelete{$itemnum})) {
 6421:                         push(@deletions,$file_name."\0".$control_item);
 6422:                     } else {
 6423:                         if (defined($changed_items{$itemnum})) {
 6424:                             $new_control{$changed_items{$itemnum}} = $now;
 6425:                             push(@deletions,$file_name."\0".$control_item);
 6426:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 6427:                         } else {
 6428:                             $new_control{$control_item} = $$curr_controls{$control_item};
 6429:                         }
 6430:                     }
 6431:                 }
 6432:             }
 6433:         }
 6434:         my ($group);
 6435:         if (&is_course($domain,$user)) {
 6436:             ($group,my $file) = split(/\//,$file_name,2);
 6437:         }
 6438:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 6439:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 6440:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 6441:         #  remove lock
 6442:         my @del_lock = ($file_name."\0".'locked_access_records');
 6443:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 6444:         my $sqlresult =
 6445:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 6446:                                     $group);
 6447:     } else {
 6448:         $outcome = "error: could not obtain lockfile\n";  
 6449:     }
 6450:     return ($outcome,$deloutcome,\%new_values,\%translation);
 6451: }
 6452: 
 6453: sub make_public_indefinitely {
 6454:     my ($requrl) = @_;
 6455:     my $now = time;
 6456:     my $action = 'activate';
 6457:     my $aclnum = 0;
 6458:     if (&is_portfolio_url($requrl)) {
 6459:         my (undef,$udom,$unum,$file_name,$group) =
 6460:             &parse_portfolio_url($requrl);
 6461:         my $current_perms = &get_portfile_permissions($udom,$unum);
 6462:         my %access_controls = &get_access_controls($current_perms,
 6463:                                                    $group,$file_name);
 6464:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 6465:             my ($num,$scope,$end,$start) = 
 6466:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6467:             if ($scope eq 'public') {
 6468:                 if ($start <= $now && $end == 0) {
 6469:                     $action = 'none';
 6470:                 } else {
 6471:                     $action = 'update';
 6472:                     $aclnum = $num;
 6473:                 }
 6474:                 last;
 6475:             }
 6476:         }
 6477:         if ($action eq 'none') {
 6478:              return 'ok';
 6479:         } else {
 6480:             my %changes;
 6481:             my $newend = 0;
 6482:             my $newstart = $now;
 6483:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 6484:             $changes{$action}{$newkey} = {
 6485:                 type => 'public',
 6486:                 time => {
 6487:                     start => $newstart,
 6488:                     end   => $newend,
 6489:                 },
 6490:             };
 6491:             my ($outcome,$deloutcome,$new_values,$translation) =
 6492:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 6493:             return $outcome;
 6494:         }
 6495:     } else {
 6496:         return 'invalid';
 6497:     }
 6498: }
 6499: 
 6500: #------------------------------------------------------Get Marked as Read Only
 6501: 
 6502: sub get_marked_as_readonly {
 6503:     my ($domain,$user,$what,$group) = @_;
 6504:     my $current_permissions = &get_portfile_permissions($domain,$user);
 6505:     my @readonly_files;
 6506:     my $cmp1=$what;
 6507:     if (ref($what)) { $cmp1=join('',@{$what}) };
 6508:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6509:         if (defined($group)) {
 6510:             if ($file_name !~ m-^\Q$group\E/-) {
 6511:                 next;
 6512:             }
 6513:         }
 6514:         if (ref($value) eq "ARRAY"){
 6515:             foreach my $stored_what (@{$value}) {
 6516:                 my $cmp2=$stored_what;
 6517:                 if (ref($stored_what) eq 'ARRAY') {
 6518:                     $cmp2=join('',@{$stored_what});
 6519:                 }
 6520:                 if ($cmp1 eq $cmp2) {
 6521:                     push(@readonly_files, $file_name);
 6522:                     last;
 6523:                 } elsif (!defined($what)) {
 6524:                     push(@readonly_files, $file_name);
 6525:                     last;
 6526:                 }
 6527:             }
 6528:         }
 6529:     }
 6530:     return @readonly_files;
 6531: }
 6532: #-----------------------------------------------------------Get Marked as Read Only Hash
 6533: 
 6534: sub get_marked_as_readonly_hash {
 6535:     my ($current_permissions,$group,$what) = @_;
 6536:     my %readonly_files;
 6537:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6538:         if (defined($group)) {
 6539:             if ($file_name !~ m-^\Q$group\E/-) {
 6540:                 next;
 6541:             }
 6542:         }
 6543:         if (ref($value) eq "ARRAY"){
 6544:             foreach my $stored_what (@{$value}) {
 6545:                 if (ref($stored_what) eq 'ARRAY') {
 6546:                     foreach my $lock_descriptor(@{$stored_what}) {
 6547:                         if ($lock_descriptor eq 'graded') {
 6548:                             $readonly_files{$file_name} = 'graded';
 6549:                         } elsif ($lock_descriptor eq 'handback') {
 6550:                             $readonly_files{$file_name} = 'handback';
 6551:                         } else {
 6552:                             if (!exists($readonly_files{$file_name})) {
 6553:                                 $readonly_files{$file_name} = 'locked';
 6554:                             }
 6555:                         }
 6556:                     }
 6557:                 } 
 6558:             }
 6559:         } 
 6560:     }
 6561:     return %readonly_files;
 6562: }
 6563: # ------------------------------------------------------------ Unmark as Read Only
 6564: 
 6565: sub unmark_as_readonly {
 6566:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 6567:     # for portfolio submissions, $what contains [$symb,$crsid] 
 6568:     my ($domain,$user,$what,$file_name,$group) = @_;
 6569:     $file_name = &declutter_portfile($file_name);
 6570:     my $symb_crs = $what;
 6571:     if (ref($what)) { $symb_crs=join('',@$what); }
 6572:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 6573:     my ($tmp)=keys(%current_permissions);
 6574:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6575:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 6576:     foreach my $file (@readonly_files) {
 6577: 	my $clean_file = &declutter_portfile($file);
 6578: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 6579: 	my $current_locks = $current_permissions{$file};
 6580:         my @new_locks;
 6581:         my @del_keys;
 6582:         if (ref($current_locks) eq "ARRAY"){
 6583:             foreach my $locker (@{$current_locks}) {
 6584:                 my $compare=$locker;
 6585:                 if (ref($locker) eq 'ARRAY') {
 6586:                     $compare=join('',@{$locker});
 6587:                     if ($compare ne $symb_crs) {
 6588:                         push(@new_locks, $locker);
 6589:                     }
 6590:                 }
 6591:             }
 6592:             if (scalar(@new_locks) > 0) {
 6593:                 $current_permissions{$file} = \@new_locks;
 6594:             } else {
 6595:                 push(@del_keys, $file);
 6596:                 &del('file_permissions',\@del_keys, $domain, $user);
 6597:                 delete($current_permissions{$file});
 6598:             }
 6599:         }
 6600:     }
 6601:     &put('file_permissions',\%current_permissions,$domain,$user);
 6602:     return;
 6603: }
 6604: 
 6605: # ------------------------------------------------------------ Directory lister
 6606: 
 6607: sub dirlist {
 6608:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 6609:     $uri=~s/^\///;
 6610:     $uri=~s/\/$//;
 6611:     my ($udom, $uname);
 6612:     if ($getuserdir) {
 6613:         $udom = $userdomain;
 6614:         $uname = $username;
 6615:     } else {
 6616:         (undef,$udom,$uname)=split(/\//,$uri);
 6617:         if(defined($userdomain)) {
 6618:             $udom = $userdomain;
 6619:         }
 6620:         if(defined($username)) {
 6621:             $uname = $username;
 6622:         }
 6623:     }
 6624:     my ($dirRoot,$listing,@listing_results);
 6625: 
 6626:     $dirRoot = $perlvar{'lonDocRoot'};
 6627:     if (defined($getpropath)) {
 6628:         $dirRoot = &propath($udom,$uname);
 6629:         $dirRoot =~ s/\/$//;
 6630:     } elsif (defined($getuserdir)) {
 6631:         my $subdir=$uname.'__';
 6632:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 6633:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 6634:                    ."/$udom/$subdir/$uname";
 6635:     } elsif (defined($alternateRoot)) {
 6636:         $dirRoot = $alternateRoot;
 6637:     }
 6638: 
 6639:     if($udom) {
 6640:         if($uname) {
 6641:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 6642:                               .$getuserdir.':'.&escape($dirRoot)
 6643:                               .':'.&escape($uname).':'.&escape($udom),
 6644:                               &homeserver($uname,$udom));
 6645:             if ($listing eq 'unknown_cmd') {
 6646:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 6647:                                   &homeserver($uname,$udom));
 6648:             } else {
 6649:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6650:             }
 6651:             if ($listing eq 'unknown_cmd') {
 6652:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 6653: 				  &homeserver($uname,$udom));
 6654:                 @listing_results = split(/:/,$listing);
 6655:             } else {
 6656:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6657:             }
 6658:             return @listing_results;
 6659:         } elsif(!$alternateRoot) {
 6660:             my %allusers;
 6661: 	    my %servers = &get_servers($udom,'library');
 6662:  	    foreach my $tryserver (keys(%servers)) {
 6663:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 6664:                                   &escape($udom),$tryserver);
 6665:                 if ($listing eq 'unknown_cmd') {
 6666: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 6667: 				      $udom, $tryserver);
 6668:                 } else {
 6669:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 6670:                 }
 6671: 		if ($listing eq 'unknown_cmd') {
 6672: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 6673: 				      $udom, $tryserver);
 6674: 		    @listing_results = split(/:/,$listing);
 6675: 		} else {
 6676: 		    @listing_results =
 6677: 			map { &unescape($_); } split(/:/,$listing);
 6678: 		}
 6679: 		if ($listing_results[0] ne 'no_such_dir' && 
 6680: 		    $listing_results[0] ne 'empty'       &&
 6681: 		    $listing_results[0] ne 'con_lost') {
 6682: 		    foreach my $line (@listing_results) {
 6683: 			my ($entry) = split(/&/,$line,2);
 6684: 			$allusers{$entry} = 1;
 6685: 		    }
 6686: 		}
 6687:             }
 6688:             my $alluserstr='';
 6689:             foreach my $user (sort(keys(%allusers))) {
 6690:                 $alluserstr.=$user.'&user:';
 6691:             }
 6692:             $alluserstr=~s/:$//;
 6693:             return split(/:/,$alluserstr);
 6694:         } else {
 6695:             return ('missing user name');
 6696:         }
 6697:     } elsif(!defined($getpropath)) {
 6698:         my @all_domains = sort(&all_domains());
 6699:         foreach my $domain (@all_domains) {
 6700:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 6701:         }
 6702:         return @all_domains;
 6703:     } else {
 6704:         return ('missing domain');
 6705:     }
 6706: }
 6707: 
 6708: # --------------------------------------------- GetFileTimestamp
 6709: # This function utilizes dirlist and returns the date stamp for
 6710: # when it was last modified.  It will also return an error of -1
 6711: # if an error occurs
 6712: 
 6713: sub GetFileTimestamp {
 6714:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 6715:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 6716:     $studentName   = &LONCAPA::clean_username($studentName);
 6717:     my ($fileStat) = 
 6718:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
 6719:                                  undef,$getuserdir);
 6720:     my @stats = split('&', $fileStat);
 6721:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6722:         # @stats contains first the filename, then the stat output
 6723:         return $stats[10]; # so this is 10 instead of 9.
 6724:     } else {
 6725:         return -1;
 6726:     }
 6727: }
 6728: 
 6729: sub stat_file {
 6730:     my ($uri) = @_;
 6731:     $uri = &clutter_with_no_wrapper($uri);
 6732: 
 6733:     my ($udom,$uname,$file);
 6734:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 6735: 	($udom,$uname,$file) =
 6736: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 6737: 	$file = 'userfiles/'.$file;
 6738:     }
 6739:     if ($uri =~ m-^/res/-) {
 6740: 	($udom,$uname) = 
 6741: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 6742: 	$file = $uri;
 6743:     }
 6744: 
 6745:     if (!$udom || !$uname || !$file) {
 6746: 	# unable to handle the uri
 6747: 	return ();
 6748:     }
 6749:     my $getpropath;
 6750:     if ($file =~ /^userfiles\//) {
 6751:         $getpropath = 1;
 6752:     }
 6753:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
 6754:     my @stats = split('&', $result);
 6755:     
 6756:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6757: 	shift(@stats); #filename is first
 6758: 	return @stats;
 6759:     }
 6760:     return ();
 6761: }
 6762: 
 6763: # -------------------------------------------------------- Value of a Condition
 6764: 
 6765: # gets the value of a specific preevaluated condition
 6766: #    stored in the string  $env{user.state.<cid>}
 6767: # or looks up a condition reference in the bighash and if if hasn't
 6768: # already been evaluated recurses into docondval to get the value of
 6769: # the condition, then memoizing it to 
 6770: #   $env{user.state.<cid>.<condition>}
 6771: sub directcondval {
 6772:     my $number=shift;
 6773:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 6774: 	&Apache::lonuserstate::evalstate();
 6775:     }
 6776:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 6777: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 6778:     } elsif ($number =~ /^_/) {
 6779: 	my $sub_condition;
 6780: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6781: 		&GDBM_READER(),0640)) {
 6782: 	    $sub_condition=$bighash{'conditions'.$number};
 6783: 	    untie(%bighash);
 6784: 	}
 6785: 	my $value = &docondval($sub_condition);
 6786: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 6787: 	return $value;
 6788:     }
 6789:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 6790:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 6791:     } else {
 6792:        return 2;
 6793:     }
 6794: }
 6795: 
 6796: # get the collection of conditions for this resource
 6797: sub condval {
 6798:     my $condidx=shift;
 6799:     my $allpathcond='';
 6800:     foreach my $cond (split(/\|/,$condidx)) {
 6801: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 6802: 	    $allpathcond.=
 6803: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 6804: 	}
 6805:     }
 6806:     $allpathcond=~s/\|$//;
 6807:     return &docondval($allpathcond);
 6808: }
 6809: 
 6810: #evaluates an expression of conditions
 6811: sub docondval {
 6812:     my ($allpathcond) = @_;
 6813:     my $result=0;
 6814:     if ($env{'request.course.id'}
 6815: 	&& defined($allpathcond)) {
 6816: 	my $operand='|';
 6817: 	my @stack;
 6818: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 6819: 	    if ($chunk eq '(') {
 6820: 		push @stack,($operand,$result);
 6821: 	    } elsif ($chunk eq ')') {
 6822: 		my $before=pop @stack;
 6823: 		if (pop @stack eq '&') {
 6824: 		    $result=$result>$before?$before:$result;
 6825: 		} else {
 6826: 		    $result=$result>$before?$result:$before;
 6827: 		}
 6828: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 6829: 		$operand=$chunk;
 6830: 	    } else {
 6831: 		my $new=directcondval($chunk);
 6832: 		if ($operand eq '&') {
 6833: 		    $result=$result>$new?$new:$result;
 6834: 		} else {
 6835: 		    $result=$result>$new?$result:$new;
 6836: 		}
 6837: 	    }
 6838: 	}
 6839:     }
 6840:     return $result;
 6841: }
 6842: 
 6843: # ---------------------------------------------------- Devalidate courseresdata
 6844: 
 6845: sub devalidatecourseresdata {
 6846:     my ($coursenum,$coursedomain)=@_;
 6847:     my $hashid=$coursenum.':'.$coursedomain;
 6848:     &devalidate_cache_new('courseres',$hashid);
 6849: }
 6850: 
 6851: 
 6852: # --------------------------------------------------- Course Resourcedata Query
 6853: #
 6854: #  Parameters:
 6855: #      $coursenum    - Number of the course.
 6856: #      $coursedomain - Domain at which the course was created.
 6857: #  Returns:
 6858: #     A hash of the course parameters along (I think) with timestamps
 6859: #     and version info.
 6860: 
 6861: sub get_courseresdata {
 6862:     my ($coursenum,$coursedomain)=@_;
 6863:     my $coursehom=&homeserver($coursenum,$coursedomain);
 6864:     my $hashid=$coursenum.':'.$coursedomain;
 6865:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 6866:     my %dumpreply;
 6867:     unless (defined($cached)) {
 6868: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 6869: 	$result=\%dumpreply;
 6870: 	my ($tmp) = keys(%dumpreply);
 6871: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6872: 	    &do_cache_new('courseres',$hashid,$result,600);
 6873: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 6874: 	    return $tmp;
 6875: 	} elsif ($tmp =~ /^(error)/) {
 6876: 	    $result=undef;
 6877: 	    &do_cache_new('courseres',$hashid,$result,600);
 6878: 	}
 6879:     }
 6880:     return $result;
 6881: }
 6882: 
 6883: sub devalidateuserresdata {
 6884:     my ($uname,$udom)=@_;
 6885:     my $hashid="$udom:$uname";
 6886:     &devalidate_cache_new('userres',$hashid);
 6887: }
 6888: 
 6889: sub get_userresdata {
 6890:     my ($uname,$udom)=@_;
 6891:     #most student don\'t have any data set, check if there is some data
 6892:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 6893: 
 6894:     my $hashid="$udom:$uname";
 6895:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 6896:     if (!defined($cached)) {
 6897: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 6898: 	$result=\%resourcedata;
 6899: 	&do_cache_new('userres',$hashid,$result,600);
 6900:     }
 6901:     my ($tmp)=keys(%$result);
 6902:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 6903: 	return $result;
 6904:     }
 6905:     #error 2 occurs when the .db doesn't exist
 6906:     if ($tmp!~/error: 2 /) {
 6907: 	&logthis("<font color=\"blue\">WARNING:".
 6908: 		 " Trying to get resource data for ".
 6909: 		 $uname." at ".$udom.": ".
 6910: 		 $tmp."</font>");
 6911:     } elsif ($tmp=~/error: 2 /) {
 6912: 	#&EXT_cache_set($udom,$uname);
 6913: 	&do_cache_new('userres',$hashid,undef,600);
 6914: 	undef($tmp); # not really an error so don't send it back
 6915:     }
 6916:     return $tmp;
 6917: }
 6918: #----------------------------------------------- resdata - return resource data
 6919: #  Purpose:
 6920: #    Return resource data for either users or for a course.
 6921: #  Parameters:
 6922: #     $name      - Course/user name.
 6923: #     $domain    - Name of the domain the user/course is registered on.
 6924: #     $type      - Type of thing $name is (must be 'course' or 'user'
 6925: #     @which     - Array of names of resources desired.
 6926: #  Returns:
 6927: #     The value of the first reasource in @which that is found in the
 6928: #     resource hash.
 6929: #  Exceptional Conditions:
 6930: #     If the $type passed in is not valid (not the string 'course' or 
 6931: #     'user', an undefined  reference is returned.
 6932: #     If none of the resources are found, an undef is returned
 6933: sub resdata {
 6934:     my ($name,$domain,$type,@which)=@_;
 6935:     my $result;
 6936:     if ($type eq 'course') {
 6937: 	$result=&get_courseresdata($name,$domain);
 6938:     } elsif ($type eq 'user') {
 6939: 	$result=&get_userresdata($name,$domain);
 6940:     }
 6941:     if (!ref($result)) { return $result; }    
 6942:     foreach my $item (@which) {
 6943: 	if (defined($result->{$item->[0]})) {
 6944: 	    return [$result->{$item->[0]},$item->[1]];
 6945: 	}
 6946:     }
 6947:     return undef;
 6948: }
 6949: 
 6950: #
 6951: # EXT resource caching routines
 6952: #
 6953: 
 6954: sub clear_EXT_cache_status {
 6955:     &delenv('cache.EXT.');
 6956: }
 6957: 
 6958: sub EXT_cache_status {
 6959:     my ($target_domain,$target_user) = @_;
 6960:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6961:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 6962:         # We know already the user has no data
 6963:         return 1;
 6964:     } else {
 6965:         return 0;
 6966:     }
 6967: }
 6968: 
 6969: sub EXT_cache_set {
 6970:     my ($target_domain,$target_user) = @_;
 6971:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6972:     #&appenv({$cachename => time});
 6973: }
 6974: 
 6975: # --------------------------------------------------------- Value of a Variable
 6976: sub EXT {
 6977: 
 6978:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 6979:     unless ($varname) { return ''; }
 6980:     #get real user name/domain, courseid and symb
 6981:     my $courseid;
 6982:     my $publicuser;
 6983:     if ($symbparm) {
 6984: 	$symbparm=&get_symb_from_alias($symbparm);
 6985:     }
 6986:     if (!($uname && $udom)) {
 6987:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 6988:       if (!$symbparm) {	$symbparm=$cursymb; }
 6989:     } else {
 6990: 	$courseid=$env{'request.course.id'};
 6991:     }
 6992:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 6993:     my $rest;
 6994:     if (defined($therest[0])) {
 6995:        $rest=join('.',@therest);
 6996:     } else {
 6997:        $rest='';
 6998:     }
 6999: 
 7000:     my $qualifierrest=$qualifier;
 7001:     if ($rest) { $qualifierrest.='.'.$rest; }
 7002:     my $spacequalifierrest=$space;
 7003:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 7004:     if ($realm eq 'user') {
 7005: # --------------------------------------------------------------- user.resource
 7006: 	if ($space eq 'resource') {
 7007: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 7008: 		  || defined($Apache::lonhomework::parsing_a_task))
 7009: 		 &&
 7010: 		 ($symbparm eq &symbread()) ) {	
 7011: 		# if we are in the middle of processing the resource the
 7012: 		# get the value we are planning on committing
 7013:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 7014:                     return $Apache::lonhomework::results{$qualifierrest};
 7015:                 } else {
 7016:                     return $Apache::lonhomework::history{$qualifierrest};
 7017:                 }
 7018: 	    } else {
 7019: 		my %restored;
 7020: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 7021: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 7022: 		} else {
 7023: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 7024: 		}
 7025: 		return $restored{$qualifierrest};
 7026: 	    }
 7027: # ----------------------------------------------------------------- user.access
 7028:         } elsif ($space eq 'access') {
 7029: 	    # FIXME - not supporting calls for a specific user
 7030:             return &allowed($qualifier,$rest);
 7031: # ------------------------------------------ user.preferences, user.environment
 7032:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 7033: 	    if (($uname eq $env{'user.name'}) &&
 7034: 		($udom eq $env{'user.domain'})) {
 7035: 		return $env{join('.',('environment',$qualifierrest))};
 7036: 	    } else {
 7037: 		my %returnhash;
 7038: 		if (!$publicuser) {
 7039: 		    %returnhash=&userenvironment($udom,$uname,
 7040: 						 $qualifierrest);
 7041: 		}
 7042: 		return $returnhash{$qualifierrest};
 7043: 	    }
 7044: # ----------------------------------------------------------------- user.course
 7045:         } elsif ($space eq 'course') {
 7046: 	    # FIXME - not supporting calls for a specific user
 7047:             return $env{join('.',('request.course',$qualifier))};
 7048: # ------------------------------------------------------------------- user.role
 7049:         } elsif ($space eq 'role') {
 7050: 	    # FIXME - not supporting calls for a specific user
 7051:             my ($role,$where)=split(/\./,$env{'request.role'});
 7052:             if ($qualifier eq 'value') {
 7053: 		return $role;
 7054:             } elsif ($qualifier eq 'extent') {
 7055:                 return $where;
 7056:             }
 7057: # ----------------------------------------------------------------- user.domain
 7058:         } elsif ($space eq 'domain') {
 7059:             return $udom;
 7060: # ------------------------------------------------------------------- user.name
 7061:         } elsif ($space eq 'name') {
 7062:             return $uname;
 7063: # ---------------------------------------------------- Any other user namespace
 7064:         } else {
 7065: 	    my %reply;
 7066: 	    if (!$publicuser) {
 7067: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 7068: 	    }
 7069: 	    return $reply{$qualifierrest};
 7070:         }
 7071:     } elsif ($realm eq 'query') {
 7072: # ---------------------------------------------- pull stuff out of query string
 7073:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 7074: 						[$spacequalifierrest]);
 7075: 	return $env{'form.'.$spacequalifierrest}; 
 7076:    } elsif ($realm eq 'request') {
 7077: # ------------------------------------------------------------- request.browser
 7078:         if ($space eq 'browser') {
 7079: 	    if ($qualifier eq 'textremote') {
 7080: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 7081: 		    return 1;
 7082: 		} else {
 7083: 		    return 0;
 7084: 		}
 7085: 	    } else {
 7086: 		return $env{'browser.'.$qualifier};
 7087: 	    }
 7088: # ------------------------------------------------------------ request.filename
 7089:         } else {
 7090:             return $env{'request.'.$spacequalifierrest};
 7091:         }
 7092:     } elsif ($realm eq 'course') {
 7093: # ---------------------------------------------------------- course.description
 7094:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 7095:     } elsif ($realm eq 'resource') {
 7096: 
 7097: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 7098: 	    if (!$symbparm) { $symbparm=&symbread(); }
 7099: 	}
 7100: 
 7101: 	if ($space eq 'title') {
 7102: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 7103: 	    return &gettitle($symbparm);
 7104: 	}
 7105: 	
 7106: 	if ($space eq 'map') {
 7107: 	    my ($map) = &decode_symb($symbparm);
 7108: 	    return &symbread($map);
 7109: 	}
 7110: 	if ($space eq 'filename') {
 7111: 	    if ($symbparm) {
 7112: 		return &clutter((&decode_symb($symbparm))[2]);
 7113: 	    }
 7114: 	    return &hreflocation('',$env{'request.filename'});
 7115: 	}
 7116: 
 7117: 	my ($section, $group, @groups);
 7118: 	my ($courselevelm,$courselevel);
 7119: 	if ($symbparm && defined($courseid) && 
 7120: 	    $courseid eq $env{'request.course.id'}) {
 7121: 
 7122: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 7123: 
 7124: # ----------------------------------------------------- Cascading lookup scheme
 7125: 	    my $symbp=$symbparm;
 7126: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 7127: 
 7128: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 7129: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 7130: 
 7131: 	    if (($env{'user.name'} eq $uname) &&
 7132: 		($env{'user.domain'} eq $udom)) {
 7133: 		$section=$env{'request.course.sec'};
 7134:                 @groups = split(/:/,$env{'request.course.groups'});  
 7135:                 @groups=&sort_course_groups($courseid,@groups); 
 7136: 	    } else {
 7137: 		if (! defined($usection)) {
 7138: 		    $section=&getsection($udom,$uname,$courseid);
 7139: 		} else {
 7140: 		    $section = $usection;
 7141: 		}
 7142:                 @groups = &get_users_groups($udom,$uname,$courseid);
 7143: 	    }
 7144: 
 7145: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 7146: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 7147: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 7148: 
 7149: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 7150: 	    my $courselevelr=$courseid.'.'.$symbparm;
 7151: 	    $courselevelm=$courseid.'.'.$mapparm;
 7152: 
 7153: # ----------------------------------------------------------- first, check user
 7154: 
 7155: 	    my $userreply=&resdata($uname,$udom,'user',
 7156: 				       ([$courselevelr,'resource'],
 7157: 					[$courselevelm,'map'     ],
 7158: 					[$courselevel, 'course'  ]));
 7159: 	    if (defined($userreply)) { return &get_reply($userreply); }
 7160: 
 7161: # ------------------------------------------------ second, check some of course
 7162:             my $coursereply;
 7163:             if (@groups > 0) {
 7164:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 7165:                                        $mapparm,$spacequalifierrest);
 7166:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 7167:             }
 7168: 
 7169: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7170: 				  $env{'course.'.$courseid.'.domain'},
 7171: 				  'course',
 7172: 				  ([$seclevelr,   'resource'],
 7173: 				   [$seclevelm,   'map'     ],
 7174: 				   [$seclevel,    'course'  ],
 7175: 				   [$courselevelr,'resource']));
 7176: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7177: 
 7178: # ------------------------------------------------------ third, check map parms
 7179: 	    my %parmhash=();
 7180: 	    my $thisparm='';
 7181: 	    if (tie(%parmhash,'GDBM_File',
 7182: 		    $env{'request.course.fn'}.'_parms.db',
 7183: 		    &GDBM_READER(),0640)) {
 7184: 		$thisparm=$parmhash{$symbparm};
 7185: 		untie(%parmhash);
 7186: 	    }
 7187: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 7188: 	}
 7189: # ------------------------------------------ fourth, look in resource metadata
 7190: 
 7191: 	$spacequalifierrest=~s/\./\_/;
 7192: 	my $filename;
 7193: 	if (!$symbparm) { $symbparm=&symbread(); }
 7194: 	if ($symbparm) {
 7195: 	    $filename=(&decode_symb($symbparm))[2];
 7196: 	} else {
 7197: 	    $filename=$env{'request.filename'};
 7198: 	}
 7199: 	my $metadata=&metadata($filename,$spacequalifierrest);
 7200: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7201: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 7202: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7203: 
 7204: # ---------------------------------------------- fourth, look in rest of course
 7205: 	if ($symbparm && defined($courseid) && 
 7206: 	    $courseid eq $env{'request.course.id'}) {
 7207: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7208: 				     $env{'course.'.$courseid.'.domain'},
 7209: 				     'course',
 7210: 				     ([$courselevelm,'map'   ],
 7211: 				      [$courselevel, 'course']));
 7212: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7213: 	}
 7214: # ------------------------------------------------------------------ Cascade up
 7215: 	unless ($space eq '0') {
 7216: 	    my @parts=split(/_/,$space);
 7217: 	    my $id=pop(@parts);
 7218: 	    my $part=join('_',@parts);
 7219: 	    if ($part eq '') { $part='0'; }
 7220: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 7221: 				 $symbparm,$udom,$uname,$section,1);
 7222: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 7223: 	}
 7224: 	if ($recurse) { return undef; }
 7225: 	my $pack_def=&packages_tab_default($filename,$varname);
 7226: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 7227: # ---------------------------------------------------- Any other user namespace
 7228:     } elsif ($realm eq 'environment') {
 7229: # ----------------------------------------------------------------- environment
 7230: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 7231: 	    return $env{'environment.'.$spacequalifierrest};
 7232: 	} else {
 7233: 	    if ($uname eq 'anonymous' && $udom eq '') {
 7234: 		return '';
 7235: 	    }
 7236: 	    my %returnhash=&userenvironment($udom,$uname,
 7237: 					    $spacequalifierrest);
 7238: 	    return $returnhash{$spacequalifierrest};
 7239: 	}
 7240:     } elsif ($realm eq 'system') {
 7241: # ----------------------------------------------------------------- system.time
 7242: 	if ($space eq 'time') {
 7243: 	    return time;
 7244:         }
 7245:     } elsif ($realm eq 'server') {
 7246: # ----------------------------------------------------------------- system.time
 7247: 	if ($space eq 'name') {
 7248: 	    return $ENV{'SERVER_NAME'};
 7249:         }
 7250:     }
 7251:     return '';
 7252: }
 7253: 
 7254: sub get_reply {
 7255:     my ($reply_value) = @_;
 7256:     if (ref($reply_value) eq 'ARRAY') {
 7257:         if (wantarray) {
 7258: 	    return @$reply_value;
 7259:         }
 7260:         return $reply_value->[0];
 7261:     } else {
 7262:         return $reply_value;
 7263:     }
 7264: }
 7265: 
 7266: sub check_group_parms {
 7267:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 7268:     my @groupitems = ();
 7269:     my $resultitem;
 7270:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 7271:     foreach my $group (@{$groups}) {
 7272:         foreach my $level (@levels) {
 7273:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 7274:              push(@groupitems,[$item,$level->[1]]);
 7275:         }
 7276:     }
 7277:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 7278:                             $env{'course.'.$courseid.'.domain'},
 7279:                                      'course',@groupitems);
 7280:     return $coursereply;
 7281: }
 7282: 
 7283: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 7284:     my ($courseid,@groups) = @_;
 7285:     @groups = sort(@groups);
 7286:     return @groups;
 7287: }
 7288: 
 7289: sub packages_tab_default {
 7290:     my ($uri,$varname)=@_;
 7291:     my (undef,$part,$name)=split(/\./,$varname);
 7292: 
 7293:     my (@extension,@specifics,$do_default);
 7294:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 7295: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 7296: 	if ($pack_type eq 'default') {
 7297: 	    $do_default=1;
 7298: 	} elsif ($pack_type eq 'extension') {
 7299: 	    push(@extension,[$package,$pack_type,$pack_part]);
 7300: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 7301: 	    # only look at packages defaults for packages that this id is
 7302: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 7303: 	}
 7304:     }
 7305:     # first look for a package that matches the requested part id
 7306:     foreach my $package (@specifics) {
 7307: 	my (undef,$pack_type,$pack_part)=@{$package};
 7308: 	next if ($pack_part ne $part);
 7309: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7310: 	    return $packagetab{"$pack_type&$name&default"};
 7311: 	}
 7312:     }
 7313:     # look for any possible matching non extension_ package
 7314:     foreach my $package (@specifics) {
 7315: 	my (undef,$pack_type,$pack_part)=@{$package};
 7316: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7317: 	    return $packagetab{"$pack_type&$name&default"};
 7318: 	}
 7319: 	if ($pack_type eq 'part') { $pack_part='0'; }
 7320: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 7321: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 7322: 	}
 7323:     }
 7324:     # look for any posible extension_ match
 7325:     foreach my $package (@extension) {
 7326: 	my ($package,$pack_type)=@{$package};
 7327: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7328: 	    return $packagetab{"$pack_type&$name&default"};
 7329: 	}
 7330: 	if (defined($packagetab{$package."&$name&default"})) {
 7331: 	    return $packagetab{$package."&$name&default"};
 7332: 	}
 7333:     }
 7334:     # look for a global default setting
 7335:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 7336: 	return $packagetab{"default&$name&default"};
 7337:     }
 7338:     return undef;
 7339: }
 7340: 
 7341: sub add_prefix_and_part {
 7342:     my ($prefix,$part)=@_;
 7343:     my $keyroot;
 7344:     if (defined($prefix) && $prefix !~ /^__/) {
 7345: 	# prefix that has a part already
 7346: 	$keyroot=$prefix;
 7347:     } elsif (defined($prefix)) {
 7348: 	# prefix that is missing a part
 7349: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 7350:     } else {
 7351: 	# no prefix at all
 7352: 	if (defined($part)) { $keyroot='_'.$part; }
 7353:     }
 7354:     return $keyroot;
 7355: }
 7356: 
 7357: # ---------------------------------------------------------------- Get metadata
 7358: 
 7359: my %metaentry;
 7360: sub metadata {
 7361:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 7362:     $uri=&declutter($uri);
 7363:     # if it is a non metadata possible uri return quickly
 7364:     if (($uri eq '') || 
 7365: 	(($uri =~ m|^/*adm/|) && 
 7366: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 7367:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 7368: 	return undef;
 7369:     }
 7370:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 7371: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 7372: 	return undef;
 7373:     }
 7374:     my $filename=$uri;
 7375:     $uri=~s/\.meta$//;
 7376: #
 7377: # Is the metadata already cached?
 7378: # Look at timestamp of caching
 7379: # Everything is cached by the main uri, libraries are never directly cached
 7380: #
 7381:     if (!defined($liburi)) {
 7382: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 7383: 	if (defined($cached)) { return $result->{':'.$what}; }
 7384:     }
 7385:     {
 7386: #
 7387: # Is this a recursive call for a library?
 7388: #
 7389: #	if (! exists($metacache{$uri})) {
 7390: #	    $metacache{$uri}={};
 7391: #	}
 7392: 	my $cachetime = 60*60;
 7393:         if ($liburi) {
 7394: 	    $liburi=&declutter($liburi);
 7395:             $filename=$liburi;
 7396:         } else {
 7397: 	    &devalidate_cache_new('meta',$uri);
 7398: 	    undef(%metaentry);
 7399: 	}
 7400:         my %metathesekeys=();
 7401:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 7402: 	my $metastring;
 7403: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 7404: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 7405: 	    $metastring = 
 7406: 		&Apache::lonnet::ssi_body($which,
 7407: 					  ('grade_target' => 'meta'));
 7408: 	    $cachetime = 1; # only want this cached in the child not long term
 7409: 	} elsif ($uri !~ m -^(editupload)/-) {
 7410: 	    my $file=&filelocation('',&clutter($filename));
 7411: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 7412: 	    $metastring=&getfile($file);
 7413: 	}
 7414:         my $parser=HTML::LCParser->new(\$metastring);
 7415:         my $token;
 7416:         undef %metathesekeys;
 7417:         while ($token=$parser->get_token) {
 7418: 	    if ($token->[0] eq 'S') {
 7419: 		if (defined($token->[2]->{'package'})) {
 7420: #
 7421: # This is a package - get package info
 7422: #
 7423: 		    my $package=$token->[2]->{'package'};
 7424: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7425: 		    if (defined($token->[2]->{'id'})) { 
 7426: 			$keyroot.='_'.$token->[2]->{'id'}; 
 7427: 		    }
 7428: 		    if ($metaentry{':packages'}) {
 7429: 			$metaentry{':packages'}.=','.$package.$keyroot;
 7430: 		    } else {
 7431: 			$metaentry{':packages'}=$package.$keyroot;
 7432: 		    }
 7433: 		    foreach my $pack_entry (keys(%packagetab)) {
 7434: 			my $part=$keyroot;
 7435: 			$part=~s/^\_//;
 7436: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 7437: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 7438: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 7439: 			    # ignore package.tab specified default values
 7440:                             # here &package_tab_default() will fetch those
 7441: 			    if ($subp eq 'default') { next; }
 7442: 			    my $value=$packagetab{$pack_entry};
 7443: 			    my $unikey;
 7444: 			    if ($pack =~ /_0$/) {
 7445: 				$unikey='parameter_0_'.$name;
 7446: 				$part=0;
 7447: 			    } else {
 7448: 				$unikey='parameter'.$keyroot.'_'.$name;
 7449: 			    }
 7450: 			    if ($subp eq 'display') {
 7451: 				$value.=' [Part: '.$part.']';
 7452: 			    }
 7453: 			    $metaentry{':'.$unikey.'.part'}=$part;
 7454: 			    $metathesekeys{$unikey}=1;
 7455: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7456: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 7457: 			    }
 7458: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 7459: 				$metaentry{':'.$unikey}=
 7460: 				    $metaentry{':'.$unikey.'.default'};
 7461: 			    }
 7462: 			}
 7463: 		    }
 7464: 		} else {
 7465: #
 7466: # This is not a package - some other kind of start tag
 7467: #
 7468: 		    my $entry=$token->[1];
 7469: 		    my $unikey;
 7470: 		    if ($entry eq 'import') {
 7471: 			$unikey='';
 7472: 		    } else {
 7473: 			$unikey=$entry;
 7474: 		    }
 7475: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7476: 
 7477: 		    if (defined($token->[2]->{'id'})) { 
 7478: 			$unikey.='_'.$token->[2]->{'id'}; 
 7479: 		    }
 7480: 
 7481: 		    if ($entry eq 'import') {
 7482: #
 7483: # Importing a library here
 7484: #
 7485: 			if ($depthcount<20) {
 7486: 			    my $location=$parser->get_text('/import');
 7487: 			    my $dir=$filename;
 7488: 			    $dir=~s|[^/]*$||;
 7489: 			    $location=&filelocation($dir,$location);
 7490: 			    my $metadata = 
 7491: 				&metadata($uri,'keys', $location,$unikey,
 7492: 					  $depthcount+1);
 7493: 			    foreach my $meta (split(',',$metadata)) {
 7494: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 7495: 				$metathesekeys{$meta}=1;
 7496: 			    }
 7497: 			}
 7498: 		    } else { 
 7499: 			
 7500: 			if (defined($token->[2]->{'name'})) { 
 7501: 			    $unikey.='_'.$token->[2]->{'name'}; 
 7502: 			}
 7503: 			$metathesekeys{$unikey}=1;
 7504: 			foreach my $param (@{$token->[3]}) {
 7505: 			    $metaentry{':'.$unikey.'.'.$param} =
 7506: 				$token->[2]->{$param};
 7507: 			}
 7508: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 7509: 			my $default=$metaentry{':'.$unikey.'.default'};
 7510: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 7511: 		 # only ws inside the tag, and not in default, so use default
 7512: 		 # as value
 7513: 			    $metaentry{':'.$unikey}=$default;
 7514: 			} elsif ( $internaltext =~ /\S/ ) {
 7515: 		  # something interesting inside the tag
 7516: 			    $metaentry{':'.$unikey}=$internaltext;
 7517: 			} else {
 7518: 		  # no interesting values, don't set a default
 7519: 			}
 7520: # end of not-a-package not-a-library import
 7521: 		    }
 7522: # end of not-a-package start tag
 7523: 		}
 7524: # the next is the end of "start tag"
 7525: 	    }
 7526: 	}
 7527: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 7528: 	$extension = lc($extension);
 7529: 	if ($extension eq 'htm') { $extension='html'; }
 7530: 
 7531: 	foreach my $key (keys(%packagetab)) {
 7532: 	    #no specific packages #how's our extension
 7533: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 7534: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 7535: 					 \%metathesekeys);
 7536: 	}
 7537: 
 7538: 	if (!exists($metaentry{':packages'})
 7539: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 7540: 	    foreach my $key (keys(%packagetab)) {
 7541: 		#no specific packages well let's get default then
 7542: 		if ($key!~/^default&/) { next; }
 7543: 		&metadata_create_package_def($uri,$key,'default',
 7544: 					     \%metathesekeys);
 7545: 	    }
 7546: 	}
 7547: # are there custom rights to evaluate
 7548: 	if ($metaentry{':copyright'} eq 'custom') {
 7549: 
 7550:     #
 7551:     # Importing a rights file here
 7552:     #
 7553: 	    unless ($depthcount) {
 7554: 		my $location=$metaentry{':customdistributionfile'};
 7555: 		my $dir=$filename;
 7556: 		$dir=~s|[^/]*$||;
 7557: 		$location=&filelocation($dir,$location);
 7558: 		my $rights_metadata =
 7559: 		    &metadata($uri,'keys',$location,'_rights',
 7560: 			      $depthcount+1);
 7561: 		foreach my $rights (split(',',$rights_metadata)) {
 7562: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 7563: 		    $metathesekeys{$rights}=1;
 7564: 		}
 7565: 	    }
 7566: 	}
 7567: 	# uniqifiy package listing
 7568: 	my %seen;
 7569: 	my @uniq_packages =
 7570: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 7571: 	$metaentry{':packages'} = join(',',@uniq_packages);
 7572: 
 7573: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 7574: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 7575: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 7576: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 7577: # this is the end of "was not already recently cached
 7578:     }
 7579:     return $metaentry{':'.$what};
 7580: }
 7581: 
 7582: sub metadata_create_package_def {
 7583:     my ($uri,$key,$package,$metathesekeys)=@_;
 7584:     my ($pack,$name,$subp)=split(/\&/,$key);
 7585:     if ($subp eq 'default') { next; }
 7586:     
 7587:     if (defined($metaentry{':packages'})) {
 7588: 	$metaentry{':packages'}.=','.$package;
 7589:     } else {
 7590: 	$metaentry{':packages'}=$package;
 7591:     }
 7592:     my $value=$packagetab{$key};
 7593:     my $unikey;
 7594:     $unikey='parameter_0_'.$name;
 7595:     $metaentry{':'.$unikey.'.part'}=0;
 7596:     $$metathesekeys{$unikey}=1;
 7597:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7598: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 7599:     }
 7600:     if (defined($metaentry{':'.$unikey.'.default'})) {
 7601: 	$metaentry{':'.$unikey}=
 7602: 	    $metaentry{':'.$unikey.'.default'};
 7603:     }
 7604: }
 7605: 
 7606: sub metadata_generate_part0 {
 7607:     my ($metadata,$metacache,$uri) = @_;
 7608:     my %allnames;
 7609:     foreach my $metakey (keys(%$metadata)) {
 7610: 	if ($metakey=~/^parameter\_(.*)/) {
 7611: 	  my $part=$$metacache{':'.$metakey.'.part'};
 7612: 	  my $name=$$metacache{':'.$metakey.'.name'};
 7613: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 7614: 	    $allnames{$name}=$part;
 7615: 	  }
 7616: 	}
 7617:     }
 7618:     foreach my $name (keys(%allnames)) {
 7619:       $$metadata{"parameter_0_$name"}=1;
 7620:       my $key=":parameter_0_$name";
 7621:       $$metacache{"$key.part"}='0';
 7622:       $$metacache{"$key.name"}=$name;
 7623:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 7624: 					   $allnames{$name}.'_'.$name.
 7625: 					   '.type'};
 7626:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 7627: 			     '.display'};
 7628:       my $expr='[Part: '.$allnames{$name}.']';
 7629:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 7630:       $$metacache{"$key.display"}=$olddis;
 7631:     }
 7632: }
 7633: 
 7634: # ------------------------------------------------------ Devalidate title cache
 7635: 
 7636: sub devalidate_title_cache {
 7637:     my ($url)=@_;
 7638:     if (!$env{'request.course.id'}) { return; }
 7639:     my $symb=&symbread($url);
 7640:     if (!$symb) { return; }
 7641:     my $key=$env{'request.course.id'}."\0".$symb;
 7642:     &devalidate_cache_new('title',$key);
 7643: }
 7644: 
 7645: # ------------------------------------------------- Get the title of a resource
 7646: 
 7647: sub gettitle {
 7648:     my $urlsymb=shift;
 7649:     my $symb=&symbread($urlsymb);
 7650:     if ($symb) {
 7651: 	my $key=$env{'request.course.id'}."\0".$symb;
 7652: 	my ($result,$cached)=&is_cached_new('title',$key);
 7653: 	if (defined($cached)) { 
 7654: 	    return $result;
 7655: 	}
 7656: 	my ($map,$resid,$url)=&decode_symb($symb);
 7657: 	my $title='';
 7658: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 7659: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 7660: 	} else {
 7661: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7662: 		    &GDBM_READER(),0640)) {
 7663: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 7664: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 7665: 		untie(%bighash);
 7666: 	    }
 7667: 	}
 7668: 	$title=~s/\&colon\;/\:/gs;
 7669: 	if ($title) {
 7670: 	    return &do_cache_new('title',$key,$title,600);
 7671: 	}
 7672: 	$urlsymb=$url;
 7673:     }
 7674:     my $title=&metadata($urlsymb,'title');
 7675:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 7676:     return $title;
 7677: }
 7678: 
 7679: sub get_slot {
 7680:     my ($which,$cnum,$cdom)=@_;
 7681:     if (!$cnum || !$cdom) {
 7682: 	(undef,my $courseid)=&whichuser();
 7683: 	$cdom=$env{'course.'.$courseid.'.domain'};
 7684: 	$cnum=$env{'course.'.$courseid.'.num'};
 7685:     }
 7686:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 7687:     my %slotinfo;
 7688:     if (exists($remembered{$key})) {
 7689: 	$slotinfo{$which} = $remembered{$key};
 7690:     } else {
 7691: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 7692: 	&Apache::lonhomework::showhash(%slotinfo);
 7693: 	my ($tmp)=keys(%slotinfo);
 7694: 	if ($tmp=~/^error:/) { return (); }
 7695: 	$remembered{$key} = $slotinfo{$which};
 7696:     }
 7697:     if (ref($slotinfo{$which}) eq 'HASH') {
 7698: 	return %{$slotinfo{$which}};
 7699:     }
 7700:     return $slotinfo{$which};
 7701: }
 7702: # ------------------------------------------------- Update symbolic store links
 7703: 
 7704: sub symblist {
 7705:     my ($mapname,%newhash)=@_;
 7706:     $mapname=&deversion(&declutter($mapname));
 7707:     my %hash;
 7708:     if (($env{'request.course.fn'}) && (%newhash)) {
 7709:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7710:                       &GDBM_WRCREAT(),0640)) {
 7711: 	    foreach my $url (keys %newhash) {
 7712: 		next if ($url eq 'last_known'
 7713: 			 && $env{'form.no_update_last_known'});
 7714: 		$hash{declutter($url)}=&encode_symb($mapname,
 7715: 						    $newhash{$url}->[1],
 7716: 						    $newhash{$url}->[0]);
 7717:             }
 7718:             if (untie(%hash)) {
 7719: 		return 'ok';
 7720:             }
 7721:         }
 7722:     }
 7723:     return 'error';
 7724: }
 7725: 
 7726: # --------------------------------------------------------------- Verify a symb
 7727: 
 7728: sub symbverify {
 7729:     my ($symb,$thisurl)=@_;
 7730:     my $thisfn=$thisurl;
 7731:     $thisfn=&declutter($thisfn);
 7732: # direct jump to resource in page or to a sequence - will construct own symbs
 7733:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 7734: # check URL part
 7735:     my ($map,$resid,$url)=&decode_symb($symb);
 7736: 
 7737:     unless ($url eq $thisfn) { return 0; }
 7738: 
 7739:     $symb=&symbclean($symb);
 7740:     $thisurl=&deversion($thisurl);
 7741:     $thisfn=&deversion($thisfn);
 7742: 
 7743:     my %bighash;
 7744:     my $okay=0;
 7745: 
 7746:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7747:                             &GDBM_READER(),0640)) {
 7748:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 7749:         unless ($ids) { 
 7750:            $ids=$bighash{'ids_/'.$thisurl};
 7751:         }
 7752:         if ($ids) {
 7753: # ------------------------------------------------------------------- Has ID(s)
 7754: 	    foreach my $id (split(/\,/,$ids)) {
 7755: 	       my ($mapid,$resid)=split(/\./,$id);
 7756:                if (
 7757:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 7758:    eq $symb) { 
 7759: 		   if (($env{'request.role.adv'}) ||
 7760: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 7761: 		       $okay=1; 
 7762: 		   }
 7763: 	       }
 7764: 	   }
 7765:         }
 7766: 	untie(%bighash);
 7767:     }
 7768:     return $okay;
 7769: }
 7770: 
 7771: # --------------------------------------------------------------- Clean-up symb
 7772: 
 7773: sub symbclean {
 7774:     my $symb=shift;
 7775:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7776: # remove version from map
 7777:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 7778: 
 7779: # remove version from URL
 7780:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 7781: 
 7782: # remove wrapper
 7783: 
 7784:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 7785:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 7786:     return $symb;
 7787: }
 7788: 
 7789: # ---------------------------------------------- Split symb to find map and url
 7790: 
 7791: sub encode_symb {
 7792:     my ($map,$resid,$url)=@_;
 7793:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 7794: }
 7795: 
 7796: sub decode_symb {
 7797:     my $symb=shift;
 7798:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7799:     my ($map,$resid,$url)=split(/___/,$symb);
 7800:     return (&fixversion($map),$resid,&fixversion($url));
 7801: }
 7802: 
 7803: sub fixversion {
 7804:     my $fn=shift;
 7805:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 7806:     my %bighash;
 7807:     my $uri=&clutter($fn);
 7808:     my $key=$env{'request.course.id'}.'_'.$uri;
 7809: # is this cached?
 7810:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 7811:     if (defined($cached)) { return $result; }
 7812: # unfortunately not cached, or expired
 7813:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7814: 	    &GDBM_READER(),0640)) {
 7815:  	if ($bighash{'version_'.$uri}) {
 7816:  	    my $version=$bighash{'version_'.$uri};
 7817:  	    unless (($version eq 'mostrecent') || 
 7818: 		    ($version==&getversion($uri))) {
 7819:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 7820:  	    }
 7821:  	}
 7822:  	untie %bighash;
 7823:     }
 7824:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 7825: }
 7826: 
 7827: sub deversion {
 7828:     my $url=shift;
 7829:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 7830:     return $url;
 7831: }
 7832: 
 7833: # ------------------------------------------------------ Return symb list entry
 7834: 
 7835: sub symbread {
 7836:     my ($thisfn,$donotrecurse)=@_;
 7837:     my $cache_str='request.symbread.cached.'.$thisfn;
 7838:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 7839: # no filename provided? try from environment
 7840:     unless ($thisfn) {
 7841:         if ($env{'request.symb'}) {
 7842: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 7843: 	}
 7844: 	$thisfn=$env{'request.filename'};
 7845:     }
 7846:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7847: # is that filename actually a symb? Verify, clean, and return
 7848:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 7849: 	if (&symbverify($thisfn,$1)) {
 7850: 	    return $env{$cache_str}=&symbclean($thisfn);
 7851: 	}
 7852:     }
 7853:     $thisfn=declutter($thisfn);
 7854:     my %hash;
 7855:     my %bighash;
 7856:     my $syval='';
 7857:     if (($env{'request.course.fn'}) && ($thisfn)) {
 7858:         my $targetfn = $thisfn;
 7859:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 7860:             $targetfn = 'adm/wrapper/'.$thisfn;
 7861:         }
 7862: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 7863: 	    $targetfn=$1;
 7864: 	}
 7865:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7866:                       &GDBM_READER(),0640)) {
 7867: 	    $syval=$hash{$targetfn};
 7868:             untie(%hash);
 7869:         }
 7870: # ---------------------------------------------------------- There was an entry
 7871:         if ($syval) {
 7872: 	    #unless ($syval=~/\_\d+$/) {
 7873: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 7874: 		    #&appenv({'request.ambiguous' => $thisfn});
 7875: 		    #return $env{$cache_str}='';
 7876: 		#}    
 7877: 		#$syval.=$1;
 7878: 	    #}
 7879:         } else {
 7880: # ------------------------------------------------------- Was not in symb table
 7881:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7882:                             &GDBM_READER(),0640)) {
 7883: # ---------------------------------------------- Get ID(s) for current resource
 7884:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 7885:               unless ($ids) { 
 7886:                  $ids=$bighash{'ids_/'.$thisfn};
 7887:               }
 7888:               unless ($ids) {
 7889: # alias?
 7890: 		  $ids=$bighash{'mapalias_'.$thisfn};
 7891:               }
 7892:               if ($ids) {
 7893: # ------------------------------------------------------------------- Has ID(s)
 7894:                  my @possibilities=split(/\,/,$ids);
 7895:                  if ($#possibilities==0) {
 7896: # ----------------------------------------------- There is only one possibility
 7897: 		     my ($mapid,$resid)=split(/\./,$ids);
 7898: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7899: 						    $resid,$thisfn);
 7900:                  } elsif (!$donotrecurse) {
 7901: # ------------------------------------------ There is more than one possibility
 7902:                      my $realpossible=0;
 7903:                      foreach my $id (@possibilities) {
 7904: 			 my $file=$bighash{'src_'.$id};
 7905:                          if (&allowed('bre',$file)) {
 7906:          		    my ($mapid,$resid)=split(/\./,$id);
 7907:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 7908: 				$realpossible++;
 7909:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7910: 						    $resid,$thisfn);
 7911:                             }
 7912: 			 }
 7913:                      }
 7914: 		     if ($realpossible!=1) { $syval=''; }
 7915:                  } else {
 7916:                      $syval='';
 7917:                  }
 7918: 	      }
 7919:               untie(%bighash)
 7920:            }
 7921:         }
 7922:         if ($syval) {
 7923: 	    return $env{$cache_str}=$syval;
 7924:         }
 7925:     }
 7926:     &appenv({'request.ambiguous' => $thisfn});
 7927:     return $env{$cache_str}='';
 7928: }
 7929: 
 7930: # ---------------------------------------------------------- Return random seed
 7931: 
 7932: sub numval {
 7933:     my $txt=shift;
 7934:     $txt=~tr/A-J/0-9/;
 7935:     $txt=~tr/a-j/0-9/;
 7936:     $txt=~tr/K-T/0-9/;
 7937:     $txt=~tr/k-t/0-9/;
 7938:     $txt=~tr/U-Z/0-5/;
 7939:     $txt=~tr/u-z/0-5/;
 7940:     $txt=~s/\D//g;
 7941:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 7942:     return int($txt);
 7943: }
 7944: 
 7945: sub numval2 {
 7946:     my $txt=shift;
 7947:     $txt=~tr/A-J/0-9/;
 7948:     $txt=~tr/a-j/0-9/;
 7949:     $txt=~tr/K-T/0-9/;
 7950:     $txt=~tr/k-t/0-9/;
 7951:     $txt=~tr/U-Z/0-5/;
 7952:     $txt=~tr/u-z/0-5/;
 7953:     $txt=~s/\D//g;
 7954:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7955:     my $total;
 7956:     foreach my $val (@txts) { $total+=$val; }
 7957:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 7958:     return int($total);
 7959: }
 7960: 
 7961: sub numval3 {
 7962:     use integer;
 7963:     my $txt=shift;
 7964:     $txt=~tr/A-J/0-9/;
 7965:     $txt=~tr/a-j/0-9/;
 7966:     $txt=~tr/K-T/0-9/;
 7967:     $txt=~tr/k-t/0-9/;
 7968:     $txt=~tr/U-Z/0-5/;
 7969:     $txt=~tr/u-z/0-5/;
 7970:     $txt=~s/\D//g;
 7971:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7972:     my $total;
 7973:     foreach my $val (@txts) { $total+=$val; }
 7974:     if ($_64bit) { $total=(($total<<32)>>32); }
 7975:     return $total;
 7976: }
 7977: 
 7978: sub digest {
 7979:     my ($data)=@_;
 7980:     my $digest=&Digest::MD5::md5($data);
 7981:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 7982:     my ($e,$f);
 7983:     {
 7984:         use integer;
 7985:         $e=($a+$b);
 7986:         $f=($c+$d);
 7987:         if ($_64bit) {
 7988:             $e=(($e<<32)>>32);
 7989:             $f=(($f<<32)>>32);
 7990:         }
 7991:     }
 7992:     if (wantarray) {
 7993: 	return ($e,$f);
 7994:     } else {
 7995: 	my $g;
 7996: 	{
 7997: 	    use integer;
 7998: 	    $g=($e+$f);
 7999: 	    if ($_64bit) {
 8000: 		$g=(($g<<32)>>32);
 8001: 	    }
 8002: 	}
 8003: 	return $g;
 8004:     }
 8005: }
 8006: 
 8007: sub latest_rnd_algorithm_id {
 8008:     return '64bit5';
 8009: }
 8010: 
 8011: sub get_rand_alg {
 8012:     my ($courseid)=@_;
 8013:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 8014:     if ($courseid) {
 8015: 	return $env{"course.$courseid.rndseed"};
 8016:     }
 8017:     return &latest_rnd_algorithm_id();
 8018: }
 8019: 
 8020: sub validCODE {
 8021:     my ($CODE)=@_;
 8022:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 8023:     return 0;
 8024: }
 8025: 
 8026: sub getCODE {
 8027:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 8028:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 8029: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 8030: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 8031: 	return $Apache::lonhomework::history{'resource.CODE'};
 8032:     }
 8033:     return undef;
 8034: }
 8035: 
 8036: sub rndseed {
 8037:     my ($symb,$courseid,$domain,$username)=@_;
 8038:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 8039:     if (!defined($symb)) {
 8040: 	unless ($symb=$wsymb) { return time; }
 8041:     }
 8042:     if (!$courseid) { $courseid=$wcourseid; }
 8043:     if (!$domain) { $domain=$wdomain; }
 8044:     if (!$username) { $username=$wusername }
 8045:     my $which=&get_rand_alg();
 8046: 
 8047:     if (defined(&getCODE())) {
 8048: 	if ($which eq '64bit5') {
 8049: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 8050: 	} elsif ($which eq '64bit4') {
 8051: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 8052: 	} else {
 8053: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 8054: 	}
 8055:     } elsif ($which eq '64bit5') {
 8056: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 8057:     } elsif ($which eq '64bit4') {
 8058: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 8059:     } elsif ($which eq '64bit3') {
 8060: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 8061:     } elsif ($which eq '64bit2') {
 8062: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 8063:     } elsif ($which eq '64bit') {
 8064: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 8065:     }
 8066:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 8067: }
 8068: 
 8069: sub rndseed_32bit {
 8070:     my ($symb,$courseid,$domain,$username)=@_;
 8071:     {
 8072: 	use integer;
 8073: 	my $symbchck=unpack("%32C*",$symb) << 27;
 8074: 	my $symbseed=numval($symb) << 22;
 8075: 	my $namechck=unpack("%32C*",$username) << 17;
 8076: 	my $nameseed=numval($username) << 12;
 8077: 	my $domainseed=unpack("%32C*",$domain) << 7;
 8078: 	my $courseseed=unpack("%32C*",$courseid);
 8079: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 8080: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8081: 	#&logthis("rndseed :$num:$symb");
 8082: 	if ($_64bit) { $num=(($num<<32)>>32); }
 8083: 	return $num;
 8084:     }
 8085: }
 8086: 
 8087: sub rndseed_64bit {
 8088:     my ($symb,$courseid,$domain,$username)=@_;
 8089:     {
 8090: 	use integer;
 8091: 	my $symbchck=unpack("%32S*",$symb) << 21;
 8092: 	my $symbseed=numval($symb) << 10;
 8093: 	my $namechck=unpack("%32S*",$username);
 8094: 	
 8095: 	my $nameseed=numval($username) << 21;
 8096: 	my $domainseed=unpack("%32S*",$domain) << 10;
 8097: 	my $courseseed=unpack("%32S*",$courseid);
 8098: 	
 8099: 	my $num1=$symbchck+$symbseed+$namechck;
 8100: 	my $num2=$nameseed+$domainseed+$courseseed;
 8101: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8102: 	#&logthis("rndseed :$num:$symb");
 8103: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8104: 	return "$num1,$num2";
 8105:     }
 8106: }
 8107: 
 8108: sub rndseed_64bit2 {
 8109:     my ($symb,$courseid,$domain,$username)=@_;
 8110:     {
 8111: 	use integer;
 8112: 	# strings need to be an even # of cahracters long, it it is odd the
 8113:         # last characters gets thrown away
 8114: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8115: 	my $symbseed=numval($symb) << 10;
 8116: 	my $namechck=unpack("%32S*",$username.' ');
 8117: 	
 8118: 	my $nameseed=numval($username) << 21;
 8119: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8120: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8121: 	
 8122: 	my $num1=$symbchck+$symbseed+$namechck;
 8123: 	my $num2=$nameseed+$domainseed+$courseseed;
 8124: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8125: 	#&logthis("rndseed :$num:$symb");
 8126: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8127: 	return "$num1,$num2";
 8128:     }
 8129: }
 8130: 
 8131: sub rndseed_64bit3 {
 8132:     my ($symb,$courseid,$domain,$username)=@_;
 8133:     {
 8134: 	use integer;
 8135: 	# strings need to be an even # of cahracters long, it it is odd the
 8136:         # last characters gets thrown away
 8137: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8138: 	my $symbseed=numval2($symb) << 10;
 8139: 	my $namechck=unpack("%32S*",$username.' ');
 8140: 	
 8141: 	my $nameseed=numval2($username) << 21;
 8142: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8143: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8144: 	
 8145: 	my $num1=$symbchck+$symbseed+$namechck;
 8146: 	my $num2=$nameseed+$domainseed+$courseseed;
 8147: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8148: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8149: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8150: 	
 8151: 	return "$num1:$num2";
 8152:     }
 8153: }
 8154: 
 8155: sub rndseed_64bit4 {
 8156:     my ($symb,$courseid,$domain,$username)=@_;
 8157:     {
 8158: 	use integer;
 8159: 	# strings need to be an even # of cahracters long, it it is odd the
 8160:         # last characters gets thrown away
 8161: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8162: 	my $symbseed=numval3($symb) << 10;
 8163: 	my $namechck=unpack("%32S*",$username.' ');
 8164: 	
 8165: 	my $nameseed=numval3($username) << 21;
 8166: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8167: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8168: 	
 8169: 	my $num1=$symbchck+$symbseed+$namechck;
 8170: 	my $num2=$nameseed+$domainseed+$courseseed;
 8171: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8172: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8173: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8174: 	
 8175: 	return "$num1:$num2";
 8176:     }
 8177: }
 8178: 
 8179: sub rndseed_64bit5 {
 8180:     my ($symb,$courseid,$domain,$username)=@_;
 8181:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 8182:     return "$num1:$num2";
 8183: }
 8184: 
 8185: sub rndseed_CODE_64bit {
 8186:     my ($symb,$courseid,$domain,$username)=@_;
 8187:     {
 8188: 	use integer;
 8189: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8190: 	my $symbseed=numval2($symb);
 8191: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8192: 	my $CODEseed=numval(&getCODE());
 8193: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8194: 	my $num1=$symbseed+$CODEchck;
 8195: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8196: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8197: 	#&logthis("rndseed :$num1:$num2:$symb");
 8198: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8199: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8200: 	return "$num1:$num2";
 8201:     }
 8202: }
 8203: 
 8204: sub rndseed_CODE_64bit4 {
 8205:     my ($symb,$courseid,$domain,$username)=@_;
 8206:     {
 8207: 	use integer;
 8208: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8209: 	my $symbseed=numval3($symb);
 8210: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8211: 	my $CODEseed=numval3(&getCODE());
 8212: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8213: 	my $num1=$symbseed+$CODEchck;
 8214: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8215: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8216: 	#&logthis("rndseed :$num1:$num2:$symb");
 8217: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8218: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8219: 	return "$num1:$num2";
 8220:     }
 8221: }
 8222: 
 8223: sub rndseed_CODE_64bit5 {
 8224:     my ($symb,$courseid,$domain,$username)=@_;
 8225:     my $code = &getCODE();
 8226:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 8227:     return "$num1:$num2";
 8228: }
 8229: 
 8230: sub setup_random_from_rndseed {
 8231:     my ($rndseed)=@_;
 8232:     if ($rndseed =~/([,:])/) {
 8233: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 8234: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 8235:     } else {
 8236: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 8237:     }
 8238: }
 8239: 
 8240: sub latest_receipt_algorithm_id {
 8241:     return 'receipt3';
 8242: }
 8243: 
 8244: sub recunique {
 8245:     my $fucourseid=shift;
 8246:     my $unique;
 8247:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 8248: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8249: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 8250:     } else {
 8251: 	$unique=$perlvar{'lonReceipt'};
 8252:     }
 8253:     return unpack("%32C*",$unique);
 8254: }
 8255: 
 8256: sub recprefix {
 8257:     my $fucourseid=shift;
 8258:     my $prefix;
 8259:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 8260: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8261: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 8262:     } else {
 8263: 	$prefix=$perlvar{'lonHostID'};
 8264:     }
 8265:     return unpack("%32C*",$prefix);
 8266: }
 8267: 
 8268: sub ireceipt {
 8269:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 8270: 
 8271:     my $return =&recprefix($fucourseid).'-';
 8272: 
 8273:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 8274: 	$env{'request.state'} eq 'construct') {
 8275: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 8276: 	return $return;
 8277:     }
 8278: 
 8279:     my $cuname=unpack("%32C*",$funame);
 8280:     my $cudom=unpack("%32C*",$fudom);
 8281:     my $cucourseid=unpack("%32C*",$fucourseid);
 8282:     my $cusymb=unpack("%32C*",$fusymb);
 8283:     my $cunique=&recunique($fucourseid);
 8284:     my $cpart=unpack("%32S*",$part);
 8285:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 8286: 
 8287: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 8288: 			       
 8289: 	$return.= ($cunique%$cuname+
 8290: 		   $cunique%$cudom+
 8291: 		   $cusymb%$cuname+
 8292: 		   $cusymb%$cudom+
 8293: 		   $cucourseid%$cuname+
 8294: 		   $cucourseid%$cudom+
 8295: 		   $cpart%$cuname+
 8296: 		   $cpart%$cudom);
 8297:     } else {
 8298: 	$return.= ($cunique%$cuname+
 8299: 		   $cunique%$cudom+
 8300: 		   $cusymb%$cuname+
 8301: 		   $cusymb%$cudom+
 8302: 		   $cucourseid%$cuname+
 8303: 		   $cucourseid%$cudom);
 8304:     }
 8305:     return $return;
 8306: }
 8307: 
 8308: sub receipt {
 8309:     my ($part)=@_;
 8310:     my ($symb,$courseid,$domain,$name) = &whichuser();
 8311:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 8312: }
 8313: 
 8314: sub whichuser {
 8315:     my ($passedsymb)=@_;
 8316:     my ($symb,$courseid,$domain,$name,$publicuser);
 8317:     if (defined($env{'form.grade_symb'})) {
 8318: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 8319: 	my $allowed=&allowed('vgr',$tmp_courseid);
 8320: 	if (!$allowed &&
 8321: 	    exists($env{'request.course.sec'}) &&
 8322: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 8323: 	    $allowed=&allowed('vgr',$tmp_courseid.
 8324: 			      '/'.$env{'request.course.sec'});
 8325: 	}
 8326: 	if ($allowed) {
 8327: 	    ($symb)=&get_env_multiple('form.grade_symb');
 8328: 	    $courseid=$tmp_courseid;
 8329: 	    ($domain)=&get_env_multiple('form.grade_domain');
 8330: 	    ($name)=&get_env_multiple('form.grade_username');
 8331: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 8332: 	}
 8333:     }
 8334:     if (!$passedsymb) {
 8335: 	$symb=&symbread();
 8336:     } else {
 8337: 	$symb=$passedsymb;
 8338:     }
 8339:     $courseid=$env{'request.course.id'};
 8340:     $domain=$env{'user.domain'};
 8341:     $name=$env{'user.name'};
 8342:     if ($name eq 'public' && $domain eq 'public') {
 8343: 	if (!defined($env{'form.username'})) {
 8344: 	    $env{'form.username'}.=time.rand(10000000);
 8345: 	}
 8346: 	$name.=$env{'form.username'};
 8347:     }
 8348:     return ($symb,$courseid,$domain,$name,$publicuser);
 8349: 
 8350: }
 8351: 
 8352: # ------------------------------------------------------------ Serves up a file
 8353: # returns either the contents of the file or 
 8354: # -1 if the file doesn't exist
 8355: #
 8356: # if the target is a file that was uploaded via DOCS, 
 8357: # a check will be made to see if a current copy exists on the local server,
 8358: # if it does this will be served, otherwise a copy will be retrieved from
 8359: # the home server for the course and stored in /home/httpd/html/userfiles on
 8360: # the local server.   
 8361: 
 8362: sub getfile {
 8363:     my ($file) = @_;
 8364:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8365:     &repcopy($file);
 8366:     return &readfile($file);
 8367: }
 8368: 
 8369: sub repcopy_userfile {
 8370:     my ($file)=@_;
 8371:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8372:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 8373:     my ($cdom,$cnum,$filename) = 
 8374: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 8375:     my $uri="/uploaded/$cdom/$cnum/$filename";
 8376:     if (-e "$file") {
 8377: # we already have a local copy, check it out
 8378: 	my @fileinfo = stat($file);
 8379: 	my $rtncode;
 8380: 	my $info;
 8381: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 8382: 	if ($lwpresp ne 'ok') {
 8383: # there is no such file anymore, even though we had a local copy
 8384: 	    if ($rtncode eq '404') {
 8385: 		unlink($file);
 8386: 	    }
 8387: 	    return -1;
 8388: 	}
 8389: 	if ($info < $fileinfo[9]) {
 8390: # nice, the file we have is up-to-date, just say okay
 8391: 	    return 'ok';
 8392: 	} else {
 8393: # the file is outdated, get rid of it
 8394: 	    unlink($file);
 8395: 	}
 8396:     }
 8397: # one way or the other, at this point, we don't have the file
 8398: # construct the correct path for the file
 8399:     my @parts = ($cdom,$cnum); 
 8400:     if ($filename =~ m|^(.+)/[^/]+$|) {
 8401: 	push @parts, split(/\//,$1);
 8402:     }
 8403:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 8404:     foreach my $part (@parts) {
 8405: 	$path .= '/'.$part;
 8406: 	if (!-e $path) {
 8407: 	    mkdir($path,0770);
 8408: 	}
 8409:     }
 8410: # now the path exists for sure
 8411: # get a user agent
 8412:     my $ua=new LWP::UserAgent;
 8413:     my $transferfile=$file.'.in.transfer';
 8414: # FIXME: this should flock
 8415:     if (-e $transferfile) { return 'ok'; }
 8416:     my $request;
 8417:     $uri=~s/^\///;
 8418:     my $homeserver = &homeserver($cnum,$cdom);
 8419:     my $protocol = $protocol{$homeserver};
 8420:     $protocol = 'http' if ($protocol ne 'https');
 8421:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
 8422:     my $response=$ua->request($request,$transferfile);
 8423: # did it work?
 8424:     if ($response->is_error()) {
 8425: 	unlink($transferfile);
 8426: 	&logthis("Userfile repcopy failed for $uri");
 8427: 	return -1;
 8428:     }
 8429: # worked, rename the transfer file
 8430:     rename($transferfile,$file);
 8431:     return 'ok';
 8432: }
 8433: 
 8434: sub tokenwrapper {
 8435:     my $uri=shift;
 8436:     $uri=~s|^https?\://([^/]+)||;
 8437:     $uri=~s|^/||;
 8438:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 8439:     my $token=$1;
 8440:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 8441:     if ($udom && $uname && $file) {
 8442: 	$file=~s|(\?\.*)*$||;
 8443:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 8444:         my $homeserver = &homeserver($uname,$udom);
 8445:         my $protocol = $protocol{$homeserver};
 8446:         $protocol = 'http' if ($protocol ne 'https');
 8447:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
 8448:                (($uri=~/\?/)?'&':'?').'token='.$token.
 8449:                                '&tokenissued='.$perlvar{'lonHostID'};
 8450:     } else {
 8451:         return '/adm/notfound.html';
 8452:     }
 8453: }
 8454: 
 8455: # call with reqtype HEAD: get last modification time
 8456: # call with reqtype GET: get the file contents
 8457: # Do not call this with reqtype GET for large files! It loads everything into memory
 8458: #
 8459: sub getuploaded {
 8460:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 8461:     $uri=~s/^\///;
 8462:     my $homeserver = &homeserver($cnum,$cdom);
 8463:     my $protocol = $protocol{$homeserver};
 8464:     $protocol = 'http' if ($protocol ne 'https');
 8465:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
 8466:     my $ua=new LWP::UserAgent;
 8467:     my $request=new HTTP::Request($reqtype,$uri);
 8468:     my $response=$ua->request($request);
 8469:     $$rtncode = $response->code;
 8470:     if (! $response->is_success()) {
 8471: 	return 'failed';
 8472:     }      
 8473:     if ($reqtype eq 'HEAD') {
 8474: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 8475:     } elsif ($reqtype eq 'GET') {
 8476: 	$$info = $response->content;
 8477:     }
 8478:     return 'ok';
 8479: }
 8480: 
 8481: sub readfile {
 8482:     my $file = shift;
 8483:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 8484:     my $fh;
 8485:     open($fh,"<$file");
 8486:     my $a='';
 8487:     while (my $line = <$fh>) { $a .= $line; }
 8488:     return $a;
 8489: }
 8490: 
 8491: sub filelocation {
 8492:     my ($dir,$file) = @_;
 8493:     my $location;
 8494:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 8495: 
 8496:     if ($file =~ m-^/adm/-) {
 8497: 	$file=~s-^/adm/wrapper/-/-;
 8498: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8499:     }
 8500: 
 8501:     if ($file=~m:^/~:) { # is a contruction space reference
 8502:         $location = $file;
 8503:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 8504:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 8505: 	# is a correct contruction space reference
 8506:         $location = $file;
 8507:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
 8508:         $location = $file;
 8509:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 8510:         my ($udom,$uname,$filename)=
 8511:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 8512:         my $home=&homeserver($uname,$udom);
 8513:         my $is_me=0;
 8514:         my @ids=&current_machine_ids();
 8515:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 8516:         if ($is_me) {
 8517:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
 8518:         } else {
 8519:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 8520:   	      $udom.'/'.$uname.'/'.$filename;
 8521:         }
 8522:     } elsif ($file =~ m-^/adm/-) {
 8523: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 8524:     } else {
 8525:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8526:         $file=~s:^/res/:/:;
 8527:         if ( !( $file =~ m:^/:) ) {
 8528:             $location = $dir. '/'.$file;
 8529:         } else {
 8530:             $location = '/home/httpd/html/res'.$file;
 8531:         }
 8532:     }
 8533:     $location=~s://+:/:g; # remove duplicate /
 8534:     while ($location=~m{/\.\./}) {
 8535: 	if ($location =~ m{/[^/]+/\.\./}) {
 8536: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 8537: 	} else {
 8538: 	    $location=~ s{/\.\./}{/}g;
 8539: 	}
 8540:     } #remove dir/..
 8541:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 8542:     return $location;
 8543: }
 8544: 
 8545: sub hreflocation {
 8546:     my ($dir,$file)=@_;
 8547:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
 8548: 	$file=filelocation($dir,$file);
 8549:     } elsif ($file=~m-^/adm/-) {
 8550: 	$file=~s-^/adm/wrapper/-/-;
 8551: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8552:     }
 8553:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 8554: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 8555:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 8556: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 8557:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 8558: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 8559: 	    -/uploaded/$1/$2/-x;
 8560:     }
 8561:     if ($file=~ m{^/userfiles/}) {
 8562: 	$file =~ s{^/userfiles/}{/uploaded/};
 8563:     }
 8564:     return $file;
 8565: }
 8566: 
 8567: sub current_machine_domains {
 8568:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 8569: }
 8570: 
 8571: sub machine_domains {
 8572:     my ($hostname) = @_;
 8573:     my @domains;
 8574:     my %hostname = &all_hostnames();
 8575:     while( my($id, $name) = each(%hostname)) {
 8576: #	&logthis("-$id-$name-$hostname-");
 8577: 	if ($hostname eq $name) {
 8578: 	    push(@domains,&host_domain($id));
 8579: 	}
 8580:     }
 8581:     return @domains;
 8582: }
 8583: 
 8584: sub current_machine_ids {
 8585:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 8586: }
 8587: 
 8588: sub machine_ids {
 8589:     my ($hostname) = @_;
 8590:     $hostname ||= &hostname($perlvar{'lonHostID'});
 8591:     my @ids;
 8592:     my %name_to_host = &all_names();
 8593:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 8594: 	return @{ $name_to_host{$hostname} };
 8595:     }
 8596:     return;
 8597: }
 8598: 
 8599: sub additional_machine_domains {
 8600:     my @domains;
 8601:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 8602:     while( my $line = <$fh>) {
 8603:         $line =~ s/\s//g;
 8604:         push(@domains,$line);
 8605:     }
 8606:     return @domains;
 8607: }
 8608: 
 8609: sub default_login_domain {
 8610:     my $domain = $perlvar{'lonDefDomain'};
 8611:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 8612:     foreach my $posdom (&current_machine_domains(),
 8613:                         &additional_machine_domains()) {
 8614:         if (lc($posdom) eq lc($testdomain)) {
 8615:             $domain=$posdom;
 8616:             last;
 8617:         }
 8618:     }
 8619:     return $domain;
 8620: }
 8621: 
 8622: # ------------------------------------------------------------- Declutters URLs
 8623: 
 8624: sub declutter {
 8625:     my $thisfn=shift;
 8626:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8627:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8628:     $thisfn=~s/^\///;
 8629:     $thisfn=~s|^adm/wrapper/||;
 8630:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 8631:     $thisfn=~s/^res\///;
 8632:     $thisfn=~s/\?.+$//;
 8633:     return $thisfn;
 8634: }
 8635: 
 8636: # ------------------------------------------------------------- Clutter up URLs
 8637: 
 8638: sub clutter {
 8639:     my $thisfn='/'.&declutter(shift);
 8640:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 8641: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 8642:        $thisfn='/res'.$thisfn; 
 8643:     }
 8644:     if ($thisfn !~m|/adm|) {
 8645: 	if ($thisfn =~ m|/ext/|) {
 8646: 	    $thisfn='/adm/wrapper'.$thisfn;
 8647: 	} else {
 8648: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 8649: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 8650: 	    if ($embstyle eq 'ssi'
 8651: 		|| ($embstyle eq 'hdn')
 8652: 		|| ($embstyle eq 'rat')
 8653: 		|| ($embstyle eq 'prv')
 8654: 		|| ($embstyle eq 'ign')) {
 8655: 		#do nothing with these
 8656: 	    } elsif (($embstyle eq 'img') 
 8657: 		|| ($embstyle eq 'emb')
 8658: 		|| ($embstyle eq 'wrp')) {
 8659: 		$thisfn='/adm/wrapper'.$thisfn;
 8660: 	    } elsif ($embstyle eq 'unk'
 8661: 		     && $thisfn!~/\.(sequence|page)$/) {
 8662: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 8663: 	    } else {
 8664: #		&logthis("Got a blank emb style");
 8665: 	    }
 8666: 	}
 8667:     }
 8668:     return $thisfn;
 8669: }
 8670: 
 8671: sub clutter_with_no_wrapper {
 8672:     my $uri = &clutter(shift);
 8673:     if ($uri =~ m-^/adm/-) {
 8674: 	$uri =~ s-^/adm/wrapper/-/-;
 8675: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 8676:     }
 8677:     return $uri;
 8678: }
 8679: 
 8680: sub freeze_escape {
 8681:     my ($value)=@_;
 8682:     if (ref($value)) {
 8683: 	$value=&nfreeze($value);
 8684: 	return '__FROZEN__'.&escape($value);
 8685:     }
 8686:     return &escape($value);
 8687: }
 8688: 
 8689: 
 8690: sub thaw_unescape {
 8691:     my ($value)=@_;
 8692:     if ($value =~ /^__FROZEN__/) {
 8693: 	substr($value,0,10,undef);
 8694: 	$value=&unescape($value);
 8695: 	return &thaw($value);
 8696:     }
 8697:     return &unescape($value);
 8698: }
 8699: 
 8700: sub correct_line_ends {
 8701:     my ($result)=@_;
 8702:     $$result =~s/\r\n/\n/mg;
 8703:     $$result =~s/\r/\n/mg;
 8704: }
 8705: # ================================================================ Main Program
 8706: 
 8707: sub goodbye {
 8708:    &logthis("Starting Shut down");
 8709: #not converted to using infrastruture and probably shouldn't be
 8710:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 8711: #converted
 8712: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 8713:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 8714: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 8715: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 8716: #1.1 only
 8717: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 8718: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 8719: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 8720: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 8721:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 8722:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 8723:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 8724:    &flushcourselogs();
 8725:    &logthis("Shutting down");
 8726: }
 8727: 
 8728: sub get_dns {
 8729:     my ($url,$func,$ignore_cache) = @_;
 8730:     if (!$ignore_cache) {
 8731: 	my ($content,$cached)=
 8732: 	    &Apache::lonnet::is_cached_new('dns',$url);
 8733: 	if ($cached) {
 8734: 	    &$func($content);
 8735: 	    return;
 8736: 	}
 8737:     }
 8738: 
 8739:     my %alldns;
 8740:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8741:     foreach my $dns (<$config>) {
 8742: 	next if ($dns !~ /^\^(\S*)/x);
 8743:         my $line = $1;
 8744:         my ($host,$protocol) = split(/:/,$line);
 8745:         if ($protocol ne 'https') {
 8746:             $protocol = 'http';
 8747:         }
 8748: 	$alldns{$host} = $protocol;
 8749:     }
 8750:     while (%alldns) {
 8751: 	my ($dns) = keys(%alldns);
 8752: 	my $ua=new LWP::UserAgent;
 8753: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
 8754: 	my $response=$ua->request($request);
 8755:         delete($alldns{$dns});
 8756: 	next if ($response->is_error());
 8757: 	my @content = split("\n",$response->content);
 8758: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 8759: 	&$func(\@content);
 8760: 	return;
 8761:     }
 8762:     close($config);
 8763:     my $which = (split('/',$url))[3];
 8764:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 8765:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 8766:     my @content = <$config>;
 8767:     &$func(\@content);
 8768:     return;
 8769: }
 8770: # ------------------------------------------------------------ Read domain file
 8771: {
 8772:     my $loaded;
 8773:     my %domain;
 8774: 
 8775:     sub parse_domain_tab {
 8776: 	my ($lines) = @_;
 8777: 	foreach my $line (@$lines) {
 8778: 	    next if ($line =~ /^(\#|\s*$ )/x);
 8779: 
 8780: 	    chomp($line);
 8781: 	    my ($name,@elements) = split(/:/,$line,9);
 8782: 	    my %this_domain;
 8783: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 8784: 			       'lang_def', 'city', 'longi', 'lati',
 8785: 			       'primary') {
 8786: 		$this_domain{$field} = shift(@elements);
 8787: 	    }
 8788: 	    $domain{$name} = \%this_domain;
 8789: 	}
 8790:     }
 8791: 
 8792:     sub reset_domain_info {
 8793: 	undef($loaded);
 8794: 	undef(%domain);
 8795:     }
 8796: 
 8797:     sub load_domain_tab {
 8798: 	my ($ignore_cache) = @_;
 8799: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 8800: 	my $fh;
 8801: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 8802: 	    my @lines = <$fh>;
 8803: 	    &parse_domain_tab(\@lines);
 8804: 	}
 8805: 	close($fh);
 8806: 	$loaded = 1;
 8807:     }
 8808: 
 8809:     sub domain {
 8810: 	&load_domain_tab() if (!$loaded);
 8811: 
 8812: 	my ($name,$what) = @_;
 8813: 	return if ( !exists($domain{$name}) );
 8814: 
 8815: 	if (!$what) {
 8816: 	    return $domain{$name}{'description'};
 8817: 	}
 8818: 	return $domain{$name}{$what};
 8819:     }
 8820: 
 8821:     sub domain_info {
 8822:         &load_domain_tab() if (!$loaded);
 8823:         return %domain;
 8824:     }
 8825: 
 8826: }
 8827: 
 8828: 
 8829: # ------------------------------------------------------------- Read hosts file
 8830: {
 8831:     my %hostname;
 8832:     my %hostdom;
 8833:     my %libserv;
 8834:     my $loaded;
 8835:     my %name_to_host;
 8836: 
 8837:     sub parse_hosts_tab {
 8838: 	my ($file) = @_;
 8839: 	foreach my $configline (@$file) {
 8840: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 8841: 	    next if ($configline =~ /^\^/);
 8842: 	    chomp($configline);
 8843: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
 8844: 	    $name=~s/\s//g;
 8845: 	    if ($id && $domain && $role && $name) {
 8846: 		$hostname{$id}=$name;
 8847: 		push(@{$name_to_host{$name}}, $id);
 8848: 		$hostdom{$id}=$domain;
 8849: 		if ($role eq 'library') { $libserv{$id}=$name; }
 8850:                 if (defined($protocol)) {
 8851:                     if ($protocol eq 'https') {
 8852:                         $protocol{$id} = $protocol;
 8853:                     } else {
 8854:                         $protocol{$id} = 'http'; 
 8855:                     }
 8856:                 } else {
 8857:                     $protocol{$id} = 'http';
 8858:                 }
 8859: 	    }
 8860: 	}
 8861:     }
 8862:     
 8863:     sub reset_hosts_info {
 8864: 	&purge_remembered();
 8865: 	&reset_domain_info();
 8866: 	&reset_hosts_ip_info();
 8867: 	undef(%name_to_host);
 8868: 	undef(%hostname);
 8869: 	undef(%hostdom);
 8870: 	undef(%libserv);
 8871: 	undef($loaded);
 8872:     }
 8873: 
 8874:     sub load_hosts_tab {
 8875: 	my ($ignore_cache) = @_;
 8876: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 8877: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8878: 	my @config = <$config>;
 8879: 	&parse_hosts_tab(\@config);
 8880: 	close($config);
 8881: 	$loaded=1;
 8882:     }
 8883: 
 8884:     sub hostname {
 8885: 	&load_hosts_tab() if (!$loaded);
 8886: 
 8887: 	my ($lonid) = @_;
 8888: 	return $hostname{$lonid};
 8889:     }
 8890: 
 8891:     sub all_hostnames {
 8892: 	&load_hosts_tab() if (!$loaded);
 8893: 
 8894: 	return %hostname;
 8895:     }
 8896: 
 8897:     sub all_names {
 8898: 	&load_hosts_tab() if (!$loaded);
 8899: 
 8900: 	return %name_to_host;
 8901:     }
 8902: 
 8903:     sub all_host_domain {
 8904:         &load_hosts_tab() if (!$loaded);
 8905:         return %hostdom;
 8906:     }
 8907: 
 8908:     sub is_library {
 8909: 	&load_hosts_tab() if (!$loaded);
 8910: 
 8911: 	return exists($libserv{$_[0]});
 8912:     }
 8913: 
 8914:     sub all_library {
 8915: 	&load_hosts_tab() if (!$loaded);
 8916: 
 8917: 	return %libserv;
 8918:     }
 8919: 
 8920:     sub get_servers {
 8921: 	&load_hosts_tab() if (!$loaded);
 8922: 
 8923: 	my ($domain,$type) = @_;
 8924: 	my %possible_hosts = ($type eq 'library') ? %libserv
 8925: 	                                          : %hostname;
 8926: 	my %result;
 8927: 	if (ref($domain) eq 'ARRAY') {
 8928: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8929: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 8930: 		    $result{$host} = $hostname;
 8931: 		}
 8932: 	    }
 8933: 	} else {
 8934: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8935: 		if ($hostdom{$host} eq $domain) {
 8936: 		    $result{$host} = $hostname;
 8937: 		}
 8938: 	    }
 8939: 	}
 8940: 	return %result;
 8941:     }
 8942: 
 8943:     sub host_domain {
 8944: 	&load_hosts_tab() if (!$loaded);
 8945: 
 8946: 	my ($lonid) = @_;
 8947: 	return $hostdom{$lonid};
 8948:     }
 8949: 
 8950:     sub all_domains {
 8951: 	&load_hosts_tab() if (!$loaded);
 8952: 
 8953: 	my %seen;
 8954: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 8955: 	return @uniq;
 8956:     }
 8957: }
 8958: 
 8959: { 
 8960:     my %iphost;
 8961:     my %name_to_ip;
 8962:     my %lonid_to_ip;
 8963: 
 8964:     sub get_hosts_from_ip {
 8965: 	my ($ip) = @_;
 8966: 	my %iphosts = &get_iphost();
 8967: 	if (ref($iphosts{$ip})) {
 8968: 	    return @{$iphosts{$ip}};
 8969: 	}
 8970: 	return;
 8971:     }
 8972:     
 8973:     sub reset_hosts_ip_info {
 8974: 	undef(%iphost);
 8975: 	undef(%name_to_ip);
 8976: 	undef(%lonid_to_ip);
 8977:     }
 8978: 
 8979:     sub get_host_ip {
 8980: 	my ($lonid) = @_;
 8981: 	if (exists($lonid_to_ip{$lonid})) {
 8982: 	    return $lonid_to_ip{$lonid};
 8983: 	}
 8984: 	my $name=&hostname($lonid);
 8985:    	my $ip = gethostbyname($name);
 8986: 	return if (!$ip || length($ip) ne 4);
 8987: 	$ip=inet_ntoa($ip);
 8988: 	$name_to_ip{$name}   = $ip;
 8989: 	$lonid_to_ip{$lonid} = $ip;
 8990: 	return $ip;
 8991:     }
 8992:     
 8993:     sub get_iphost {
 8994: 	my ($ignore_cache) = @_;
 8995: 
 8996: 	if (!$ignore_cache) {
 8997: 	    if (%iphost) {
 8998: 		return %iphost;
 8999: 	    }
 9000: 	    my ($ip_info,$cached)=
 9001: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 9002: 	    if ($cached) {
 9003: 		%iphost      = %{$ip_info->[0]};
 9004: 		%name_to_ip  = %{$ip_info->[1]};
 9005: 		%lonid_to_ip = %{$ip_info->[2]};
 9006: 		return %iphost;
 9007: 	    }
 9008: 	}
 9009: 
 9010: 	# get yesterday's info for fallback
 9011: 	my %old_name_to_ip;
 9012: 	my ($ip_info,$cached)=
 9013: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 9014: 	if ($cached) {
 9015: 	    %old_name_to_ip = %{$ip_info->[1]};
 9016: 	}
 9017: 
 9018: 	my %name_to_host = &all_names();
 9019: 	foreach my $name (keys(%name_to_host)) {
 9020: 	    my $ip;
 9021: 	    if (!exists($name_to_ip{$name})) {
 9022: 		$ip = gethostbyname($name);
 9023: 		if (!$ip || length($ip) ne 4) {
 9024: 		    if (defined($old_name_to_ip{$name})) {
 9025: 			$ip = $old_name_to_ip{$name};
 9026: 			&logthis("Can't find $name defaulting to old $ip");
 9027: 		    } else {
 9028: 			&logthis("Name $name no IP found");
 9029: 			next;
 9030: 		    }
 9031: 		} else {
 9032: 		    $ip=inet_ntoa($ip);
 9033: 		}
 9034: 		$name_to_ip{$name} = $ip;
 9035: 	    } else {
 9036: 		$ip = $name_to_ip{$name};
 9037: 	    }
 9038: 	    foreach my $id (@{ $name_to_host{$name} }) {
 9039: 		$lonid_to_ip{$id} = $ip;
 9040: 	    }
 9041: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 9042: 	}
 9043: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 9044: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 9045: 				      48*60*60);
 9046: 
 9047: 	return %iphost;
 9048:     }
 9049: 
 9050:     #
 9051:     #  Given a DNS returns the loncapa host name for that DNS 
 9052:     # 
 9053:     sub host_from_dns {
 9054:         my ($dns) = @_;
 9055:         my @hosts;
 9056:         my $ip;
 9057: 
 9058:         if (defined($name_to_ip{$dns})) {
 9059:             $ip = $name_to_ip{$dns};
 9060:         }
 9061:         if (!$ip) {
 9062:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
 9063:             if (length($ip) == 4) { 
 9064: 	        $ip   = &IO::Socket::inet_ntoa($ip);
 9065:             }
 9066:         }
 9067:         if ($ip) {
 9068: 	    @hosts = get_hosts_from_ip($ip);
 9069: 	    return $hosts[0];
 9070:         }
 9071:         return undef;
 9072:     }
 9073: 
 9074: }
 9075: 
 9076: BEGIN {
 9077: 
 9078: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 9079:     unless ($readit) {
 9080: {
 9081:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 9082:     %perlvar = (%perlvar,%{$configvars});
 9083: }
 9084: 
 9085: 
 9086: # ------------------------------------------------------ Read spare server file
 9087: {
 9088:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 9089: 
 9090:     while (my $configline=<$config>) {
 9091:        chomp($configline);
 9092:        if ($configline) {
 9093: 	   my ($host,$type) = split(':',$configline,2);
 9094: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 9095: 	   push(@{ $spareid{$type} }, $host);
 9096:        }
 9097:     }
 9098:     close($config);
 9099: }
 9100: # ------------------------------------------------------------ Read permissions
 9101: {
 9102:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 9103: 
 9104:     while (my $configline=<$config>) {
 9105: 	chomp($configline);
 9106: 	if ($configline) {
 9107: 	    my ($role,$perm)=split(/ /,$configline);
 9108: 	    if ($perm ne '') { $pr{$role}=$perm; }
 9109: 	}
 9110:     }
 9111:     close($config);
 9112: }
 9113: 
 9114: # -------------------------------------------- Read plain texts for permissions
 9115: {
 9116:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 9117: 
 9118:     while (my $configline=<$config>) {
 9119: 	chomp($configline);
 9120: 	if ($configline) {
 9121: 	    my ($short,@plain)=split(/:/,$configline);
 9122:             %{$prp{$short}} = ();
 9123: 	    if (@plain > 0) {
 9124:                 $prp{$short}{'std'} = $plain[0];
 9125:                 for (my $i=1; $i<@plain; $i++) {
 9126:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 9127:                 }
 9128:             }
 9129: 	}
 9130:     }
 9131:     close($config);
 9132: }
 9133: 
 9134: # ---------------------------------------------------------- Read package table
 9135: {
 9136:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 9137: 
 9138:     while (my $configline=<$config>) {
 9139: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 9140: 	chomp($configline);
 9141: 	my ($short,$plain)=split(/:/,$configline);
 9142: 	my ($pack,$name)=split(/\&/,$short);
 9143: 	if ($plain ne '') {
 9144: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 9145: 	    $packagetab{$short}=$plain; 
 9146: 	}
 9147:     }
 9148:     close($config);
 9149: }
 9150: 
 9151: # ------------- set up temporary directory
 9152: {
 9153:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 9154: 
 9155: }
 9156: 
 9157: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 9158: 				'compress_threshold'=> 20_000,
 9159:  			        });
 9160: 
 9161: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 9162: $dumpcount=0;
 9163: $locknum=0;
 9164: 
 9165: &logtouch();
 9166: &logthis('<font color="yellow">INFO: Read configuration</font>');
 9167: $readit=1;
 9168:     {
 9169: 	use integer;
 9170: 	my $test=(2**32)+1;
 9171: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 9172: 	&logthis(" Detected 64bit platform ($_64bit)");
 9173:     }
 9174: }
 9175: }
 9176: 
 9177: 1;
 9178: __END__
 9179: 
 9180: =pod
 9181: 
 9182: =head1 NAME
 9183: 
 9184: Apache::lonnet - Subroutines to ask questions about things in the network.
 9185: 
 9186: =head1 SYNOPSIS
 9187: 
 9188: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 9189: 
 9190:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 9191: 
 9192: Common parameters:
 9193: 
 9194: =over 4
 9195: 
 9196: =item *
 9197: 
 9198: $uname : an internal username (if $cname expecting a course Id specifically)
 9199: 
 9200: =item *
 9201: 
 9202: $udom : a domain (if $cdom expecting a course's domain specifically)
 9203: 
 9204: =item *
 9205: 
 9206: $symb : a resource instance identifier
 9207: 
 9208: =item *
 9209: 
 9210: $namespace : the name of a .db file that contains the data needed or
 9211: being set.
 9212: 
 9213: =back
 9214: 
 9215: =head1 OVERVIEW
 9216: 
 9217: lonnet provides subroutines which interact with the
 9218: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 9219: about classes, users, and resources.
 9220: 
 9221: For many of these objects you can also use this to store data about
 9222: them or modify them in various ways.
 9223: 
 9224: =head2 Symbs
 9225: 
 9226: To identify a specific instance of a resource, LON-CAPA uses symbols
 9227: or "symbs"X<symb>. These identifiers are built from the URL of the
 9228: map, the resource number of the resource in the map, and the URL of
 9229: the resource itself. The latter is somewhat redundant, but might help
 9230: if maps change.
 9231: 
 9232: An example is
 9233: 
 9234:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 9235: 
 9236: The respective map entry is
 9237: 
 9238:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 9239:   title="Problem 2">
 9240:  </resource>
 9241: 
 9242: Symbs are used by the random number generator, as well as to store and
 9243: restore data specific to a certain instance of for example a problem.
 9244: 
 9245: =head2 Storing And Retrieving Data
 9246: 
 9247: X<store()>X<cstore()>X<restore()>Three of the most important functions
 9248: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 9249: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 9250: is is the non-critical message twin of cstore. These functions are for
 9251: handlers to store a perl hash to a user's permanent data space in an
 9252: easy manner, and to retrieve it again on another call. It is expected
 9253: that a handler would use this once at the beginning to retrieve data,
 9254: and then again once at the end to send only the new data back.
 9255: 
 9256: The data is stored in the user's data directory on the user's
 9257: homeserver under the ID of the course.
 9258: 
 9259: The hash that is returned by restore will have all of the previous
 9260: value for all of the elements of the hash.
 9261: 
 9262: Example:
 9263: 
 9264:  #creating a hash
 9265:  my %hash;
 9266:  $hash{'foo'}='bar';
 9267: 
 9268:  #storing it
 9269:  &Apache::lonnet::cstore(\%hash);
 9270: 
 9271:  #changing a value
 9272:  $hash{'foo'}='notbar';
 9273: 
 9274:  #adding a new value
 9275:  $hash{'bar'}='foo';
 9276:  &Apache::lonnet::cstore(\%hash);
 9277: 
 9278:  #retrieving the hash
 9279:  my %history=&Apache::lonnet::restore();
 9280: 
 9281:  #print the hash
 9282:  foreach my $key (sort(keys(%history))) {
 9283:    print("\%history{$key} = $history{$key}");
 9284:  }
 9285: 
 9286: Will print out:
 9287: 
 9288:  %history{1:foo} = bar
 9289:  %history{1:keys} = foo:timestamp
 9290:  %history{1:timestamp} = 990455579
 9291:  %history{2:bar} = foo
 9292:  %history{2:foo} = notbar
 9293:  %history{2:keys} = foo:bar:timestamp
 9294:  %history{2:timestamp} = 990455580
 9295:  %history{bar} = foo
 9296:  %history{foo} = notbar
 9297:  %history{timestamp} = 990455580
 9298:  %history{version} = 2
 9299: 
 9300: Note that the special hash entries C<keys>, C<version> and
 9301: C<timestamp> were added to the hash. C<version> will be equal to the
 9302: total number of versions of the data that have been stored. The
 9303: C<timestamp> attribute will be the UNIX time the hash was
 9304: stored. C<keys> is available in every historical section to list which
 9305: keys were added or changed at a specific historical revision of a
 9306: hash.
 9307: 
 9308: B<Warning>: do not store the hash that restore returns directly. This
 9309: will cause a mess since it will restore the historical keys as if the
 9310: were new keys. I.E. 1:foo will become 1:1:foo etc.
 9311: 
 9312: Calling convention:
 9313: 
 9314:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 9315:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 9316: 
 9317: For more detailed information, see lonnet specific documentation.
 9318: 
 9319: =head1 RETURN MESSAGES
 9320: 
 9321: =over 4
 9322: 
 9323: =item * B<con_lost>: unable to contact remote host
 9324: 
 9325: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 9326: when the connection is brought back up
 9327: 
 9328: =item * B<con_failed>: unable to contact remote host and unable to save message
 9329: for later delivery
 9330: 
 9331: =item * B<error:>: an error a occurred, a description of the error follows the :
 9332: 
 9333: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 9334: that was requested
 9335: 
 9336: =back
 9337: 
 9338: =head1 PUBLIC SUBROUTINES
 9339: 
 9340: =head2 Session Environment Functions
 9341: 
 9342: =over 4
 9343: 
 9344: =item * 
 9345: X<appenv()>
 9346: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
 9347: the user envirnoment file, and will be restored for each access this
 9348: user makes during this session, also modifies the %env for the current
 9349: process. Optional rolesarrayref - if defined contains a reference to an array
 9350: of roles which are exempt from the restriction on modifying user.role entries 
 9351: in the user's environment.db and in %env.    
 9352: 
 9353: =item *
 9354: X<delenv()>
 9355: B<delenv($delthis,$regexp)>: removes all items from the session
 9356: environment file that begin with $delthis. If the 
 9357: optional second arg - $regexp - is true, $delthis is treated as a 
 9358: regular expression, otherwise \Q$delthis\E is used. 
 9359: The values are also deleted from the current processes %env.
 9360: 
 9361: =item * get_env_multiple($name) 
 9362: 
 9363: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9364: values may be defined and end up as an array ref.
 9365: 
 9366: returns an array of values
 9367: 
 9368: =back
 9369: 
 9370: =head2 User Information
 9371: 
 9372: =over 4
 9373: 
 9374: =item *
 9375: X<queryauthenticate()>
 9376: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 9377: authentication scheme
 9378: 
 9379: =item *
 9380: X<authenticate()>
 9381: B<authenticate($uname,$upass,$udom)>: try to
 9382: authenticate user from domain's lib servers (first use the current
 9383: one). C<$upass> should be the users password.
 9384: 
 9385: =item *
 9386: X<homeserver()>
 9387: B<homeserver($uname,$udom)>: find the server which has
 9388: the user's directory and files (there must be only one), this caches
 9389: the answer, and also caches if there is a borken connection.
 9390: 
 9391: =item *
 9392: X<idget()>
 9393: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 9394: (IDs are a unique resource in a domain, there must be only 1 ID per
 9395: username, and only 1 username per ID in a specific domain) (returns
 9396: hash: id=>name,id=>name)
 9397: 
 9398: =item *
 9399: X<idrget()>
 9400: B<idrget($udom,@unames)>: find the IDs behind a list of
 9401: usernames (returns hash: name=>id,name=>id)
 9402: 
 9403: =item *
 9404: X<idput()>
 9405: B<idput($udom,%ids)>: store away a list of names and associated IDs
 9406: 
 9407: =item *
 9408: X<rolesinit()>
 9409: B<rolesinit($udom,$username,$authhost)>: get user privileges
 9410: 
 9411: =item *
 9412: X<getsection()>
 9413: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 9414: course $cname, return section name/number or '' for "not in course"
 9415: and '-1' for "no section"
 9416: 
 9417: =item *
 9418: X<userenvironment()>
 9419: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 9420: passed in @what from the requested user's environment, returns a hash
 9421: 
 9422: =item * 
 9423: X<userlog_query()>
 9424: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 9425: activity.log file. %filters defines filters applied when parsing the
 9426: log file. These can be start or end timestamps, or the type of action
 9427: - log to look for Login or Logout events, check for Checkin or
 9428: Checkout, role for role selection. The response is in the form
 9429: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 9430: escaped strings of the action recorded in the activity.log file.
 9431: 
 9432: =back
 9433: 
 9434: =head2 User Roles
 9435: 
 9436: =over 4
 9437: 
 9438: =item *
 9439: 
 9440: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 9441:  F: full access
 9442:  U,I,K: authentication modes (cxx only)
 9443:  '': forbidden
 9444:  1: user needs to choose course
 9445:  2: browse allowed
 9446:  A: passphrase authentication needed
 9447: 
 9448: =item *
 9449: 
 9450: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 9451: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 9452: and course level
 9453: 
 9454: =item *
 9455: 
 9456: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
 9457: (rolesplain.tab); plain text explanation of a user role term.
 9458: $type is Course (default) or Group.
 9459: If $forcedefault evaluates to true, text returned will be default 
 9460: text for $type. Otherwise, if this is a course, the text returned 
 9461: will be a custom name for the role (if defined in the course's 
 9462: environment).  If no custom name is defined the default is returned.
 9463:    
 9464: =item *
 9465: 
 9466: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
 9467: All arguments are optional. Returns a hash of a roles, either for
 9468: co-author/assistant author roles for a user's Construction Space
 9469: (default), or if $context is 'userroles', roles for the user himself,
 9470: In the hash, keys are set to colon-separated $uname,$udom,$role, and
 9471: (optionally) if $withsec is true, a fourth colon-separated item - $section.
 9472: For each key, value is set to colon-separated start and end times for
 9473: the role.  If no username and domain are specified, will default to
 9474: current user/domain. Types, roles, and roledoms are references to arrays
 9475: of role statuses (active, future or previous), roles 
 9476: (e.g., cc,in, st etc.) and domains of the roles which can be used
 9477: to restrict the list of roles reported. If no array ref is 
 9478: provided for types, will default to return only active roles.
 9479: 
 9480: =back
 9481: 
 9482: =head2 User Modification
 9483: 
 9484: =over 4
 9485: 
 9486: =item *
 9487: 
 9488: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
 9489: user for the level given by URL.  Optional start and end dates (leave empty
 9490: string or zero for "no date")
 9491: 
 9492: =item *
 9493: 
 9494: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 9495: change a users, password, possible return values are: ok,
 9496: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 9497: refused
 9498: 
 9499: =item *
 9500: 
 9501: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 9502: 
 9503: =item *
 9504: 
 9505: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
 9506:            $forceid,$desiredhome,$email,$inststatus) : 
 9507: modify user
 9508: 
 9509: =item *
 9510: 
 9511: modifystudent
 9512: 
 9513: modify a student's enrollment and identification information.
 9514: The course id is resolved based on the current users environment.  
 9515: This means the envoking user must be a course coordinator or otherwise
 9516: associated with a course.
 9517: 
 9518: This call is essentially a wrapper for lonnet::modifyuser and
 9519: lonnet::modify_student_enrollment
 9520: 
 9521: Inputs: 
 9522: 
 9523: =over 4
 9524: 
 9525: =item B<$udom> Student's loncapa domain
 9526: 
 9527: =item B<$uname> Student's loncapa login name
 9528: 
 9529: =item B<$uid> Student/Employee ID
 9530: 
 9531: =item B<$umode> Student's authentication mode
 9532: 
 9533: =item B<$upass> Student's password
 9534: 
 9535: =item B<$first> Student's first name
 9536: 
 9537: =item B<$middle> Student's middle name
 9538: 
 9539: =item B<$last> Student's last name
 9540: 
 9541: =item B<$gene> Student's generation
 9542: 
 9543: =item B<$usec> Student's section in course
 9544: 
 9545: =item B<$end> Unix time of the roles expiration
 9546: 
 9547: =item B<$start> Unix time of the roles start date
 9548: 
 9549: =item B<$forceid> If defined, allow $uid to be changed
 9550: 
 9551: =item B<$desiredhome> server to use as home server for student
 9552: 
 9553: =item B<$email> Student's permanent e-mail address
 9554: 
 9555: =item B<$type> Type of enrollment (auto or manual)
 9556: 
 9557: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
 9558: 
 9559: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
 9560: 
 9561: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
 9562: 
 9563: =item B<$context> role change context (shown in User Management Logs display in a course)
 9564: 
 9565: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
 9566: 
 9567: =back
 9568: 
 9569: =item *
 9570: 
 9571: modify_student_enrollment
 9572: 
 9573: Change a students enrollment status in a class.  The environment variable
 9574: 'role.request.course' must be defined for this function to proceed.
 9575: 
 9576: Inputs:
 9577: 
 9578: =over 4
 9579: 
 9580: =item $udom, students domain
 9581: 
 9582: =item $uname, students name
 9583: 
 9584: =item $uid, students user id
 9585: 
 9586: =item $first, students first name
 9587: 
 9588: =item $middle
 9589: 
 9590: =item $last
 9591: 
 9592: =item $gene
 9593: 
 9594: =item $usec
 9595: 
 9596: =item $end
 9597: 
 9598: =item $start
 9599: 
 9600: =item $type
 9601: 
 9602: =item $locktype
 9603: 
 9604: =item $cid
 9605: 
 9606: =item $selfenroll
 9607: 
 9608: =item $context
 9609: 
 9610: =back
 9611: 
 9612: 
 9613: =item *
 9614: 
 9615: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 9616: custom role; give a custom role to a user for the level given by URL.  Specify
 9617: name and domain of role author, and role name
 9618: 
 9619: =item *
 9620: 
 9621: revokerole($udom,$uname,$url,$role) : revoke a role for url
 9622: 
 9623: =item *
 9624: 
 9625: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 9626: 
 9627: =back
 9628: 
 9629: =head2 Course Infomation
 9630: 
 9631: =over 4
 9632: 
 9633: =item *
 9634: 
 9635: coursedescription($courseid) : returns a hash of information about the
 9636: specified course id, including all environment settings for the
 9637: course, the description of the course will be in the hash under the
 9638: key 'description'
 9639: 
 9640: =item *
 9641: 
 9642: resdata($name,$domain,$type,@which) : request for current parameter
 9643: setting for a specific $type, where $type is either 'course' or 'user',
 9644: @what should be a list of parameters to ask about. This routine caches
 9645: answers for 5 minutes.
 9646: 
 9647: =item *
 9648: 
 9649: get_courseresdata($courseid, $domain) : dump the entire course resource
 9650: data base, returning a hash that is keyed by the resource name and has
 9651: values that are the resource value.  I believe that the timestamps and
 9652: versions are also returned.
 9653: 
 9654: 
 9655: =back
 9656: 
 9657: =head2 Course Modification
 9658: 
 9659: =over 4
 9660: 
 9661: =item *
 9662: 
 9663: writecoursepref($courseid,%prefs) : write preferences (environment
 9664: database) for a course
 9665: 
 9666: =item *
 9667: 
 9668: createcourse($udom,$description,$url) : make/modify course
 9669: 
 9670: =back
 9671: 
 9672: =head2 Resource Subroutines
 9673: 
 9674: =over 4
 9675: 
 9676: =item *
 9677: 
 9678: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 9679: 
 9680: =item *
 9681: 
 9682: repcopy($filename) : subscribes to the requested file, and attempts to
 9683: replicate from the owning library server, Might return
 9684: 'unavailable', 'not_found', 'forbidden', 'ok', or
 9685: 'bad_request', also attempts to grab the metadata for the
 9686: resource. Expects the local filesystem pathname
 9687: (/home/httpd/html/res/....)
 9688: 
 9689: =back
 9690: 
 9691: =head2 Resource Information
 9692: 
 9693: =over 4
 9694: 
 9695: =item *
 9696: 
 9697: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 9698: a vairety of different possible values, $varname should be a request
 9699: string, and the other parameters can be used to specify who and what
 9700: one is asking about.
 9701: 
 9702: Possible values for $varname are environment.lastname (or other item
 9703: from the envirnment hash), user.name (or someother aspect about the
 9704: user), resource.0.maxtries (or some other part and parameter of a
 9705: resource)
 9706: 
 9707: =item *
 9708: 
 9709: directcondval($number) : get current value of a condition; reads from a state
 9710: string
 9711: 
 9712: =item *
 9713: 
 9714: condval($condidx) : value of condition index based on state
 9715: 
 9716: =item *
 9717: 
 9718: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 9719: resource's metadata, $what should be either a specific key, or either
 9720: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 9721: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 9722: 
 9723: this function automatically caches all requests
 9724: 
 9725: =item *
 9726: 
 9727: metadata_query($query,$custom,$customshow) : make a metadata query against the
 9728: network of library servers; returns file handle of where SQL and regex results
 9729: will be stored for query
 9730: 
 9731: =item *
 9732: 
 9733: symbread($filename) : return symbolic list entry (filename argument optional);
 9734: returns the data handle
 9735: 
 9736: =item *
 9737: 
 9738: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 9739: a possible symb for the URL in $thisfn, and if is an encryypted
 9740: resource that the user accessed using /enc/ returns a 1 on success, 0
 9741: on failure, user must be in a course, as it assumes the existance of
 9742: the course initial hash, and uses $env('request.course.id'}
 9743: 
 9744: 
 9745: =item *
 9746: 
 9747: symbclean($symb) : removes versions numbers from a symb, returns the
 9748: cleaned symb
 9749: 
 9750: =item *
 9751: 
 9752: is_on_map($uri) : checks if the $uri is somewhere on the current
 9753: course map, user must be in a course for it to work.
 9754: 
 9755: =item *
 9756: 
 9757: numval($salt) : return random seed value (addend for rndseed)
 9758: 
 9759: =item *
 9760: 
 9761: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 9762: a random seed, all arguments are optional, if they aren't sent it uses the
 9763: environment to derive them. Note: if symb isn't sent and it can't get one
 9764: from &symbread it will use the current time as its return value
 9765: 
 9766: =item *
 9767: 
 9768: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 9769: unfakeable, receipt
 9770: 
 9771: =item *
 9772: 
 9773: receipt() : API to ireceipt working off of env values; given out to users
 9774: 
 9775: =item *
 9776: 
 9777: countacc($url) : count the number of accesses to a given URL
 9778: 
 9779: =item *
 9780: 
 9781: 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
 9782: 
 9783: =item *
 9784: 
 9785: 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)
 9786: 
 9787: =item *
 9788: 
 9789: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 9790: 
 9791: =item *
 9792: 
 9793: devalidate($symb) : devalidate temporary spreadsheet calculations,
 9794: forcing spreadsheet to reevaluate the resource scores next time.
 9795: 
 9796: =back
 9797: 
 9798: =head2 Storing/Retreiving Data
 9799: 
 9800: =over 4
 9801: 
 9802: =item *
 9803: 
 9804: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 9805: for this url; hashref needs to be given and should be a \%hashname; the
 9806: remaining args aren't required and if they aren't passed or are '' they will
 9807: be derived from the env
 9808: 
 9809: =item *
 9810: 
 9811: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 9812: uses critical subroutine
 9813: 
 9814: =item *
 9815: 
 9816: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 9817: all args are optional
 9818: 
 9819: =item *
 9820: 
 9821: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 9822: dumps the complete (or key matching regexp) namespace into a hash
 9823: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 9824: normally &store()ed into
 9825: 
 9826: $range should be either an integer '100' (give me the first 100
 9827:                                            matching records)
 9828:               or be  two integers sperated by a - with no spaces
 9829:                  '30-50' (give me the 30th through the 50th matching
 9830:                           records)
 9831: 
 9832: 
 9833: =item *
 9834: 
 9835: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 9836: replaces a &store() version of data with a replacement set of data
 9837: for a particular resource in a namespace passed in the $storehash hash 
 9838: reference
 9839: 
 9840: =item *
 9841: 
 9842: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 9843: works very similar to store/cstore, but all data is stored in a
 9844: temporary location and can be reset using tmpreset, $storehash should
 9845: be a hash reference, returns nothing on success
 9846: 
 9847: =item *
 9848: 
 9849: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 9850: similar to restore, but all data is stored in a temporary location and
 9851: can be reset using tmpreset. Returns a hash of values on success,
 9852: error string otherwise.
 9853: 
 9854: =item *
 9855: 
 9856: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 9857: deltes all keys for $symb form the temporary storage hash.
 9858: 
 9859: =item *
 9860: 
 9861: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9862: reference filled in from namesp ($udom and $uname are optional)
 9863: 
 9864: =item *
 9865: 
 9866: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 9867: namesp ($udom and $uname are optional)
 9868: 
 9869: =item *
 9870: 
 9871: dump($namespace,$udom,$uname,$regexp,$range) : 
 9872: dumps the complete (or key matching regexp) namespace into a hash
 9873: ($udom, $uname, $regexp, $range are optional)
 9874: 
 9875: $range should be either an integer '100' (give me the first 100
 9876:                                            matching records)
 9877:               or be  two integers sperated by a - with no spaces
 9878:                  '30-50' (give me the 30th through the 50th matching
 9879:                           records)
 9880: =item *
 9881: 
 9882: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 9883: $store can be a scalar, an array reference, or if the amount to be 
 9884: incremented is > 1, a hash reference.
 9885: 
 9886: ($udom and $uname are optional)
 9887: 
 9888: =item *
 9889: 
 9890: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 9891: ($udom and $uname are optional)
 9892: 
 9893: =item *
 9894: 
 9895: cput($namespace,$storehash,$udom,$uname) : critical put
 9896: ($udom and $uname are optional)
 9897: 
 9898: =item *
 9899: 
 9900: newput($namespace,$storehash,$udom,$uname) :
 9901: 
 9902: Attempts to store the items in the $storehash, but only if they don't
 9903: currently exist, if this succeeds you can be certain that you have 
 9904: successfully created a new key value pair in the $namespace db.
 9905: 
 9906: 
 9907: Args:
 9908:  $namespace: name of database to store values to
 9909:  $storehash: hashref to store to the db
 9910:  $udom: (optional) domain of user containing the db
 9911:  $uname: (optional) name of user caontaining the db
 9912: 
 9913: Returns:
 9914:  'ok' -> succeeded in storing all keys of $storehash
 9915:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 9916:                         least <key> already existed in the db (other
 9917:                         requested keys may also already exist)
 9918:  'error: <msg>' -> unable to tie the DB or other error occurred
 9919:  'con_lost' -> unable to contact request server
 9920:  'refused' -> action was not allowed by remote machine
 9921: 
 9922: 
 9923: =item *
 9924: 
 9925: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9926: reference filled in from namesp (encrypts the return communication)
 9927: ($udom and $uname are optional)
 9928: 
 9929: =item *
 9930: 
 9931: log($udom,$name,$home,$message) : write to permanent log for user; use
 9932: critical subroutine
 9933: 
 9934: =item *
 9935: 
 9936: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
 9937: array reference filled in from namespace found in domain level on either
 9938: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
 9939: 
 9940: =item *
 9941: 
 9942: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
 9943: domain level either on specified domain server ($uhome) or primary domain 
 9944: server ($udom and $uhome are optional)
 9945: 
 9946: =item * 
 9947: 
 9948: get_domain_defaults($target_domain) : returns hash with defaults for
 9949: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
 9950: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
 9951: or localauth), initial password or a kerberos realm, language (e.g., en-us).
 9952: Values are retrieved from cache (if current), or from domain's configuration.db
 9953: (if available), or lastly from values in lonTabs/dns_domain,tab, 
 9954: or lonTabs/domain.tab. 
 9955: 
 9956: %domdefaults = &get_auth_defaults($target_domain);
 9957: 
 9958: =back
 9959: 
 9960: =head2 Network Status Functions
 9961: 
 9962: =over 4
 9963: 
 9964: =item *
 9965: 
 9966: dirlist($uri) : return directory list based on URI
 9967: 
 9968: =item *
 9969: 
 9970: spareserver() : find server with least workload from spare.tab
 9971: 
 9972: 
 9973: =item *
 9974: 
 9975: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
 9976: if there is no corresponding loncapa host.
 9977: 
 9978: =back
 9979: 
 9980: 
 9981: =head2 Apache Request
 9982: 
 9983: =over 4
 9984: 
 9985: =item *
 9986: 
 9987: ssi($url,%hash) : server side include, does a complete request cycle on url to
 9988: localhost, posts hash
 9989: 
 9990: =back
 9991: 
 9992: =head2 Data to String to Data
 9993: 
 9994: =over 4
 9995: 
 9996: =item *
 9997: 
 9998: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 9999: and '&' separators, supports elements that are arrayrefs and hashrefs
10000: 
10001: =item *
10002: 
10003: hashref2str($hashref) : convert a hashref into a string complete with
10004: escaping and '=' and '&' separators, supports elements that are
10005: arrayrefs and hashrefs
10006: 
10007: =item *
10008: 
10009: arrayref2str($arrayref) : convert an arrayref into a string complete
10010: with escaping and '&' separators, supports elements that are arrayrefs
10011: and hashrefs
10012: 
10013: =item *
10014: 
10015: str2hash($string) : convert string to hash using unescaping and
10016: splitting on '=' and '&', supports elements that are arrayrefs and
10017: hashrefs
10018: 
10019: =item *
10020: 
10021: str2array($string) : convert string to hash using unescaping and
10022: splitting on '&', supports elements that are arrayrefs and hashrefs
10023: 
10024: =back
10025: 
10026: =head2 Logging Routines
10027: 
10028: =over 4
10029: 
10030: These routines allow one to make log messages in the lonnet.log and
10031: lonnet.perm logfiles.
10032: 
10033: =item *
10034: 
10035: logtouch() : make sure the logfile, lonnet.log, exists
10036: 
10037: =item *
10038: 
10039: logthis() : append message to the normal lonnet.log file, it gets
10040: preiodically rolled over and deleted.
10041: 
10042: =item *
10043: 
10044: logperm() : append a permanent message to lonnet.perm.log, this log
10045: file never gets deleted by any automated portion of the system, only
10046: messages of critical importance should go in here.
10047: 
10048: =back
10049: 
10050: =head2 General File Helper Routines
10051: 
10052: =over 4
10053: 
10054: =item *
10055: 
10056: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10057: (a) files in /uploaded
10058:   (i) If a local copy of the file exists - 
10059:       compares modification date of local copy with last-modified date for 
10060:       definitive version stored on home server for course. If local copy is 
10061:       stale, requests a new version from the home server and stores it. 
10062:       If the original has been removed from the home server, then local copy 
10063:       is unlinked.
10064:   (ii) If local copy does not exist -
10065:       requests the file from the home server and stores it. 
10066:   
10067:   If $caller is 'uploadrep':  
10068:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10069:     for request for files originally uploaded via DOCS. 
10070:      - returns 'ok' if fresh local copy now available, -1 otherwise.
10071:   
10072:   Otherwise:
10073:      This indicates a call from the content generation phase of the request.
10074:      -  returns the entire contents of the file or -1.
10075:      
10076: (b) files in /res
10077:    - returns the entire contents of a file or -1; 
10078:    it properly subscribes to and replicates the file if neccessary.
10079: 
10080: 
10081: =item *
10082: 
10083: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10084:                   reference
10085: 
10086: returns either a stat() list of data about the file or an empty list
10087: if the file doesn't exist or couldn't find out about it (connection
10088: problems or user unknown)
10089: 
10090: =item *
10091: 
10092: filelocation($dir,$file) : returns file system location of a file
10093: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10094: directory that relative $file lookups are to looked in ($dir of /a/dir
10095: and a file of ../bob will become /a/bob)
10096: 
10097: =item *
10098: 
10099: hreflocation($dir,$file) : returns file system location or a URL; same as
10100: filelocation except for hrefs
10101: 
10102: =item *
10103: 
10104: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10105: 
10106: =back
10107: 
10108: =head2 Usererfile file routines (/uploaded*)
10109: 
10110: =over 4
10111: 
10112: =item *
10113: 
10114: userfileupload(): main rotine for putting a file in a user or course's
10115:                   filespace, arguments are,
10116: 
10117:  formname - required - this is the name of the element in $env where the
10118:            filename, and the contents of the file to create/modifed exist
10119:            the filename is in $env{'form.'.$formname.'.filename'} and the
10120:            contents of the file is located in $env{'form.'.$formname}
10121:  coursedoc - if true, store the file in the course of the active role
10122:              of the current user
10123:  subdir - required - subdirectory to put the file in under ../userfiles/
10124:          if undefined, it will be placed in "unknown"
10125: 
10126:  (This routine calls clean_filename() to remove any dangerous
10127:  characters from the filename, and then calls finuserfileupload() to
10128:  complete the transaction)
10129: 
10130:  returns either the url of the uploaded file (/uploaded/....) if successful
10131:  and /adm/notfound.html if unsuccessful
10132: 
10133: =item *
10134: 
10135: clean_filename(): routine for cleaing a filename up for storage in
10136:                  userfile space, argument is:
10137: 
10138:  filename - proposed filename
10139: 
10140: returns: the new clean filename
10141: 
10142: =item *
10143: 
10144: finishuserfileupload(): routine that creaes and sends the file to
10145: userspace, probably shouldn't be called directly
10146: 
10147:   docuname: username or courseid of destination for the file
10148:   docudom: domain of user/course of destination for the file
10149:   formname: same as for userfileupload()
10150:   fname: filename (inculding subdirectories) for the file
10151: 
10152:  returns either the url of the uploaded file (/uploaded/....) if successful
10153:  and /adm/notfound.html if unsuccessful
10154: 
10155: =item *
10156: 
10157: renameuserfile(): renames an existing userfile to a new name
10158: 
10159:   Args:
10160:    docuname: username or courseid of destination for the file
10161:    docudom: domain of user/course of destination for the file
10162:    old: current file name (including any subdirs under userfiles)
10163:    new: desired file name (including any subdirs under userfiles)
10164: 
10165: =item *
10166: 
10167: mkdiruserfile(): creates a directory is a userfiles dir
10168: 
10169:   Args:
10170:    docuname: username or courseid of destination for the file
10171:    docudom: domain of user/course of destination for the file
10172:    dir: dir to create (including any subdirs under userfiles)
10173: 
10174: =item *
10175: 
10176: removeuserfile(): removes a file that exists in userfiles
10177: 
10178:   Args:
10179:    docuname: username or courseid of destination for the file
10180:    docudom: domain of user/course of destination for the file
10181:    fname: filname to delete (including any subdirs under userfiles)
10182: 
10183: =item *
10184: 
10185: removeuploadedurl(): convience function for removeuserfile()
10186: 
10187:   Args:
10188:    url:  a full /uploaded/... url to delete
10189: 
10190: =item * 
10191: 
10192: get_portfile_permissions():
10193:   Args:
10194:     domain: domain of user or course contain the portfolio files
10195:     user: name of user or num of course contain the portfolio files
10196:   Returns:
10197:     hashref of a dump of the proper file_permissions.db
10198:    
10199: 
10200: =item * 
10201: 
10202: get_access_controls():
10203: 
10204: Args:
10205:   current_permissions: the hash ref returned from get_portfile_permissions()
10206:   group: (optional) the group you want the files associated with
10207:   file: (optional) the file you want access info on
10208: 
10209: Returns:
10210:     a hash (keys are file names) of hashes containing
10211:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10212:         values are XML containing access control settings (see below) 
10213: 
10214: Internal notes:
10215: 
10216:  access controls are stored in file_permissions.db as key=value pairs.
10217:     key -> path to file/file_name\0uniqueID:scope_end_start
10218:         where scope -> public,guest,course,group,domains or users.
10219:               end -> UNIX time for end of access (0 -> no end date)
10220:               start -> UNIX time for start of access
10221: 
10222:     value -> XML description of access control
10223:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10224:             <start></start>
10225:             <end></end>
10226: 
10227:             <password></password>  for scope type = guest
10228: 
10229:             <domain></domain>     for scope type = course or group
10230:             <number></number>
10231:             <roles id="">
10232:              <role></role>
10233:              <access></access>
10234:              <section></section>
10235:              <group></group>
10236:             </roles>
10237: 
10238:             <dom></dom>         for scope type = domains
10239: 
10240:             <users>             for scope type = users
10241:              <user>
10242:               <uname></uname>
10243:               <udom></udom>
10244:              </user>
10245:             </users>
10246:            </scope> 
10247:               
10248:  Access data is also aggregated for each file in an additional key=value pair:
10249:  key -> path to file/file_name\0accesscontrol 
10250:  value -> reference to hash
10251:           hash contains key = value pairs
10252:           where key = uniqueID:scope_end_start
10253:                 value = UNIX time record was last updated
10254: 
10255:           Used to improve speed of look-ups of access controls for each file.  
10256:  
10257:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10258: 
10259: modify_access_controls():
10260: 
10261: Modifies access controls for a portfolio file
10262: Args
10263: 1. file name
10264: 2. reference to hash of required changes,
10265: 3. domain
10266: 4. username
10267:   where domain,username are the domain of the portfolio owner 
10268:   (either a user or a course) 
10269: 
10270: Returns:
10271: 1. result of additions or updates ('ok' or 'error', with error message). 
10272: 2. result of deletions ('ok' or 'error', with error message).
10273: 3. reference to hash of any new or updated access controls.
10274: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10275:    key = integer (inbound ID)
10276:    value = uniqueID  
10277: 
10278: =back
10279: 
10280: =head2 HTTP Helper Routines
10281: 
10282: =over 4
10283: 
10284: =item *
10285: 
10286: escape() : unpack non-word characters into CGI-compatible hex codes
10287: 
10288: =item *
10289: 
10290: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10291: 
10292: =back
10293: 
10294: =head1 PRIVATE SUBROUTINES
10295: 
10296: =head2 Underlying communication routines (Shouldn't call)
10297: 
10298: =over 4
10299: 
10300: =item *
10301: 
10302: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10303: 
10304: =item *
10305: 
10306: reply() : uses subreply to send a message to remote machine, logs all failures
10307: 
10308: =item *
10309: 
10310: critical() : passes a critical message to another server; if cannot
10311: get through then place message in connection buffer directory and
10312: returns con_delayed, if incapable of saving message, returns
10313: con_failed
10314: 
10315: =item *
10316: 
10317: reconlonc() : tries to reconnect lonc client processes.
10318: 
10319: =back
10320: 
10321: =head2 Resource Access Logging
10322: 
10323: =over 4
10324: 
10325: =item *
10326: 
10327: flushcourselogs() : flush (save) buffer logs and access logs
10328: 
10329: =item *
10330: 
10331: courselog($what) : save message for course in hash
10332: 
10333: =item *
10334: 
10335: courseacclog($what) : save message for course using &courselog().  Perform
10336: special processing for specific resource types (problems, exams, quizzes, etc).
10337: 
10338: =item *
10339: 
10340: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10341: as a PerlChildExitHandler
10342: 
10343: =back
10344: 
10345: =head2 Other
10346: 
10347: =over 4
10348: 
10349: =item *
10350: 
10351: symblist($mapname,%newhash) : update symbolic storage links
10352: 
10353: =back
10354: 
10355: =cut
10356: 

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