File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.977: download - view: text, annotated - select for diffs
Tue Dec 9 11:32:03 2008 UTC (15 years, 7 months ago) by amueller
Branches: MAIN
CVS tags: HEAD
Add wrapper function for user photoupload to determine a photoupload in lonnet.pm. This function is used in lonaboutme.pm. Changes in function finishuserfileupload in lonnet.pm to resize a upload Image to max. size 300x400.By Alexander Schulze and Niels Neumann

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.977 2008/12/09 11:32:03 amueller 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 Date::Parse;
   79: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   80:             $_64bit %env %protocol);
   81: 
   82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   85:     %courseownerbuf, %coursetypebuf,$locknum);
   86: 
   87: use IO::Socket;
   88: use GDBM_File;
   89: use HTML::LCParser;
   90: use Fcntl qw(:flock);
   91: use Storable qw(thaw nfreeze);
   92: use Time::HiRes qw( gettimeofday tv_interval );
   93: use Cache::Memcached;
   94: use Digest::MD5;
   95: use Math::Random;
   96: use LONCAPA qw(:DEFAULT :match);
   97: use LONCAPA::Configuration;
   98: 
   99: my $readit;
  100: my $max_connection_retries = 10;     # Or some such value.
  101: 
  102: my $upload_photo_form = 0; #Variable to check  when user upload a photo 0=not 1=true
  103: 
  104: require Exporter;
  105: 
  106: our @ISA = qw (Exporter);
  107: our @EXPORT = qw(%env);
  108: 
  109: 
  110: # --------------------------------------------------------------------- Logging
  111: {
  112:     my $logid;
  113:     sub instructor_log {
  114: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  115:         if (($cnum eq '') || ($cdom eq '')) {
  116:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  117:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  118:         }
  119: 	$logid++;
  120:         my $now = time();
  121: 	my $id=$now.'00000'.$$.'00000'.$logid;
  122: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  123: 				    { $id => {
  124: 					'exe_uname' => $env{'user.name'},
  125: 					'exe_udom'  => $env{'user.domain'},
  126: 					'exe_time'  => $now,
  127: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  128: 					'delflag'   => $delflag,
  129: 					'logentry'  => $storehash,
  130: 					'uname'     => $uname,
  131: 					'udom'      => $udom,
  132: 				    }
  133: 				  },$cdom,$cnum);
  134:     }
  135: }
  136: 
  137: sub logtouch {
  138:     my $execdir=$perlvar{'lonDaemons'};
  139:     unless (-e "$execdir/logs/lonnet.log") {	
  140: 	open(my $fh,">>$execdir/logs/lonnet.log");
  141: 	close $fh;
  142:     }
  143:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  144:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  145: }
  146: 
  147: sub logthis {
  148:     my $message=shift;
  149:     my $execdir=$perlvar{'lonDaemons'};
  150:     my $now=time;
  151:     my $local=localtime($now);
  152:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  153: 	print $fh "$local ($$): $message\n";
  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: 
  185: # -------------------------------------------------- Non-critical communication
  186: sub subreply {
  187:     my ($cmd,$server)=@_;
  188:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  189:     #
  190:     #  With loncnew process trimming, there's a timing hole between lonc server
  191:     #  process exit and the master server picking up the listen on the AF_UNIX
  192:     #  socket.  In that time interval, a lock file will exist:
  193: 
  194:     my $lockfile=$peerfile.".lock";
  195:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  196: 	sleep(1);
  197:     }
  198:     # At this point, either a loncnew parent is listening or an old lonc
  199:     # or loncnew child is listening so we can connect or everything's dead.
  200:     #
  201:     #   We'll give the connection a few tries before abandoning it.  If
  202:     #   connection is not possible, we'll con_lost back to the client.
  203:     #   
  204:     my $client;
  205:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  206: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  207: 				      Type    => SOCK_STREAM,
  208: 				      Timeout => 10);
  209: 	if ($client) {
  210: 	    last;		# Connected!
  211: 	} else {
  212: 	    &create_connection(&hostname($server),$server);
  213: 	}
  214:         sleep(1);		# Try again later if failed connection.
  215:     }
  216:     my $answer;
  217:     if ($client) {
  218: 	print $client "sethost:$server:$cmd\n";
  219: 	$answer=<$client>;
  220: 	if (!$answer) { $answer="con_lost"; }
  221: 	chomp($answer);
  222:     } else {
  223: 	$answer = 'con_lost';	# Failed connection.
  224:     }
  225:     return $answer;
  226: }
  227: 
  228: sub reply {
  229:     my ($cmd,$server)=@_;
  230:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  231:     my $answer=subreply($cmd,$server);
  232:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  233:        &logthis("<font color=\"blue\">WARNING:".
  234:                 " $cmd to $server returned $answer</font>");
  235:     }
  236:     return $answer;
  237: }
  238: 
  239: # ----------------------------------------------------------- Send USR1 to lonc
  240: 
  241: sub reconlonc {
  242:     my ($lonid) = @_;
  243:     my $hostname = &hostname($lonid);
  244:     if ($lonid) {
  245: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  246: 	if ($hostname && -e $peerfile) {
  247: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  248: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  249: 					     Type    => SOCK_STREAM,
  250: 					     Timeout => 10);
  251: 	    if ($client) {
  252: 		print $client ("reset_retries\n");
  253: 		my $answer=<$client>;
  254: 		#reset just this one.
  255: 	    }
  256: 	}
  257: 	return;
  258:     }
  259: 
  260:     &logthis("Trying to reconnect lonc");
  261:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  262:     if (open(my $fh,"<$loncfile")) {
  263: 	my $loncpid=<$fh>;
  264:         chomp($loncpid);
  265:         if (kill 0 => $loncpid) {
  266: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  267:             kill USR1 => $loncpid;
  268:             sleep 1;
  269:          } else {
  270: 	    &logthis(
  271:                "<font color=\"blue\">WARNING:".
  272:                " lonc at pid $loncpid not responding, giving up</font>");
  273:         }
  274:     } else {
  275: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  276:     }
  277: }
  278: 
  279: # ------------------------------------------------------ Critical communication
  280: 
  281: sub critical {
  282:     my ($cmd,$server)=@_;
  283:     unless (&hostname($server)) {
  284:         &logthis("<font color=\"blue\">WARNING:".
  285:                " Critical message to unknown server ($server)</font>");
  286:         return 'no_such_host';
  287:     }
  288:     my $answer=reply($cmd,$server);
  289:     if ($answer eq 'con_lost') {
  290: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  291: 	my $answer=reply($cmd,$server);
  292:         if ($answer eq 'con_lost') {
  293:             my $now=time;
  294:             my $middlename=$cmd;
  295:             $middlename=substr($middlename,0,16);
  296:             $middlename=~s/\W//g;
  297:             my $dfilename=
  298:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  299:             $dumpcount++;
  300:             {
  301: 		my $dfh;
  302: 		if (open($dfh,">$dfilename")) {
  303: 		    print $dfh "$cmd\n"; 
  304: 		    close($dfh);
  305: 		}
  306:             }
  307:             sleep 2;
  308:             my $wcmd='';
  309:             {
  310: 		my $dfh;
  311: 		if (open($dfh,"<$dfilename")) {
  312: 		    $wcmd=<$dfh>; 
  313: 		    close($dfh);
  314: 		}
  315:             }
  316:             chomp($wcmd);
  317:             if ($wcmd eq $cmd) {
  318: 		&logthis("<font color=\"blue\">WARNING: ".
  319:                          "Connection buffer $dfilename: $cmd</font>");
  320:                 &logperm("D:$server:$cmd");
  321: 	        return 'con_delayed';
  322:             } else {
  323:                 &logthis("<font color=\"red\">CRITICAL:"
  324:                         ." Critical connection failed: $server $cmd</font>");
  325:                 &logperm("F:$server:$cmd");
  326:                 return 'con_failed';
  327:             }
  328:         }
  329:     }
  330:     return $answer;
  331: }
  332: 
  333: # ------------------------------------------- check if return value is an error
  334: 
  335: sub error {
  336:     my ($result) = @_;
  337:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  338: 	if ($2 == 2) { return undef; }
  339: 	return $1;
  340:     }
  341:     return undef;
  342: }
  343: 
  344: sub convert_and_load_session_env {
  345:     my ($lonidsdir,$handle)=@_;
  346:     my @profile;
  347:     {
  348: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  349: 	if (!$opened) {
  350: 	    return 0;
  351: 	}
  352: 	flock($idf,LOCK_SH);
  353: 	@profile=<$idf>;
  354: 	close($idf);
  355:     }
  356:     my %temp_env;
  357:     foreach my $line (@profile) {
  358: 	if ($line !~ m/=/) {
  359: 	    return 0;
  360: 	}
  361: 	chomp($line);
  362: 	my ($envname,$envvalue)=split(/=/,$line,2);
  363: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  364:     }
  365:     unlink("$lonidsdir/$handle.id");
  366:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  367: 	    0640)) {
  368: 	%disk_env = %temp_env;
  369: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  370: 	untie(%disk_env);
  371:     }
  372:     return 1;
  373: }
  374: 
  375: # ------------------------------------------- Transfer profile into environment
  376: my $env_loaded;
  377: sub transfer_profile_to_env {
  378:     my ($lonidsdir,$handle,$force_transfer) = @_;
  379:     if (!$force_transfer && $env_loaded) { return; } 
  380: 
  381:     if (!defined($lonidsdir)) {
  382: 	$lonidsdir = $perlvar{'lonIDsDir'};
  383:     }
  384:     if (!defined($handle)) {
  385:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  386:     }
  387: 
  388:     my $convert;
  389:     {
  390:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  391: 	if (!$opened) {
  392: 	    return;
  393: 	}
  394: 	flock($idf,LOCK_SH);
  395: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  396: 		&GDBM_READER(),0640)) {
  397: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  398: 	    untie(%disk_env);
  399: 	} else {
  400: 	    $convert = 1;
  401: 	}
  402:     }
  403:     if ($convert) {
  404: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  405: 	    &logthis("Failed to load session, or convert session.");
  406: 	}
  407:     }
  408: 
  409:     my %remove;
  410:     while ( my $envname = each(%env) ) {
  411:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  412:             if ($time < time-300) {
  413:                 $remove{$key}++;
  414:             }
  415:         }
  416:     }
  417: 
  418:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  419:     $env_loaded=1;
  420:     foreach my $expired_key (keys(%remove)) {
  421:         &delenv($expired_key);
  422:     }
  423: }
  424: 
  425: # ---------------------------------------------------- Check for valid session 
  426: sub check_for_valid_session {
  427:     my ($r) = @_;
  428:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  429:     my $lonid=$cookies{'lonID'};
  430:     return undef if (!$lonid);
  431: 
  432:     my $handle=&LONCAPA::clean_handle($lonid->value);
  433:     my $lonidsdir=$r->dir_config('lonIDsDir');
  434:     return undef if (!-e "$lonidsdir/$handle.id");
  435: 
  436:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  437:     return undef if (!$opened);
  438: 
  439:     flock($idf,LOCK_SH);
  440:     my %disk_env;
  441:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  442: 	    &GDBM_READER(),0640)) {
  443: 	return undef;	
  444:     }
  445: 
  446:     if (!defined($disk_env{'user.name'})
  447: 	|| !defined($disk_env{'user.domain'})) {
  448: 	return undef;
  449:     }
  450:     return $handle;
  451: }
  452: 
  453: sub timed_flock {
  454:     my ($file,$lock_type) = @_;
  455:     my $failed=0;
  456:     eval {
  457: 	local $SIG{__DIE__}='DEFAULT';
  458: 	local $SIG{ALRM}=sub {
  459: 	    $failed=1;
  460: 	    die("failed lock");
  461: 	};
  462: 	alarm(13);
  463: 	flock($file,$lock_type);
  464: 	alarm(0);
  465:     };
  466:     if ($failed) {
  467: 	return undef;
  468:     } else {
  469: 	return 1;
  470:     }
  471: }
  472: 
  473: # ---------------------------------------------------------- Append Environment
  474: 
  475: sub appenv {
  476:     my ($newenv,$roles) = @_;
  477:     if (ref($newenv) eq 'HASH') {
  478:         foreach my $key (keys(%{$newenv})) {
  479:             my $refused = 0;
  480: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  481:                 $refused = 1;
  482:                 if (ref($roles) eq 'ARRAY') {
  483:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  484:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  485:                         $refused = 0;
  486:                     }
  487:                 }
  488:             }
  489:             if ($refused) {
  490:                 &logthis("<font color=\"blue\">WARNING: ".
  491:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  492:                          .'</font>');
  493: 	        delete($newenv->{$key});
  494:             } else {
  495:                 $env{$key}=$newenv->{$key};
  496:             }
  497:         }
  498:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  499:         if ($opened
  500: 	    && &timed_flock($env_file,LOCK_EX)
  501: 	    &&
  502: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  503: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  504: 	    while (my ($key,$value) = each(%{$newenv})) {
  505: 	        $disk_env{$key} = $value;
  506: 	    }
  507: 	    untie(%disk_env);
  508:         }
  509:     }
  510:     return 'ok';
  511: }
  512: # ----------------------------------------------------- Delete from Environment
  513: 
  514: sub delenv {
  515:     my $delthis=shift;
  516:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  517:         &logthis("<font color=\"blue\">WARNING: ".
  518:                 "Attempt to delete from environment ".$delthis);
  519:         return 'error';
  520:     }
  521:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  522:     if ($opened
  523: 	&& &timed_flock($env_file,LOCK_EX)
  524: 	&&
  525: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  526: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  527: 	foreach my $key (keys(%disk_env)) {
  528: 	    if ($key=~/^$delthis/) { 
  529: 		delete($env{$key});
  530: 		delete($disk_env{$key});
  531: 	    }
  532: 	}
  533: 	untie(%disk_env);
  534:     }
  535:     return 'ok';
  536: }
  537: 
  538: sub get_env_multiple {
  539:     my ($name) = @_;
  540:     my @values;
  541:     if (defined($env{$name})) {
  542:         # exists is it an array
  543:         if (ref($env{$name})) {
  544:             @values=@{ $env{$name} };
  545:         } else {
  546:             $values[0]=$env{$name};
  547:         }
  548:     }
  549:     return(@values);
  550: }
  551: 
  552: # ------------------------------------------------------------------- Locking
  553: 
  554: sub set_lock {
  555:     my ($text)=@_;
  556:     $locknum++;
  557:     my $id=$$.'-'.$locknum;
  558:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  559:              'session.lock.'.$id => $text});
  560:     return $id;
  561: }
  562: 
  563: sub get_locks {
  564:     my $num=0;
  565:     my %texts=();
  566:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  567:        if ($lock=~/\w/) {
  568:           $num++;
  569:           $texts{$lock}=$env{'session.lock.'.$lock};
  570:        }
  571:    }
  572:    return ($num,%texts);
  573: }
  574: 
  575: sub remove_lock {
  576:     my ($id)=@_;
  577:     my $newlocks='';
  578:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  579:        if (($lock=~/\w/) && ($lock ne $id)) {
  580:           $newlocks.=','.$lock;
  581:        }
  582:     }
  583:     &appenv({'session.locks' => $newlocks});
  584:     &delenv('session.lock.'.$id);
  585: }
  586: 
  587: sub remove_all_locks {
  588:     my $activelocks=$env{'session.locks'};
  589:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  590:        if ($lock=~/\w/) {
  591:           &remove_lock($lock);
  592:        }
  593:     }
  594: }
  595: 
  596: 
  597: # ------------------------------------------ Find out current server userload
  598: sub userload {
  599:     my $numusers=0;
  600:     {
  601: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  602: 	my $filename;
  603: 	my $curtime=time;
  604: 	while ($filename=readdir(LONIDS)) {
  605: 	    next if ($filename eq '.' || $filename eq '..');
  606: 	    next if ($filename =~ /publicuser_\d+\.id/);
  607: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  608: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  609: 	}
  610: 	closedir(LONIDS);
  611:     }
  612:     my $userloadpercent=0;
  613:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  614:     if ($maxuserload) {
  615: 	$userloadpercent=100*$numusers/$maxuserload;
  616:     }
  617:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  618:     return $userloadpercent;
  619: }
  620: 
  621: # ------------------------------------------ Fight off request when overloaded
  622: 
  623: sub overloaderror {
  624:     my ($r,$checkserver)=@_;
  625:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  626:     my $loadavg;
  627:     if ($checkserver eq $perlvar{'lonHostID'}) {
  628:        open(my $loadfile,'/proc/loadavg');
  629:        $loadavg=<$loadfile>;
  630:        $loadavg =~ s/\s.*//g;
  631:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  632:        close($loadfile);
  633:     } else {
  634:        $loadavg=&reply('load',$checkserver);
  635:     }
  636:     my $overload=$loadavg-100;
  637:     if ($overload>0) {
  638: 	$r->err_headers_out->{'Retry-After'}=$overload;
  639:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  640:         return 413;
  641:     }    
  642:     return '';
  643: }
  644: 
  645: # ------------------------------ Find server with least workload from spare.tab
  646: 
  647: sub spareserver {
  648:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  649:     my $spare_server;
  650:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  651:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  652:                                                      :  $userloadpercent;
  653:     
  654:     foreach my $try_server (@{ $spareid{'primary'} }) {
  655: 	($spare_server, $lowest_load) =
  656: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  657:     }
  658: 
  659:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  660: 
  661:     if (!$found_server) {
  662: 	foreach my $try_server (@{ $spareid{'default'} }) {
  663: 	    ($spare_server, $lowest_load) =
  664: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  665: 	}
  666:     }
  667: 
  668:     if (!$want_server_name) {
  669:         my $protocol = 'http';
  670:         if ($protocol{$spare_server} eq 'https') {
  671:             $protocol = $protocol{$spare_server};
  672:         }
  673: 	$spare_server = $protocol.'://'.&hostname($spare_server);
  674:     }
  675:     return $spare_server;
  676: }
  677: 
  678: sub compare_server_load {
  679:     my ($try_server, $spare_server, $lowest_load) = @_;
  680: 
  681:     my $loadans     = &reply('load',    $try_server);
  682:     my $userloadans = &reply('userload',$try_server);
  683: 
  684:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  685: 	next; #didn't get a number from the server
  686:     }
  687: 
  688:     my $load;
  689:     if ($loadans =~ /\d/) {
  690: 	if ($userloadans =~ /\d/) {
  691: 	    #both are numbers, pick the bigger one
  692: 	    $load = ($loadans > $userloadans) ? $loadans 
  693: 		                              : $userloadans;
  694: 	} else {
  695: 	    $load = $loadans;
  696: 	}
  697:     } else {
  698: 	$load = $userloadans;
  699:     }
  700: 
  701:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  702: 	$spare_server = $try_server;
  703: 	$lowest_load  = $load;
  704:     }
  705:     return ($spare_server,$lowest_load);
  706: }
  707: 
  708: # --------------------------- ask offload servers if user already has a session
  709: sub find_existing_session {
  710:     my ($udom,$uname) = @_;
  711:     foreach my $try_server (@{ $spareid{'primary'} },
  712: 			    @{ $spareid{'default'} }) {
  713: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
  714:     }
  715:     return;
  716: }
  717: 
  718: # -------------------------------- ask if server already has a session for user
  719: sub has_user_session {
  720:     my ($lonid,$udom,$uname) = @_;
  721:     my $result = &reply(join(':','userhassession',
  722: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  723:     return 1 if ($result eq 'ok');
  724: 
  725:     return 0;
  726: }
  727: 
  728: # --------------------------------------------- Try to change a user's password
  729: 
  730: sub changepass {
  731:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  732:     $currentpass = &escape($currentpass);
  733:     $newpass     = &escape($newpass);
  734:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  735: 		       $server);
  736:     if (! $answer) {
  737: 	&logthis("No reply on password change request to $server ".
  738: 		 "by $uname in domain $udom.");
  739:     } elsif ($answer =~ "^ok") {
  740:         &logthis("$uname in $udom successfully changed their password ".
  741: 		 "on $server.");
  742:     } elsif ($answer =~ "^pwchange_failure") {
  743: 	&logthis("$uname in $udom was unable to change their password ".
  744: 		 "on $server.  The action was blocked by either lcpasswd ".
  745: 		 "or pwchange");
  746:     } elsif ($answer =~ "^non_authorized") {
  747:         &logthis("$uname in $udom did not get their password correct when ".
  748: 		 "attempting to change it on $server.");
  749:     } elsif ($answer =~ "^auth_mode_error") {
  750:         &logthis("$uname in $udom attempted to change their password despite ".
  751: 		 "not being locally or internally authenticated on $server.");
  752:     } elsif ($answer =~ "^unknown_user") {
  753:         &logthis("$uname in $udom attempted to change their password ".
  754: 		 "on $server but were unable to because $server is not ".
  755: 		 "their home server.");
  756:     } elsif ($answer =~ "^refused") {
  757: 	&logthis("$server refused to change $uname in $udom password because ".
  758: 		 "it was sent an unencrypted request to change the password.");
  759:     }
  760:     return $answer;
  761: }
  762: 
  763: # ----------------------- Try to determine user's current authentication scheme
  764: 
  765: sub queryauthenticate {
  766:     my ($uname,$udom)=@_;
  767:     my $uhome=&homeserver($uname,$udom);
  768:     if (!$uhome) {
  769: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  770: 	return 'no_host';
  771:     }
  772:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  773:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  774: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  775:     }
  776:     return $answer;
  777: }
  778: 
  779: # --------- Try to authenticate user from domain's lib servers (first this one)
  780: 
  781: sub authenticate {
  782:     my ($uname,$upass,$udom,$checkdefauth)=@_;
  783:     $upass=&escape($upass);
  784:     $uname= &LONCAPA::clean_username($uname);
  785:     my $uhome=&homeserver($uname,$udom,1);
  786:     my $newhome;
  787:     if ((!$uhome) || ($uhome eq 'no_host')) {
  788: # Maybe the machine was offline and only re-appeared again recently?
  789:         &reconlonc();
  790: # One more
  791: 	$uhome=&homeserver($uname,$udom,1);
  792:         if (($uhome eq 'no_host') && $checkdefauth) {
  793:             if (defined(&domain($udom,'primary'))) {
  794:                 $newhome=&domain($udom,'primary');
  795:             }
  796:             if ($newhome ne '') {
  797:                 $uhome = $newhome;
  798:             }
  799:         }
  800: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  801: 	    &logthis("User $uname at $udom is unknown in authenticate");
  802: 	    return 'no_host';
  803:         }
  804:     }
  805:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
  806:     if ($answer eq 'authorized') {
  807:         if ($newhome) {
  808:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
  809:             return 'no_account_on_host'; 
  810:         } else {
  811:             &logthis("User $uname at $udom authorized by $uhome");
  812:             return $uhome;
  813:         }
  814:     }
  815:     if ($answer eq 'non_authorized') {
  816: 	&logthis("User $uname at $udom rejected by $uhome");
  817: 	return 'no_host'; 
  818:     }
  819:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  820:     return 'no_host';
  821: }
  822: 
  823: # ---------------------- Find the homebase for a user from domain's lib servers
  824: 
  825: my %homecache;
  826: sub homeserver {
  827:     my ($uname,$udom,$ignoreBadCache)=@_;
  828:     my $index="$uname:$udom";
  829: 
  830:     if (exists($homecache{$index})) { return $homecache{$index}; }
  831: 
  832:     my %servers = &get_servers($udom,'library');
  833:     foreach my $tryserver (keys(%servers)) {
  834:         next if ($ignoreBadCache ne 'true' && 
  835: 		 exists($badServerCache{$tryserver}));
  836: 
  837: 	my $answer=reply("home:$udom:$uname",$tryserver);
  838: 	if ($answer eq 'found') {
  839: 	    delete($badServerCache{$tryserver}); 
  840: 	    return $homecache{$index}=$tryserver;
  841: 	} elsif ($answer eq 'no_host') {
  842: 	    $badServerCache{$tryserver}=1;
  843: 	}
  844:     }    
  845:     return 'no_host';
  846: }
  847: 
  848: # ------------------------------------- Find the usernames behind a list of IDs
  849: 
  850: sub idget {
  851:     my ($udom,@ids)=@_;
  852:     my %returnhash=();
  853:     
  854:     my %servers = &get_servers($udom,'library');
  855:     foreach my $tryserver (keys(%servers)) {
  856: 	my $idlist=join('&',@ids);
  857: 	$idlist=~tr/A-Z/a-z/; 
  858: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  859: 	my @answer=();
  860: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  861: 	    @answer=split(/\&/,$reply);
  862: 	}                    ;
  863: 	my $i;
  864: 	for ($i=0;$i<=$#ids;$i++) {
  865: 	    if ($answer[$i]) {
  866: 		$returnhash{$ids[$i]}=$answer[$i];
  867: 	    } 
  868: 	}
  869:     } 
  870:     return %returnhash;
  871: }
  872: 
  873: # ------------------------------------- Find the IDs behind a list of usernames
  874: 
  875: sub idrget {
  876:     my ($udom,@unames)=@_;
  877:     my %returnhash=();
  878:     foreach my $uname (@unames) {
  879:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  880:     }
  881:     return %returnhash;
  882: }
  883: 
  884: # ------------------------------- Store away a list of names and associated IDs
  885: 
  886: sub idput {
  887:     my ($udom,%ids)=@_;
  888:     my %servers=();
  889:     foreach my $uname (keys(%ids)) {
  890: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  891:         my $uhom=&homeserver($uname,$udom);
  892:         if ($uhom ne 'no_host') {
  893:             my $id=&escape($ids{$uname});
  894:             $id=~tr/A-Z/a-z/;
  895:             my $esc_unam=&escape($uname);
  896: 	    if ($servers{$uhom}) {
  897: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  898:             } else {
  899:                 $servers{$uhom}=$id.'='.$esc_unam;
  900:             }
  901:         }
  902:     }
  903:     foreach my $server (keys(%servers)) {
  904:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  905:     }
  906: }
  907: 
  908: # ------------------------------------------- get items from domain db files   
  909: 
  910: sub get_dom {
  911:     my ($namespace,$storearr,$udom,$uhome)=@_;
  912:     my $items='';
  913:     foreach my $item (@$storearr) {
  914:         $items.=&escape($item).'&';
  915:     }
  916:     $items=~s/\&$//;
  917:     if (!$udom) {
  918:         $udom=$env{'user.domain'};
  919:         if (defined(&domain($udom,'primary'))) {
  920:             $uhome=&domain($udom,'primary');
  921:         } else {
  922:             undef($uhome);
  923:         }
  924:     } else {
  925:         if (!$uhome) {
  926:             if (defined(&domain($udom,'primary'))) {
  927:                 $uhome=&domain($udom,'primary');
  928:             }
  929:         }
  930:     }
  931:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  932:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  933:         my %returnhash;
  934:         if ($rep eq '' || $rep =~ /^error: 2 /) {
  935:             return %returnhash;
  936:         }
  937:         my @pairs=split(/\&/,$rep);
  938:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  939:             return @pairs;
  940:         }
  941:         my $i=0;
  942:         foreach my $item (@$storearr) {
  943:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  944:             $i++;
  945:         }
  946:         return %returnhash;
  947:     } else {
  948:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
  949:     }
  950: }
  951: 
  952: # -------------------------------------------- put items in domain db files 
  953: 
  954: sub put_dom {
  955:     my ($namespace,$storehash,$udom,$uhome)=@_;
  956:     if (!$udom) {
  957:         $udom=$env{'user.domain'};
  958:         if (defined(&domain($udom,'primary'))) {
  959:             $uhome=&domain($udom,'primary');
  960:         } else {
  961:             undef($uhome);
  962:         }
  963:     } else {
  964:         if (!$uhome) {
  965:             if (defined(&domain($udom,'primary'))) {
  966:                 $uhome=&domain($udom,'primary');
  967:             }
  968:         }
  969:     } 
  970:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  971:         my $items='';
  972:         foreach my $item (keys(%$storehash)) {
  973:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  974:         }
  975:         $items=~s/\&$//;
  976:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  977:     } else {
  978:         &logthis("put_dom failed - no homeserver and/or domain");
  979:     }
  980: }
  981: 
  982: sub retrieve_inst_usertypes {
  983:     my ($udom) = @_;
  984:     my (%returnhash,@order);
  985:     if (defined(&domain($udom,'primary'))) {
  986:         my $uhome=&domain($udom,'primary');
  987:         my $rep=&reply("inst_usertypes:$udom",$uhome);
  988:         if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
  989:             &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
  990:             return (\%returnhash,\@order);
  991:         }
  992:         my ($hashitems,$orderitems) = split(/:/,$rep); 
  993:         my @pairs=split(/\&/,$hashitems);
  994:         foreach my $item (@pairs) {
  995:             my ($key,$value)=split(/=/,$item,2);
  996:             $key = &unescape($key);
  997:             next if ($key =~ /^error: 2 /);
  998:             $returnhash{$key}=&thaw_unescape($value);
  999:         }
 1000:         my @esc_order = split(/\&/,$orderitems);
 1001:         foreach my $item (@esc_order) {
 1002:             push(@order,&unescape($item));
 1003:         }
 1004:     } else {
 1005:         &logthis("get_dom failed - no primary domain server for $udom");
 1006:     }
 1007:     return (\%returnhash,\@order);
 1008: }
 1009: 
 1010: sub is_domainimage {
 1011:     my ($url) = @_;
 1012:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1013:         if (&domain($1) ne '') {
 1014:             return '1';
 1015:         }
 1016:     }
 1017:     return;
 1018: }
 1019: 
 1020: sub inst_directory_query {
 1021:     my ($srch) = @_;
 1022:     my $udom = $srch->{'srchdomain'};
 1023:     my %results;
 1024:     my $homeserver = &domain($udom,'primary');
 1025:     my $outcome;
 1026:     if ($homeserver ne '') {
 1027: 	my $queryid=&reply("querysend:instdirsearch:".
 1028: 			   &escape($srch->{'srchby'}).':'.
 1029: 			   &escape($srch->{'srchterm'}).':'.
 1030: 			   &escape($srch->{'srchtype'}),$homeserver);
 1031: 	my $host=&hostname($homeserver);
 1032: 	if ($queryid !~/^\Q$host\E\_/) {
 1033: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1034: 	    return;
 1035: 	}
 1036: 	my $response = &get_query_reply($queryid);
 1037: 	my $maxtries = 5;
 1038: 	my $tries = 1;
 1039: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1040: 	    $response = &get_query_reply($queryid);
 1041: 	    $tries ++;
 1042: 	}
 1043: 
 1044:         if (!&error($response) && $response ne 'refused') {
 1045:             if ($response eq 'unavailable') {
 1046:                 $outcome = $response;
 1047:             } else {
 1048:                 $outcome = 'ok';
 1049:                 my @matches = split(/\n/,$response);
 1050:                 foreach my $match (@matches) {
 1051:                     my ($key,$value) = split(/=/,$match);
 1052:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1053:                 }
 1054:             }
 1055:         }
 1056:     }
 1057:     return ($outcome,%results);
 1058: }
 1059: 
 1060: sub usersearch {
 1061:     my ($srch) = @_;
 1062:     my $dom = $srch->{'srchdomain'};
 1063:     my %results;
 1064:     my %libserv = &all_library();
 1065:     my $query = 'usersearch';
 1066:     foreach my $tryserver (keys(%libserv)) {
 1067:         if (&host_domain($tryserver) eq $dom) {
 1068:             my $host=&hostname($tryserver);
 1069:             my $queryid=
 1070:                 &reply("querysend:".&escape($query).':'.
 1071:                        &escape($srch->{'srchby'}).':'.
 1072:                        &escape($srch->{'srchtype'}).':'.
 1073:                        &escape($srch->{'srchterm'}),$tryserver);
 1074:             if ($queryid !~/^\Q$host\E\_/) {
 1075:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1076:                 next;
 1077:             }
 1078:             my $reply = &get_query_reply($queryid);
 1079:             my $maxtries = 1;
 1080:             my $tries = 1;
 1081:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1082:                 $reply = &get_query_reply($queryid);
 1083:                 $tries ++;
 1084:             }
 1085:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1086:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1087:             } else {
 1088:                 my @matches;
 1089:                 if ($reply =~ /\n/) {
 1090:                     @matches = split(/\n/,$reply);
 1091:                 } else {
 1092:                     @matches = split(/\&/,$reply);
 1093:                 }
 1094:                 foreach my $match (@matches) {
 1095:                     my ($uname,$udom,%userhash);
 1096:                     foreach my $entry (split(/:/,$match)) {
 1097:                         my ($key,$value) =
 1098:                             map {&unescape($_);} split(/=/,$entry);
 1099:                         $userhash{$key} = $value;
 1100:                         if ($key eq 'username') {
 1101:                             $uname = $value;
 1102:                         } elsif ($key eq 'domain') {
 1103:                             $udom = $value;
 1104:                         }
 1105:                     }
 1106:                     $results{$uname.':'.$udom} = \%userhash;
 1107:                 }
 1108:             }
 1109:         }
 1110:     }
 1111:     return %results;
 1112: }
 1113: 
 1114: sub get_instuser {
 1115:     my ($udom,$uname,$id) = @_;
 1116:     my $homeserver = &domain($udom,'primary');
 1117:     my ($outcome,%results);
 1118:     if ($homeserver ne '') {
 1119:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1120:                            &escape($id).':'.&escape($udom),$homeserver);
 1121:         my $host=&hostname($homeserver);
 1122:         if ($queryid !~/^\Q$host\E\_/) {
 1123:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1124:             return;
 1125:         }
 1126:         my $response = &get_query_reply($queryid);
 1127:         my $maxtries = 5;
 1128:         my $tries = 1;
 1129:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1130:             $response = &get_query_reply($queryid);
 1131:             $tries ++;
 1132:         }
 1133:         if (!&error($response) && $response ne 'refused') {
 1134:             if ($response eq 'unavailable') {
 1135:                 $outcome = $response;
 1136:             } else {
 1137:                 $outcome = 'ok';
 1138:                 my @matches = split(/\n/,$response);
 1139:                 foreach my $match (@matches) {
 1140:                     my ($key,$value) = split(/=/,$match);
 1141:                     $results{&unescape($key)} = &thaw_unescape($value);
 1142:                 }
 1143:             }
 1144:         }
 1145:     }
 1146:     my %userinfo;
 1147:     if (ref($results{$uname}) eq 'HASH') {
 1148:         %userinfo = %{$results{$uname}};
 1149:     } 
 1150:     return ($outcome,%userinfo);
 1151: }
 1152: 
 1153: sub inst_rulecheck {
 1154:     my ($udom,$uname,$id,$item,$rules) = @_;
 1155:     my %returnhash;
 1156:     if ($udom ne '') {
 1157:         if (ref($rules) eq 'ARRAY') {
 1158:             @{$rules} = map {&escape($_);} (@{$rules});
 1159:             my $rulestr = join(':',@{$rules});
 1160:             my $homeserver=&domain($udom,'primary');
 1161:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1162:                 my $response;
 1163:                 if ($item eq 'username') {                
 1164:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1165:                                               ':'.&escape($uname).':'.$rulestr,
 1166:                                               $homeserver));
 1167:                 } elsif ($item eq 'id') {
 1168:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1169:                                               ':'.&escape($id).':'.$rulestr,
 1170:                                               $homeserver));
 1171:                 } elsif ($item eq 'selfcreate') {
 1172:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1173:                                                &escape($udom).':'.&escape($uname).
 1174:                                               ':'.$rulestr,$homeserver));
 1175:                 }
 1176:                 if ($response ne 'refused') {
 1177:                     my @pairs=split(/\&/,$response);
 1178:                     foreach my $item (@pairs) {
 1179:                         my ($key,$value)=split(/=/,$item,2);
 1180:                         $key = &unescape($key);
 1181:                         next if ($key =~ /^error: 2 /);
 1182:                         $returnhash{$key}=&thaw_unescape($value);
 1183:                     }
 1184:                 }
 1185:             }
 1186:         }
 1187:     }
 1188:     return %returnhash;
 1189: }
 1190: 
 1191: sub inst_userrules {
 1192:     my ($udom,$check) = @_;
 1193:     my (%ruleshash,@ruleorder);
 1194:     if ($udom ne '') {
 1195:         my $homeserver=&domain($udom,'primary');
 1196:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1197:             my $response;
 1198:             if ($check eq 'id') {
 1199:                 $response=&reply('instidrules:'.&escape($udom),
 1200:                                  $homeserver);
 1201:             } elsif ($check eq 'email') {
 1202:                 $response=&reply('instemailrules:'.&escape($udom),
 1203:                                  $homeserver);
 1204:             } else {
 1205:                 $response=&reply('instuserrules:'.&escape($udom),
 1206:                                  $homeserver);
 1207:             }
 1208:             if (($response ne 'refused') && ($response ne 'error') && 
 1209:                 ($response ne 'unknown_cmd') && 
 1210:                 ($response ne 'no_such_host')) {
 1211:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1212:                 my @pairs=split(/\&/,$hashitems);
 1213:                 foreach my $item (@pairs) {
 1214:                     my ($key,$value)=split(/=/,$item,2);
 1215:                     $key = &unescape($key);
 1216:                     next if ($key =~ /^error: 2 /);
 1217:                     $ruleshash{$key}=&thaw_unescape($value);
 1218:                 }
 1219:                 my @esc_order = split(/\&/,$orderitems);
 1220:                 foreach my $item (@esc_order) {
 1221:                     push(@ruleorder,&unescape($item));
 1222:                 }
 1223:             }
 1224:         }
 1225:     }
 1226:     return (\%ruleshash,\@ruleorder);
 1227: }
 1228: 
 1229: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1230: 
 1231: sub get_domain_defaults {
 1232:     my ($domain) = @_;
 1233:     my $cachetime = 60*60*24;
 1234:     my ($defauthtype,$defautharg,$deflang,%deftools);
 1235:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1236:     if (defined($cached)) {
 1237:         if (ref($result) eq 'HASH') {
 1238:             return %{$result};
 1239:         }
 1240:     }
 1241:     my %domdefaults;
 1242:     my %domconfig =
 1243:          &Apache::lonnet::get_dom('configuration',['defaults','quotas'],$domain);
 1244:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1245:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1246:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1247:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1248:     } else {
 1249:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1250:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1251:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1252:     }
 1253:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1254:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1255:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1256:         } else {
 1257:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1258:         } 
 1259:         my @usertools = ('aboutme','blog','portfolio');
 1260:         foreach my $item (@usertools) {
 1261:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1262:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1263:             }
 1264:         }
 1265:     }
 1266:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1267:                                   $cachetime);
 1268:     return %domdefaults;
 1269: }
 1270: 
 1271: # --------------------------------------------------- Assign a key to a student
 1272: 
 1273: sub assign_access_key {
 1274: #
 1275: # a valid key looks like uname:udom#comments
 1276: # comments are being appended
 1277: #
 1278:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1279:     $kdom=
 1280:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1281:     $knum=
 1282:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1283:     $cdom=
 1284:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1285:     $cnum=
 1286:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1287:     $udom=$env{'user.name'} unless (defined($udom));
 1288:     $uname=$env{'user.domain'} unless (defined($uname));
 1289:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1290:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1291:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1292:                                                   # assigned to this person
 1293:                                                   # - this should not happen,
 1294:                                                   # unless something went wrong
 1295:                                                   # the first time around
 1296: # ready to assign
 1297:         $logentry=$1.'; '.$logentry;
 1298:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1299:                                                  $kdom,$knum) eq 'ok') {
 1300: # key now belongs to user
 1301: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1302:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1303:                 &appenv({'environment.'.$envkey => $ckey});
 1304:                 return 'ok';
 1305:             } else {
 1306:                 return 
 1307:   'error: Count not permanently assign key, will need to be re-entered later.';
 1308: 	    }
 1309:         } else {
 1310:             return 'error: Could not assign key, try again later.';
 1311:         }
 1312:     } elsif (!$existing{$ckey}) {
 1313: # the key does not exist
 1314: 	return 'error: The key does not exist';
 1315:     } else {
 1316: # the key is somebody else's
 1317: 	return 'error: The key is already in use';
 1318:     }
 1319: }
 1320: 
 1321: # ------------------------------------------ put an additional comment on a key
 1322: 
 1323: sub comment_access_key {
 1324: #
 1325: # a valid key looks like uname:udom#comments
 1326: # comments are being appended
 1327: #
 1328:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1329:     $cdom=
 1330:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1331:     $cnum=
 1332:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1333:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1334:     if ($existing{$ckey}) {
 1335:         $existing{$ckey}.='; '.$logentry;
 1336: # ready to assign
 1337:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1338:                                                  $cdom,$cnum) eq 'ok') {
 1339: 	    return 'ok';
 1340:         } else {
 1341: 	    return 'error: Count not store comment.';
 1342:         }
 1343:     } else {
 1344: # the key does not exist
 1345: 	return 'error: The key does not exist';
 1346:     }
 1347: }
 1348: 
 1349: # ------------------------------------------------------ Generate a set of keys
 1350: 
 1351: sub generate_access_keys {
 1352:     my ($number,$cdom,$cnum,$logentry)=@_;
 1353:     $cdom=
 1354:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1355:     $cnum=
 1356:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1357:     unless (&allowed('mky',$cdom)) { return 0; }
 1358:     unless (($cdom) && ($cnum)) { return 0; }
 1359:     if ($number>10000) { return 0; }
 1360:     sleep(2); # make sure don't get same seed twice
 1361:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1362:     my $total=0;
 1363:     for (my $i=1;$i<=$number;$i++) {
 1364:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1365:                   sprintf("%lx",int(100000*rand)).'-'.
 1366:                   sprintf("%lx",int(100000*rand));
 1367:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1368:        $newkey=~s/0/h/g; # and also 0 and O
 1369:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1370:        if ($existing{$newkey}) {
 1371:            $i--;
 1372:        } else {
 1373: 	  if (&put('accesskeys',
 1374:               { $newkey => '# generated '.localtime().
 1375:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1376:                            '; '.$logentry },
 1377: 		   $cdom,$cnum) eq 'ok') {
 1378:               $total++;
 1379: 	  }
 1380:        }
 1381:     }
 1382:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1383:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1384:     return $total;
 1385: }
 1386: 
 1387: # ------------------------------------------------------- Validate an accesskey
 1388: 
 1389: sub validate_access_key {
 1390:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1391:     $cdom=
 1392:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1393:     $cnum=
 1394:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1395:     $udom=$env{'user.domain'} unless (defined($udom));
 1396:     $uname=$env{'user.name'} unless (defined($uname));
 1397:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1398:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1399: }
 1400: 
 1401: # ------------------------------------- Find the section of student in a course
 1402: sub devalidate_getsection_cache {
 1403:     my ($udom,$unam,$courseid)=@_;
 1404:     my $hashid="$udom:$unam:$courseid";
 1405:     &devalidate_cache_new('getsection',$hashid);
 1406: }
 1407: 
 1408: sub courseid_to_courseurl {
 1409:     my ($courseid) = @_;
 1410:     #already url style courseid
 1411:     return $courseid if ($courseid =~ m{^/});
 1412: 
 1413:     if (exists($env{'course.'.$courseid.'.num'})) {
 1414: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1415: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1416: 	return "/$cdom/$cnum";
 1417:     }
 1418: 
 1419:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1420:     if (exists($courseinfo{'num'})) {
 1421: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1422:     }
 1423: 
 1424:     return undef;
 1425: }
 1426: 
 1427: sub getsection {
 1428:     my ($udom,$unam,$courseid)=@_;
 1429:     my $cachetime=1800;
 1430: 
 1431:     my $hashid="$udom:$unam:$courseid";
 1432:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1433:     if (defined($cached)) { return $result; }
 1434: 
 1435:     my %Pending; 
 1436:     my %Expired;
 1437:     #
 1438:     # Each role can either have not started yet (pending), be active, 
 1439:     #    or have expired.
 1440:     #
 1441:     # If there is an active role, we are done.
 1442:     #
 1443:     # If there is more than one role which has not started yet, 
 1444:     #     choose the one which will start sooner
 1445:     # If there is one role which has not started yet, return it.
 1446:     #
 1447:     # If there is more than one expired role, choose the one which ended last.
 1448:     # If there is a role which has expired, return it.
 1449:     #
 1450:     $courseid = &courseid_to_courseurl($courseid);
 1451:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1452:     foreach my $key (keys(%roleshash)) {
 1453:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1454:         my $section=$1;
 1455:         if ($key eq $courseid.'_st') { $section=''; }
 1456:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1457:         my $now=time;
 1458:         if (defined($end) && $end && ($now > $end)) {
 1459:             $Expired{$end}=$section;
 1460:             next;
 1461:         }
 1462:         if (defined($start) && $start && ($now < $start)) {
 1463:             $Pending{$start}=$section;
 1464:             next;
 1465:         }
 1466:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1467:     }
 1468:     #
 1469:     # Presumedly there will be few matching roles from the above
 1470:     # loop and the sorting time will be negligible.
 1471:     if (scalar(keys(%Pending))) {
 1472:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1473:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1474:     } 
 1475:     if (scalar(keys(%Expired))) {
 1476:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1477:         my $time = pop(@sorted);
 1478:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1479:     }
 1480:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1481: }
 1482: 
 1483: sub save_cache {
 1484:     &purge_remembered();
 1485:     #&Apache::loncommon::validate_page();
 1486:     undef(%env);
 1487:     undef($env_loaded);
 1488: }
 1489: 
 1490: my $to_remember=-1;
 1491: my %remembered;
 1492: my %accessed;
 1493: my $kicks=0;
 1494: my $hits=0;
 1495: sub make_key {
 1496:     my ($name,$id) = @_;
 1497:     if (length($id) > 65 
 1498: 	&& length(&escape($id)) > 200) {
 1499: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1500:     }
 1501:     return &escape($name.':'.$id);
 1502: }
 1503: 
 1504: sub devalidate_cache_new {
 1505:     my ($name,$id,$debug) = @_;
 1506:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1507:     $id=&make_key($name,$id);
 1508:     $memcache->delete($id);
 1509:     delete($remembered{$id});
 1510:     delete($accessed{$id});
 1511: }
 1512: 
 1513: sub is_cached_new {
 1514:     my ($name,$id,$debug) = @_;
 1515:     $id=&make_key($name,$id);
 1516:     if (exists($remembered{$id})) {
 1517: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1518: 	$accessed{$id}=[&gettimeofday()];
 1519: 	$hits++;
 1520: 	return ($remembered{$id},1);
 1521:     }
 1522:     my $value = $memcache->get($id);
 1523:     if (!(defined($value))) {
 1524: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1525: 	return (undef,undef);
 1526:     }
 1527:     if ($value eq '__undef__') {
 1528: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1529: 	$value=undef;
 1530:     }
 1531:     &make_room($id,$value,$debug);
 1532:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1533:     return ($value,1);
 1534: }
 1535: 
 1536: sub do_cache_new {
 1537:     my ($name,$id,$value,$time,$debug) = @_;
 1538:     $id=&make_key($name,$id);
 1539:     my $setvalue=$value;
 1540:     if (!defined($setvalue)) {
 1541: 	$setvalue='__undef__';
 1542:     }
 1543:     if (!defined($time) ) {
 1544: 	$time=600;
 1545:     }
 1546:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1547:     my $result = $memcache->set($id,$setvalue,$time);
 1548:     if (! $result) {
 1549: 	&logthis("caching of id -> $id  failed");
 1550: 	$memcache->disconnect_all();
 1551:     }
 1552:     # need to make a copy of $value
 1553:     &make_room($id,$value,$debug);
 1554:     return $value;
 1555: }
 1556: 
 1557: sub make_room {
 1558:     my ($id,$value,$debug)=@_;
 1559: 
 1560:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1561:                                     : $value;
 1562:     if ($to_remember<0) { return; }
 1563:     $accessed{$id}=[&gettimeofday()];
 1564:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1565:     my $to_kick;
 1566:     my $max_time=0;
 1567:     foreach my $other (keys(%accessed)) {
 1568: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1569: 	    $to_kick=$other;
 1570: 	    $max_time=&tv_interval($accessed{$other});
 1571: 	}
 1572:     }
 1573:     delete($remembered{$to_kick});
 1574:     delete($accessed{$to_kick});
 1575:     $kicks++;
 1576:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1577:     return;
 1578: }
 1579: 
 1580: sub purge_remembered {
 1581:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1582:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1583:     undef(%remembered);
 1584:     undef(%accessed);
 1585: }
 1586: # ------------------------------------- Read an entry from a user's environment
 1587: 
 1588: sub userenvironment {
 1589:     my ($udom,$unam,@what)=@_;
 1590:     my $items;
 1591:     foreach my $item (@what) {
 1592:         $items.=&escape($item).'&';
 1593:     }
 1594:     $items=~s/\&$//;
 1595:     my %returnhash=();
 1596:     my @answer=split(/\&/,
 1597:                 &reply('get:'.$udom.':'.$unam.':environment:'.$items,
 1598:                       &homeserver($unam,$udom)));
 1599:     my $i;
 1600:     for ($i=0;$i<=$#what;$i++) {
 1601: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1602:     }
 1603:     return %returnhash;
 1604: }
 1605: 
 1606: # ---------------------------------------------------------- Get a studentphoto
 1607: sub studentphoto {
 1608:     my ($udom,$unam,$ext) = @_;
 1609:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1610:     if (defined($env{'request.course.id'})) {
 1611:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1612:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1613:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1614:             } else {
 1615:                 my ($result,$perm_reqd)=
 1616: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1617:                 if ($result eq 'ok') {
 1618:                     if (!($perm_reqd eq 'yes')) {
 1619:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1620:                     }
 1621:                 }
 1622:             }
 1623:         }
 1624:     } else {
 1625:         my ($result,$perm_reqd) = 
 1626: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1627:         if ($result eq 'ok') {
 1628:             if (!($perm_reqd eq 'yes')) {
 1629:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1630:             }
 1631:         }
 1632:     }
 1633:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1634: }
 1635: 
 1636: sub retrievestudentphoto {
 1637:     my ($udom,$unam,$ext,$type) = @_;
 1638:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1639:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1640:     if ($ret eq 'ok') {
 1641:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1642:         if ($type eq 'thumbnail') {
 1643:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1644:         }
 1645:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1646:         return $tokenurl;
 1647:     } else {
 1648:         if ($type eq 'thumbnail') {
 1649:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1650:         } else { 
 1651:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1652:         }
 1653:     }
 1654: }
 1655: 
 1656: # -------------------------------------------------------------------- New chat
 1657: 
 1658: sub chatsend {
 1659:     my ($newentry,$anon,$group)=@_;
 1660:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1661:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1662:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1663:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1664: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1665: 		   &escape($newentry)).':'.$group,$chome);
 1666: }
 1667: 
 1668: # ------------------------------------------ Find current version of a resource
 1669: 
 1670: sub getversion {
 1671:     my $fname=&clutter(shift);
 1672:     unless ($fname=~/^\/res\//) { return -1; }
 1673:     return &currentversion(&filelocation('',$fname));
 1674: }
 1675: 
 1676: sub currentversion {
 1677:     my $fname=shift;
 1678:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1679:     if (defined($cached)) { return $result; }
 1680:     my $author=$fname;
 1681:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1682:     my ($udom,$uname)=split(/\//,$author);
 1683:     my $home=homeserver($uname,$udom);
 1684:     if ($home eq 'no_host') { 
 1685:         return -1; 
 1686:     }
 1687:     my $answer=reply("currentversion:$fname",$home);
 1688:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1689: 	return -1;
 1690:     }
 1691:     return &do_cache_new('resversion',$fname,$answer,600);
 1692: }
 1693: 
 1694: # ----------------------------- Subscribe to a resource, return URL if possible
 1695: 
 1696: sub subscribe {
 1697:     my $fname=shift;
 1698:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1699:     $fname=~s/[\n\r]//g;
 1700:     my $author=$fname;
 1701:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1702:     my ($udom,$uname)=split(/\//,$author);
 1703:     my $home=homeserver($uname,$udom);
 1704:     if ($home eq 'no_host') {
 1705:         return 'not_found';
 1706:     }
 1707:     my $answer=reply("sub:$fname",$home);
 1708:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1709: 	$answer.=' by '.$home;
 1710:     }
 1711:     return $answer;
 1712: }
 1713:     
 1714: # -------------------------------------------------------------- Replicate file
 1715: 
 1716: sub repcopy {
 1717:     my $filename=shift;
 1718:     $filename=~s/\/+/\//g;
 1719:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1720:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1721:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1722: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1723: 	return &repcopy_userfile($filename);
 1724:     }
 1725:     $filename=~s/[\n\r]//g;
 1726:     my $transname="$filename.in.transfer";
 1727: # FIXME: this should flock
 1728:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1729:     my $remoteurl=subscribe($filename);
 1730:     if ($remoteurl =~ /^con_lost by/) {
 1731: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1732:            return 'unavailable';
 1733:     } elsif ($remoteurl eq 'not_found') {
 1734: 	   #&logthis("Subscribe returned not_found: $filename");
 1735: 	   return 'not_found';
 1736:     } elsif ($remoteurl =~ /^rejected by/) {
 1737: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1738:            return 'forbidden';
 1739:     } elsif ($remoteurl eq 'directory') {
 1740:            return 'ok';
 1741:     } else {
 1742:         my $author=$filename;
 1743:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1744:         my ($udom,$uname)=split(/\//,$author);
 1745:         my $home=homeserver($uname,$udom);
 1746:         unless ($home eq $perlvar{'lonHostID'}) {
 1747:            my @parts=split(/\//,$filename);
 1748:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1749:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1750:                &logthis("Malconfiguration for replication: $filename");
 1751: 	       return 'bad_request';
 1752:            }
 1753:            my $count;
 1754:            for ($count=5;$count<$#parts;$count++) {
 1755:                $path.="/$parts[$count]";
 1756:                if ((-e $path)!=1) {
 1757: 		   mkdir($path,0777);
 1758:                }
 1759:            }
 1760:            my $ua=new LWP::UserAgent;
 1761:            my $request=new HTTP::Request('GET',"$remoteurl");
 1762:            my $response=$ua->request($request,$transname);
 1763:            if ($response->is_error()) {
 1764: 	       unlink($transname);
 1765:                my $message=$response->status_line;
 1766:                &logthis("<font color=\"blue\">WARNING:"
 1767:                        ." LWP get: $message: $filename</font>");
 1768:                return 'unavailable';
 1769:            } else {
 1770: 	       if ($remoteurl!~/\.meta$/) {
 1771:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1772:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1773:                   if ($mresponse->is_error()) {
 1774: 		      unlink($filename.'.meta');
 1775:                       &logthis(
 1776:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1777:                   }
 1778: 	       }
 1779:                rename($transname,$filename);
 1780:                return 'ok';
 1781:            }
 1782:        }
 1783:     }
 1784: }
 1785: 
 1786: # ------------------------------------------------ Get server side include body
 1787: sub ssi_body {
 1788:     my ($filelink,%form)=@_;
 1789:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1790:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1791:     }
 1792:     my $output='';
 1793:     my $response;
 1794:     if ($filelink=~/^http\:/) {
 1795:        ($output,$response)=&externalssi($filelink);
 1796:     } else {
 1797:        ($output,$response)=&ssi($filelink,%form);
 1798:     }
 1799:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1800:     $output=~s/^.*?\<body[^\>]*\>//si;
 1801:     $output=~s/\<\/body\s*\>.*?$//si;
 1802:     if (wantarray) {
 1803:         return ($output, $response);
 1804:     } else {
 1805:         return $output;
 1806:     }
 1807: }
 1808: 
 1809: # --------------------------------------------------------- Server Side Include
 1810: 
 1811: sub absolute_url {
 1812:     my ($host_name) = @_;
 1813:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1814:     if ($host_name eq '') {
 1815: 	$host_name = $ENV{'SERVER_NAME'};
 1816:     }
 1817:     return $protocol.$host_name;
 1818: }
 1819: 
 1820: #
 1821: #   Server side include.
 1822: # Parameters:
 1823: #  fn     Possibly encrypted resource name/id.
 1824: #  form   Hash that describes how the rendering should be done
 1825: #         and other things.
 1826: # Returns:
 1827: #   Scalar context: The content of the response.
 1828: #   Array context:  2 element list of the content and the full response object.
 1829: #     
 1830: sub ssi {
 1831: 
 1832:     my ($fn,%form)=@_;
 1833:     my $ua=new LWP::UserAgent;
 1834:     my $request;
 1835: 
 1836:     $form{'no_update_last_known'}=1;
 1837:     &Apache::lonenc::check_encrypt(\$fn);
 1838:     if (%form) {
 1839:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1840:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1841:     } else {
 1842:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1843:     }
 1844: 
 1845:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1846:     my $response=$ua->request($request);
 1847: 
 1848:     if (wantarray) {
 1849: 	return ($response->content, $response);
 1850:     } else {
 1851: 	return $response->content;
 1852:     }
 1853: }
 1854: 
 1855: sub externalssi {
 1856:     my ($url)=@_;
 1857:     my $ua=new LWP::UserAgent;
 1858:     my $request=new HTTP::Request('GET',$url);
 1859:     my $response=$ua->request($request);
 1860:     if (wantarray) {
 1861:         return ($response->content, $response);
 1862:     } else {
 1863:         return $response->content;
 1864:     }
 1865: }
 1866: 
 1867: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1868: 
 1869: sub allowuploaded {
 1870:     my ($srcurl,$url)=@_;
 1871:     $url=&clutter(&declutter($url));
 1872:     my $dir=$url;
 1873:     $dir=~s/\/[^\/]+$//;
 1874:     my %httpref=();
 1875:     my $httpurl=&hreflocation('',$url);
 1876:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1877:     &Apache::lonnet::appenv(\%httpref);
 1878: }
 1879: 
 1880: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1881: # input: action, courseID, current domain, intended
 1882: #        path to file, source of file, instruction to parse file for objects,
 1883: #        ref to hash for embedded objects,
 1884: #        ref to hash for codebase of java objects.
 1885: #
 1886: # output: url to file (if action was uploaddoc), 
 1887: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1888: #
 1889: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1890: # course.
 1891: #
 1892: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1893: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1894: #          course's home server.
 1895: #
 1896: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1897: #          be copied from $source (current location) to 
 1898: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1899: #         and will then be copied to
 1900: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1901: #         course's home server.
 1902: #
 1903: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1904: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1905: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1906: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1907: #         in course's home server.
 1908: #
 1909: 
 1910: sub process_coursefile {
 1911:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1912:     my $fetchresult;
 1913:     my $home=&homeserver($docuname,$docudom);
 1914:     if ($action eq 'propagate') {
 1915:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1916: 			     $home);
 1917:     } else {
 1918:         my $fpath = '';
 1919:         my $fname = $file;
 1920:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1921:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1922:         my $filepath = &build_filepath($fpath);
 1923:         if ($action eq 'copy') {
 1924:             if ($source eq '') {
 1925:                 $fetchresult = 'no source file';
 1926:                 return $fetchresult;
 1927:             } else {
 1928:                 my $destination = $filepath.'/'.$fname;
 1929:                 rename($source,$destination);
 1930:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1931:                                  $home);
 1932:             }
 1933:         } elsif ($action eq 'uploaddoc') {
 1934:             open(my $fh,'>'.$filepath.'/'.$fname);
 1935:             print $fh $env{'form.'.$source};
 1936:             close($fh);
 1937:             if ($parser eq 'parse') {
 1938:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 1939:                 unless ($parse_result eq 'ok') {
 1940:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1941:                 }
 1942:             }
 1943:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1944:                                  $home);
 1945:             if ($fetchresult eq 'ok') {
 1946:                 return '/uploaded/'.$fpath.'/'.$fname;
 1947:             } else {
 1948:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1949:                         ' to host '.$home.': '.$fetchresult);
 1950:                 return '/adm/notfound.html';
 1951:             }
 1952:         }
 1953:     }
 1954:     unless ( $fetchresult eq 'ok') {
 1955:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1956:              ' to host '.$home.': '.$fetchresult);
 1957:     }
 1958:     return $fetchresult;
 1959: }
 1960: 
 1961: sub build_filepath {
 1962:     my ($fpath) = @_;
 1963:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1964:     unless ($fpath eq '') {
 1965:         my @parts=split('/',$fpath);
 1966:         foreach my $part (@parts) {
 1967:             $filepath.= '/'.$part;
 1968:             if ((-e $filepath)!=1) {
 1969:                 mkdir($filepath,0777);
 1970:             }
 1971:         }
 1972:     }
 1973:     return $filepath;
 1974: }
 1975: 
 1976: sub store_edited_file {
 1977:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1978:     my $file = $primary_url;
 1979:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1980:     my $fpath = '';
 1981:     my $fname = $file;
 1982:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1983:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1984:     my $filepath = &build_filepath($fpath);
 1985:     open(my $fh,'>'.$filepath.'/'.$fname);
 1986:     print $fh $content;
 1987:     close($fh);
 1988:     my $home=&homeserver($docuname,$docudom);
 1989:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1990: 			  $home);
 1991:     if ($$fetchresult eq 'ok') {
 1992:         return '/uploaded/'.$fpath.'/'.$fname;
 1993:     } else {
 1994:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1995: 		 ' to host '.$home.': '.$$fetchresult);
 1996:         return '/adm/notfound.html';
 1997:     }
 1998: }
 1999: 
 2000: sub clean_filename {
 2001:     my ($fname,$args)=@_;
 2002: # Replace Windows backslashes by forward slashes
 2003:     $fname=~s/\\/\//g;
 2004:     if (!$args->{'keep_path'}) {
 2005:         # Get rid of everything but the actual filename
 2006: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2007:     }
 2008: # Replace spaces by underscores
 2009:     $fname=~s/\s+/\_/g;
 2010: # Replace all other weird characters by nothing
 2011:     $fname=~s{[^/\w\.\-]}{}g;
 2012: # Replace all .\d. sequences with _\d. so they no longer look like version
 2013: # numbers
 2014:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2015:     return $fname;
 2016: }
 2017: 
 2018: #Wrapper function for userphotoupload
 2019: sub userphotoupload
 2020: {
 2021: 	my($formname,$subdir) = @_;
 2022: 	$upload_photo_form = 1;
 2023: 	return &userfileupload($formname,undef,$subdir);
 2024: }
 2025: 
 2026: # --------------- Take an uploaded file and put it into the userfiles directory
 2027: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2028: #                    the desired filenam is in $env{"form.$formname.filename"}
 2029: #        $coursedoc - if true up to the current course
 2030: #                     if false
 2031: #        $subdir - directory in userfile to store the file into
 2032: #        $parser - instruction to parse file for objects ($parser = parse)    
 2033: #        $allfiles - reference to hash for embedded objects
 2034: #        $codebase - reference to hash for codebase of java objects
 2035: #        $desuname - username for permanent storage of uploaded file
 2036: #        $dsetudom - domain for permanaent storage of uploaded file
 2037: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2038: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2039: # 
 2040: # output: url of file in userspace, or error: <message> 
 2041: #             or /adm/notfound.html if failure to upload occurse
 2042: 
 2043: 
 2044: sub userfileupload {
 2045:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 2046:         $destudom,$thumbwidth,$thumbheight)=@_;
 2047:     if (!defined($subdir)) { $subdir='unknown'; }
 2048:     my $fname=$env{'form.'.$formname.'.filename'};
 2049:     $fname=&clean_filename($fname);
 2050: # See if there is anything left
 2051:     unless ($fname) { return 'error: no uploaded file'; }
 2052:     chop($env{'form.'.$formname});
 2053:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 2054:         my $now = time;
 2055:         my $filepath = 'tmp/helprequests/'.$now;
 2056:         my @parts=split(/\//,$filepath);
 2057:         my $fullpath = $perlvar{'lonDaemons'};
 2058:         for (my $i=0;$i<@parts;$i++) {
 2059:             $fullpath .= '/'.$parts[$i];
 2060:             if ((-e $fullpath)!=1) {
 2061:                 mkdir($fullpath,0777);
 2062:             }
 2063:         }
 2064:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2065:         print $fh $env{'form.'.$formname};
 2066:         close($fh);
 2067:         return $fullpath.'/'.$fname;
 2068:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 2069:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2070:                        '_'.$env{'user.domain'}.'/pending';
 2071:         my @parts=split(/\//,$filepath);
 2072:         my $fullpath = $perlvar{'lonDaemons'};
 2073:         for (my $i=0;$i<@parts;$i++) {
 2074:             $fullpath .= '/'.$parts[$i];
 2075:             if ((-e $fullpath)!=1) {
 2076:                 mkdir($fullpath,0777);
 2077:             }
 2078:         }
 2079:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2080:         print $fh $env{'form.'.$formname};
 2081:         close($fh);
 2082:         return $fullpath.'/'.$fname;
 2083:     }
 2084:     
 2085: # Create the directory if not present
 2086:     $fname="$subdir/$fname";
 2087:     if ($coursedoc) {
 2088: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2089: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2090:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2091:             return &finishuserfileupload($docuname,$docudom,
 2092: 					 $formname,$fname,$parser,$allfiles,
 2093: 					 $codebase,$thumbwidth,$thumbheight);
 2094:         } else {
 2095:             $fname=$env{'form.folder'}.'/'.$fname;
 2096:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2097: 				       $fname,$formname,$parser,
 2098: 				       $allfiles,$codebase);
 2099:         }
 2100:     } elsif (defined($destuname)) {
 2101:         my $docuname=$destuname;
 2102:         my $docudom=$destudom;
 2103: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2104: 				     $parser,$allfiles,$codebase,
 2105:                                      $thumbwidth,$thumbheight);
 2106:         
 2107:     } else {
 2108:         my $docuname=$env{'user.name'};
 2109:         my $docudom=$env{'user.domain'};
 2110:         if (exists($env{'form.group'})) {
 2111:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2112:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2113:         }
 2114: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2115: 				     $parser,$allfiles,$codebase,
 2116:                                      $thumbwidth,$thumbheight);
 2117:     }
 2118: }
 2119: 
 2120: sub finishuserfileupload {
 2121:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2122:         $thumbwidth,$thumbheight) = @_;
 2123:     my $path=$docudom.'/'.$docuname.'/';
 2124:     my $filepath=$perlvar{'lonDocRoot'};
 2125:     my ($fnamepath,$file,$fetchthumb);
 2126:     $file=$fname;
 2127:     if ($fname=~m|/|) {
 2128:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2129: 	$path.=$fnamepath.'/';
 2130:     }
 2131:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2132:     my $count;
 2133:     for ($count=4;$count<=$#parts;$count++) {
 2134:         $filepath.="/$parts[$count]";
 2135:         if ((-e $filepath)!=1) {
 2136: 	    mkdir($filepath,0777);
 2137:         }
 2138:     }
 2139: # Save the file
 2140:     {
 2141: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2142: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2143: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2144: 	    return '/adm/notfound.html';
 2145: 	}
 2146: 	if (!print FH ($env{'form.'.$formname})) {
 2147: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2148: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2149: 	    return '/adm/notfound.html';
 2150: 	}
 2151: 	close(FH);
 2152: 	if($upload_photo_form==1)
 2153: 	{
 2154: 		my $ima = Image::Magick->new;                       
 2155:             	$ima->Read($filepath.'/'.$file);
 2156: 		if($ima->Get('width') > 300)
 2157: 		{
 2158: 			my $factor = $ima->Get('width')/300;
 2159:              		$ima->Scale( width=>300, height=>$ima->Get('height')/$factor );
 2160: 		}
 2161: 		if($ima->Get('height') > 400)
 2162:                 {
 2163:                         my $factor = $ima->Get('height')/400;
 2164:                         $ima->Scale( width=>$ima->Get('width')/$factor, height=>400);
 2165:                 }
 2166:  
 2167: 		
 2168: 		$ima->Write($filepath.'/'.$file);
 2169: 		$upload_photo_form = 0;
 2170: 	}
 2171:     }
 2172:     if ($parser eq 'parse') {
 2173:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
 2174: 						   $codebase);
 2175:         unless ($parse_result eq 'ok') {
 2176:             &logthis('Failed to parse '.$filepath.$file.
 2177: 		     ' for embedded media: '.$parse_result); 
 2178:         }
 2179:     }
 2180:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2181:         my $input = $filepath.'/'.$file;
 2182:         my $output = $filepath.'/'.'tn-'.$file;
 2183:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2184:         system("convert -sample $thumbsize $input $output");
 2185:         if (-e $filepath.'/'.'tn-'.$file) {
 2186:             $fetchthumb  = 1; 
 2187:         }
 2188:     }
 2189:  
 2190: # Notify homeserver to grep it
 2191: #
 2192:     my $docuhome=&homeserver($docuname,$docudom);
 2193:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2194:     if ($fetchresult eq 'ok') {
 2195:         if ($fetchthumb) {
 2196:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2197:             if ($thumbresult ne 'ok') {
 2198:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2199:                          $docuhome.': '.$thumbresult);
 2200:             }
 2201:         }
 2202: #
 2203: # Return the URL to it
 2204:         return '/uploaded/'.$path.$file;
 2205:     } else {
 2206:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2207: 		 ': '.$fetchresult);
 2208:         return '/adm/notfound.html';
 2209:     }
 2210: }
 2211: 
 2212: sub extract_embedded_items {
 2213:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 2214:     my @state = ();
 2215:     my %javafiles = (
 2216:                       codebase => '',
 2217:                       code => '',
 2218:                       archive => ''
 2219:                     );
 2220:     my %mediafiles = (
 2221:                       src => '',
 2222:                       movie => '',
 2223:                      );
 2224:     my $p;
 2225:     if ($content) {
 2226:         $p = HTML::LCParser->new($content);
 2227:     } else {
 2228:         $p = HTML::LCParser->new($fullpath);
 2229:     }
 2230:     while (my $t=$p->get_token()) {
 2231: 	if ($t->[0] eq 'S') {
 2232: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2233: 	    push(@state, $tagname);
 2234:             if (lc($tagname) eq 'allow') {
 2235:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2236:             }
 2237: 	    if (lc($tagname) eq 'img') {
 2238: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2239: 	    }
 2240: 	    if (lc($tagname) eq 'a') {
 2241: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2242: 	    }
 2243:             if (lc($tagname) eq 'script') {
 2244:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2245:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2246:                 } else {
 2247:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2248:                 }
 2249:             }
 2250:             if (lc($tagname) eq 'link') {
 2251:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2252:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2253:                 }
 2254:             }
 2255: 	    if (lc($tagname) eq 'object' ||
 2256: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2257: 		foreach my $item (keys(%javafiles)) {
 2258: 		    $javafiles{$item} = '';
 2259: 		}
 2260: 	    }
 2261: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2262: 		my $name = lc($attr->{'name'});
 2263: 		foreach my $item (keys(%javafiles)) {
 2264: 		    if ($name eq $item) {
 2265: 			$javafiles{$item} = $attr->{'value'};
 2266: 			last;
 2267: 		    }
 2268: 		}
 2269: 		foreach my $item (keys(%mediafiles)) {
 2270: 		    if ($name eq $item) {
 2271: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2272: 			last;
 2273: 		    }
 2274: 		}
 2275: 	    }
 2276: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2277: 		foreach my $item (keys(%javafiles)) {
 2278: 		    if ($attr->{$item}) {
 2279: 			$javafiles{$item} = $attr->{$item};
 2280: 			last;
 2281: 		    }
 2282: 		}
 2283: 		foreach my $item (keys(%mediafiles)) {
 2284: 		    if ($attr->{$item}) {
 2285: 			&add_filetype($allfiles,$attr->{$item},$item);
 2286: 			last;
 2287: 		    }
 2288: 		}
 2289: 	    }
 2290: 	} elsif ($t->[0] eq 'E') {
 2291: 	    my ($tagname) = ($t->[1]);
 2292: 	    if ($javafiles{'codebase'} ne '') {
 2293: 		$javafiles{'codebase'} .= '/';
 2294: 	    }  
 2295: 	    if (lc($tagname) eq 'applet' ||
 2296: 		lc($tagname) eq 'object' ||
 2297: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2298: 		) {
 2299: 		foreach my $item (keys(%javafiles)) {
 2300: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2301: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2302: 			&add_filetype($allfiles,$file,$item);
 2303: 		    }
 2304: 		}
 2305: 	    } 
 2306: 	    pop @state;
 2307: 	}
 2308:     }
 2309:     return 'ok';
 2310: }
 2311: 
 2312: sub add_filetype {
 2313:     my ($allfiles,$file,$type)=@_;
 2314:     if (exists($allfiles->{$file})) {
 2315: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2316: 	    push(@{$allfiles->{$file}}, &escape($type));
 2317: 	}
 2318:     } else {
 2319: 	@{$allfiles->{$file}} = (&escape($type));
 2320:     }
 2321: }
 2322: 
 2323: sub removeuploadedurl {
 2324:     my ($url)=@_;
 2325:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 2326:     return &removeuserfile($uname,$udom,$fname);
 2327: }
 2328: 
 2329: sub removeuserfile {
 2330:     my ($docuname,$docudom,$fname)=@_;
 2331:     my $home=&homeserver($docuname,$docudom);
 2332:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2333:     if ($result eq 'ok') {
 2334:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2335:             my $metafile = $fname.'.meta';
 2336:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2337: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2338:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2339:             my $sqlresult = 
 2340:                 &update_portfolio_table($docuname,$docudom,$file,
 2341:                                         'portfolio_metadata',$group,
 2342:                                         'delete');
 2343:         }
 2344:     }
 2345:     return $result;
 2346: }
 2347: 
 2348: sub mkdiruserfile {
 2349:     my ($docuname,$docudom,$dir)=@_;
 2350:     my $home=&homeserver($docuname,$docudom);
 2351:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2352: }
 2353: 
 2354: sub renameuserfile {
 2355:     my ($docuname,$docudom,$old,$new)=@_;
 2356:     my $home=&homeserver($docuname,$docudom);
 2357:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2358:                         &escape("$old").':'.&escape("$new"),$home);
 2359:     if ($result eq 'ok') {
 2360:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2361:             my $oldmeta = $old.'.meta';
 2362:             my $newmeta = $new.'.meta';
 2363:             my $metaresult = 
 2364:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2365: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2366:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2367:             my $sqlresult = 
 2368:                 &update_portfolio_table($docuname,$docudom,$file,
 2369:                                         'portfolio_metadata',$group,
 2370:                                         'delete');
 2371:         }
 2372:     }
 2373:     return $result;
 2374: }
 2375: 
 2376: # ------------------------------------------------------------------------- Log
 2377: 
 2378: sub log {
 2379:     my ($dom,$nam,$hom,$what)=@_;
 2380:     return critical("log:$dom:$nam:$what",$hom);
 2381: }
 2382: 
 2383: # ------------------------------------------------------------------ Course Log
 2384: #
 2385: # This routine flushes several buffers of non-mission-critical nature
 2386: #
 2387: 
 2388: sub flushcourselogs {
 2389:     &logthis('Flushing log buffers');
 2390: #
 2391: # course logs
 2392: # This is a log of all transactions in a course, which can be used
 2393: # for data mining purposes
 2394: #
 2395: # It also collects the courseid database, which lists last transaction
 2396: # times and course titles for all courseids
 2397: #
 2398:     my %courseidbuffer=();
 2399:     foreach my $crsid (keys(%courselogs)) {
 2400:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2401: 		          &escape($courselogs{$crsid}),
 2402: 		          $coursehombuf{$crsid}) eq 'ok') {
 2403: 	    delete $courselogs{$crsid};
 2404:         } else {
 2405:             &logthis('Failed to flush log buffer for '.$crsid);
 2406:             if (length($courselogs{$crsid})>40000) {
 2407:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2408:                         " exceeded maximum size, deleting.</font>");
 2409:                delete $courselogs{$crsid};
 2410:             }
 2411:         }
 2412:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2413:             'description' => $coursedescrbuf{$crsid},
 2414:             'inst_code'    => $courseinstcodebuf{$crsid},
 2415:             'type'        => $coursetypebuf{$crsid},
 2416:             'owner'       => $courseownerbuf{$crsid},
 2417:         };
 2418:     }
 2419: #
 2420: # Write course id database (reverse lookup) to homeserver of courses 
 2421: # Is used in pickcourse
 2422: #
 2423:     foreach my $crs_home (keys(%courseidbuffer)) {
 2424:         my $response = &courseidput(&host_domain($crs_home),
 2425:                                     $courseidbuffer{$crs_home},
 2426:                                     $crs_home,'timeonly');
 2427:     }
 2428: #
 2429: # File accesses
 2430: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2431: #
 2432:     foreach my $entry (keys(%accesshash)) {
 2433:         if ($entry =~ /___count$/) {
 2434:             my ($dom,$name);
 2435:             ($dom,$name,undef)=
 2436: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2437:             if (! defined($dom) || $dom eq '' || 
 2438:                 ! defined($name) || $name eq '') {
 2439:                 my $cid = $env{'request.course.id'};
 2440:                 $dom  = $env{'request.'.$cid.'.domain'};
 2441:                 $name = $env{'request.'.$cid.'.num'};
 2442:             }
 2443:             my $value = $accesshash{$entry};
 2444:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2445:             my %temphash=($url => $value);
 2446:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2447:             if ($result eq 'ok') {
 2448:                 delete $accesshash{$entry};
 2449:             } elsif ($result eq 'unknown_cmd') {
 2450:                 # Target server has old code running on it.
 2451:                 my %temphash=($entry => $value);
 2452:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2453:                     delete $accesshash{$entry};
 2454:                 }
 2455:             }
 2456:         } else {
 2457:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2458:             my %temphash=($entry => $accesshash{$entry});
 2459:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2460:                 delete $accesshash{$entry};
 2461:             }
 2462:         }
 2463:     }
 2464: #
 2465: # Roles
 2466: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2467: #
 2468:     foreach my $entry (keys(%userrolehash)) {
 2469:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2470: 	    split(/\:/,$entry);
 2471:         if (&Apache::lonnet::put('nohist_userroles',
 2472:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2473:                 $rudom,$runame) eq 'ok') {
 2474: 	    delete $userrolehash{$entry};
 2475:         }
 2476:     }
 2477: #
 2478: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2479: #
 2480:     my %domrolebuffer = ();
 2481:     foreach my $entry (keys %domainrolehash) {
 2482:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2483:         if ($domrolebuffer{$rudom}) {
 2484:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2485:                       '='.&escape($domainrolehash{$entry});
 2486:         } else {
 2487:             $domrolebuffer{$rudom}.=&escape($entry).
 2488:                       '='.&escape($domainrolehash{$entry});
 2489:         }
 2490:         delete $domainrolehash{$entry};
 2491:     }
 2492:     foreach my $dom (keys(%domrolebuffer)) {
 2493: 	my %servers = &get_servers($dom,'library');
 2494: 	foreach my $tryserver (keys(%servers)) {
 2495: 	    unless (&reply('domroleput:'.$dom.':'.
 2496: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2497: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2498: 	    }
 2499:         }
 2500:     }
 2501:     $dumpcount++;
 2502: }
 2503: 
 2504: sub courselog {
 2505:     my $what=shift;
 2506:     $what=time.':'.$what;
 2507:     unless ($env{'request.course.id'}) { return ''; }
 2508:     $coursedombuf{$env{'request.course.id'}}=
 2509:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2510:     $coursenumbuf{$env{'request.course.id'}}=
 2511:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2512:     $coursehombuf{$env{'request.course.id'}}=
 2513:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2514:     $coursedescrbuf{$env{'request.course.id'}}=
 2515:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2516:     $courseinstcodebuf{$env{'request.course.id'}}=
 2517:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2518:     $courseownerbuf{$env{'request.course.id'}}=
 2519:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2520:     $coursetypebuf{$env{'request.course.id'}}=
 2521:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2522:     if (defined $courselogs{$env{'request.course.id'}}) {
 2523: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2524:     } else {
 2525: 	$courselogs{$env{'request.course.id'}}.=$what;
 2526:     }
 2527:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2528: 	&flushcourselogs();
 2529:     }
 2530: }
 2531: 
 2532: sub courseacclog {
 2533:     my $fnsymb=shift;
 2534:     unless ($env{'request.course.id'}) { return ''; }
 2535:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2536:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2537:         $what.=':POST';
 2538:         # FIXME: Probably ought to escape things....
 2539: 	foreach my $key (keys(%env)) {
 2540:             if ($key=~/^form\.(.*)/) {
 2541:                 my $formitem = $1;
 2542:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 2543:                     $what.=':'.$formitem.'='.$env{$key};
 2544:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 2545:                     $what.=':'.$formitem.'='.$env{$key};
 2546:                 }
 2547:             }
 2548:         }
 2549:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2550:         # FIXME: We should not be depending on a form parameter that someone
 2551:         # editing lonsearchcat.pm might change in the future.
 2552:         if ($env{'form.phase'} eq 'course_search') {
 2553:             $what.= ':POST';
 2554:             # FIXME: Probably ought to escape things....
 2555:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2556:                                  'crsdiscuss') {
 2557:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2558:             }
 2559:         }
 2560:     }
 2561:     &courselog($what);
 2562: }
 2563: 
 2564: sub countacc {
 2565:     my $url=&declutter(shift);
 2566:     return if (! defined($url) || $url eq '');
 2567:     unless ($env{'request.course.id'}) { return ''; }
 2568:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2569:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2570:     $accesshash{$key}++;
 2571: }
 2572: 
 2573: sub linklog {
 2574:     my ($from,$to)=@_;
 2575:     $from=&declutter($from);
 2576:     $to=&declutter($to);
 2577:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2578:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2579: }
 2580:   
 2581: sub userrolelog {
 2582:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2583:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2584:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2585:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2586:         ($trole=~/^ta/)) {
 2587:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2588:        $userrolehash
 2589:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2590:                     =$tend.':'.$tstart;
 2591:     }
 2592:     if (($env{'request.role'} =~ /dc\./) &&
 2593: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2594: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2595: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
 2596:        $userrolehash
 2597:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2598:                     =$tend.':'.$tstart;
 2599:     }
 2600:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2601:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2602:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2603:         ($trole=~/^sc/)) {
 2604:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2605:        $domainrolehash
 2606:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2607:                     = $tend.':'.$tstart;
 2608:     }
 2609: }
 2610: 
 2611: sub courserolelog {
 2612:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 2613:     if (($trole eq 'cc') || ($trole eq 'in') ||
 2614:         ($trole eq 'ep') || ($trole eq 'ad') ||
 2615:         ($trole eq 'ta') || ($trole eq 'st') ||
 2616:         ($trole=~/^cr/) || ($trole eq 'gr')) {
 2617:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 2618:             my $cdom = $1;
 2619:             my $cnum = $2;
 2620:             my $sec = $3;
 2621:             my $namespace = 'rolelog';
 2622:             my %storehash = (
 2623:                                role    => $trole,
 2624:                                start   => $tstart,
 2625:                                end     => $tend,
 2626:                                selfenroll => $selfenroll,
 2627:                                context    => $context,
 2628:                             );
 2629:             if ($trole eq 'gr') {
 2630:                 $namespace = 'groupslog';
 2631:                 $storehash{'group'} = $sec;
 2632:             } else {
 2633:                 $storehash{'section'} = $sec;
 2634:             }
 2635:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 2636:         }
 2637:     }
 2638:     return;
 2639: }
 2640: 
 2641: sub get_course_adv_roles {
 2642:     my ($cid,$codes) = @_;
 2643:     $cid=$env{'request.course.id'} unless (defined($cid));
 2644:     my %coursehash=&coursedescription($cid);
 2645:     my %nothide=();
 2646:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2647:         if ($user !~ /:/) {
 2648: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2649:         } else {
 2650:             $nothide{$user}=1;
 2651:         }
 2652:     }
 2653:     my %returnhash=();
 2654:     my %dumphash=
 2655:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2656:     my $now=time;
 2657:     foreach my $entry (keys %dumphash) {
 2658: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2659:         if (($tstart) && ($tstart<0)) { next; }
 2660:         if (($tend) && ($tend<$now)) { next; }
 2661:         if (($tstart) && ($now<$tstart)) { next; }
 2662:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2663: 	if ($username eq '' || $domain eq '') { next; }
 2664: 	if ((&privileged($username,$domain)) && 
 2665: 	    (!$nothide{$username.':'.$domain})) { next; }
 2666: 	if ($role eq 'cr') { next; }
 2667:         if ($codes) {
 2668:             if ($section) { $role .= ':'.$section; }
 2669:             if ($returnhash{$role}) {
 2670:                 $returnhash{$role}.=','.$username.':'.$domain;
 2671:             } else {
 2672:                 $returnhash{$role}=$username.':'.$domain;
 2673:             }
 2674:         } else {
 2675:             my $key=&plaintext($role);
 2676:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 2677:             if ($returnhash{$key}) {
 2678: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2679:             } else {
 2680:                 $returnhash{$key}=$username.':'.$domain;
 2681:             }
 2682:         }
 2683:     }
 2684:     return %returnhash;
 2685: }
 2686: 
 2687: sub get_my_roles {
 2688:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2689:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2690:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2691:     my (%dumphash,%nothide);
 2692:     if ($context eq 'userroles') { 
 2693:         %dumphash = &dump('roles',$udom,$uname);
 2694:     } else {
 2695:         %dumphash=
 2696:             &dump('nohist_userroles',$udom,$uname);
 2697:         if ($hidepriv) {
 2698:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2699:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2700:                 if ($user !~ /:/) {
 2701:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2702:                 } else {
 2703:                     $nothide{$user} = 1;
 2704:                 }
 2705:             }
 2706:         }
 2707:     }
 2708:     my %returnhash=();
 2709:     my $now=time;
 2710:     foreach my $entry (keys(%dumphash)) {
 2711:         my ($role,$tend,$tstart);
 2712:         if ($context eq 'userroles') {
 2713: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2714:         } else {
 2715:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2716:         }
 2717:         if (($tstart) && ($tstart<0)) { next; }
 2718:         my $status = 'active';
 2719:         if (($tend) && ($tend<=$now)) {
 2720:             $status = 'previous';
 2721:         } 
 2722:         if (($tstart) && ($now<$tstart)) {
 2723:             $status = 'future';
 2724:         }
 2725:         if (ref($types) eq 'ARRAY') {
 2726:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2727:                 next;
 2728:             } 
 2729:         } else {
 2730:             if ($status ne 'active') {
 2731:                 next;
 2732:             }
 2733:         }
 2734:         my ($rolecode,$username,$domain,$section,$area);
 2735:         if ($context eq 'userroles') {
 2736:             ($area,$rolecode) = split(/_/,$entry);
 2737:             (undef,$domain,$username,$section) = split(/\//,$area);
 2738:         } else {
 2739:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2740:         }
 2741:         if (ref($roledoms) eq 'ARRAY') {
 2742:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2743:                 next;
 2744:             }
 2745:         }
 2746:         if (ref($roles) eq 'ARRAY') {
 2747:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2748:                 if ($role =~ /^cr\//) {
 2749:                     if (!grep(/^cr$/,@{$roles})) {
 2750:                         next;
 2751:                     }
 2752:                 } else {
 2753:                     next;
 2754:                 }
 2755:             }
 2756:         }
 2757:         if ($hidepriv) {
 2758:             if ((&privileged($username,$domain)) &&
 2759:                 (!$nothide{$username.':'.$domain})) { 
 2760:                 next;
 2761:             }
 2762:         }
 2763:         if ($withsec) {
 2764:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2765:                 $tstart.':'.$tend;
 2766:         } else {
 2767:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2768:         }
 2769:     }
 2770:     return %returnhash;
 2771: }
 2772: 
 2773: # ----------------------------------------------------- Frontpage Announcements
 2774: #
 2775: #
 2776: 
 2777: sub postannounce {
 2778:     my ($server,$text)=@_;
 2779:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2780:     unless ($text=~/\w/) { $text=''; }
 2781:     return &reply('setannounce:'.&escape($text),$server);
 2782: }
 2783: 
 2784: sub getannounce {
 2785: 
 2786:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2787: 	my $announcement='';
 2788: 	while (my $line = <$fh>) { $announcement .= $line; }
 2789: 	close($fh);
 2790: 	if ($announcement=~/\w/) { 
 2791: 	    return 
 2792:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2793:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2794: 	} else {
 2795: 	    return '';
 2796: 	}
 2797:     } else {
 2798: 	return '';
 2799:     }
 2800: }
 2801: 
 2802: # ---------------------------------------------------------- Course ID routines
 2803: # Deal with domain's nohist_courseid.db files
 2804: #
 2805: 
 2806: sub courseidput {
 2807:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2808:     my $outcome;
 2809:     if ($caller eq 'timeonly') {
 2810:         my $cids = '';
 2811:         foreach my $item (keys(%$storehash)) {
 2812:             $cids.=&escape($item).'&';
 2813:         }
 2814:         $cids=~s/\&$//;
 2815:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 2816:                           $coursehome);       
 2817:     } else {
 2818:         my $items = '';
 2819:         foreach my $item (keys(%$storehash)) {
 2820:             $items.= &escape($item).'='.
 2821:                      &freeze_escape($$storehash{$item}).'&';
 2822:         }
 2823:         $items=~s/\&$//;
 2824:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 2825:                           $coursehome);
 2826:     }
 2827:     if ($outcome eq 'unknown_cmd') {
 2828:         my $what;
 2829:         foreach my $cid (keys(%$storehash)) {
 2830:             $what .= &escape($cid).'=';
 2831:             foreach my $item ('description','inst_code','owner','type') {
 2832:                 $what .= &escape($storehash->{$cid}{$item}).':';
 2833:             }
 2834:             $what =~ s/\:$/&/;
 2835:         }
 2836:         $what =~ s/\&$//;  
 2837:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2838:     } else {
 2839:         return $outcome;
 2840:     }
 2841: }
 2842: 
 2843: sub courseiddump {
 2844:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 2845:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 2846:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
 2847:     my $as_hash = 1;
 2848:     my %returnhash;
 2849:     if (!$domfilter) { $domfilter=''; }
 2850:     my %libserv = &all_library();
 2851:     foreach my $tryserver (keys(%libserv)) {
 2852:         if ( (  $hostidflag == 1 
 2853: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2854: 	     || (!defined($hostidflag)) ) {
 2855: 
 2856: 	    if (($domfilter eq '') ||
 2857: 		(&host_domain($tryserver) eq $domfilter)) {
 2858:                 my $rep = 
 2859:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 2860:                          $sincefilter.':'.&escape($descfilter).':'.
 2861:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 2862:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 2863:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 2864:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 2865:                          $showhidden.':'.$caller,$tryserver);
 2866:                 my @pairs=split(/\&/,$rep);
 2867:                 foreach my $item (@pairs) {
 2868:                     my ($key,$value)=split(/\=/,$item,2);
 2869:                     $key = &unescape($key);
 2870:                     next if ($key =~ /^error: 2 /);
 2871:                     my $result = &thaw_unescape($value);
 2872:                     if (ref($result) eq 'HASH') {
 2873:                         $returnhash{$key}=$result;
 2874:                     } else {
 2875:                         my @responses = split(/:/,$value);
 2876:                         my @items = ('description','inst_code','owner','type');
 2877:                         for (my $i=0; $i<@responses; $i++) {
 2878:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 2879:                         }
 2880:                     } 
 2881:                 }
 2882:             }
 2883:         }
 2884:     }
 2885:     return %returnhash;
 2886: }
 2887: 
 2888: # ---------------------------------------------------------- DC e-mail
 2889: 
 2890: sub dcmailput {
 2891:     my ($domain,$msgid,$message,$server)=@_;
 2892:     my $status = &Apache::lonnet::critical(
 2893:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2894:        &escape($message),$server);
 2895:     return $status;
 2896: }
 2897: 
 2898: sub dcmaildump {
 2899:     my ($dom,$startdate,$enddate,$senders) = @_;
 2900:     my %returnhash=();
 2901: 
 2902:     if (defined(&domain($dom,'primary'))) {
 2903:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2904:                                                          &escape($enddate).':';
 2905: 	my @esc_senders=map { &escape($_)} @$senders;
 2906: 	$cmd.=&escape(join('&',@esc_senders));
 2907: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2908:             my ($key,$value) = split(/\=/,$line,2);
 2909:             if (($key) && ($value)) {
 2910:                 $returnhash{&unescape($key)} = &unescape($value);
 2911:             }
 2912:         }
 2913:     }
 2914:     return %returnhash;
 2915: }
 2916: # ---------------------------------------------------------- Domain roles
 2917: 
 2918: sub get_domain_roles {
 2919:     my ($dom,$roles,$startdate,$enddate)=@_;
 2920:     if (undef($startdate) || $startdate eq '') {
 2921:         $startdate = '.';
 2922:     }
 2923:     if (undef($enddate) || $enddate eq '') {
 2924:         $enddate = '.';
 2925:     }
 2926:     my $rolelist;
 2927:     if (ref($roles) eq 'ARRAY') {
 2928:         $rolelist = join(':',@{$roles});
 2929:     }
 2930:     my %personnel = ();
 2931: 
 2932:     my %servers = &get_servers($dom,'library');
 2933:     foreach my $tryserver (keys(%servers)) {
 2934: 	%{$personnel{$tryserver}}=();
 2935: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2936: 					    &escape($startdate).':'.
 2937: 					    &escape($enddate).':'.
 2938: 					    &escape($rolelist), $tryserver))) {
 2939: 	    my ($key,$value) = split(/\=/,$line,2);
 2940: 	    if (($key) && ($value)) {
 2941: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2942: 	    }
 2943: 	}
 2944:     }
 2945:     return %personnel;
 2946: }
 2947: 
 2948: # ----------------------------------------------------------- Check out an item
 2949: 
 2950: sub get_first_access {
 2951:     my ($type,$argsymb)=@_;
 2952:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2953:     if ($argsymb) { $symb=$argsymb; }
 2954:     my ($map,$id,$res)=&decode_symb($symb);
 2955:     if ($type eq 'course') {
 2956: 	$res='course';
 2957:     } elsif ($type eq 'map') {
 2958: 	$res=&symbread($map);
 2959:     } else {
 2960: 	$res=$symb;
 2961:     }
 2962:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2963:     return $times{"$courseid\0$res"};
 2964: }
 2965: 
 2966: sub set_first_access {
 2967:     my ($type)=@_;
 2968:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2969:     my ($map,$id,$res)=&decode_symb($symb);
 2970:     if ($type eq 'course') {
 2971: 	$res='course';
 2972:     } elsif ($type eq 'map') {
 2973: 	$res=&symbread($map);
 2974:     } else {
 2975: 	$res=$symb;
 2976:     }
 2977:     my $firstaccess=&get_first_access($type,$symb);
 2978:     if (!$firstaccess) {
 2979: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2980:     }
 2981:     return 'already_set';
 2982: }
 2983: 
 2984: sub checkout {
 2985:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2986:     my $now=time;
 2987:     my $lonhost=$perlvar{'lonHostID'};
 2988:     my $infostr=&escape(
 2989:                  'CHECKOUTTOKEN&'.
 2990:                  $tuname.'&'.
 2991:                  $tudom.'&'.
 2992:                  $tcrsid.'&'.
 2993:                  $symb.'&'.
 2994: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2995:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2996:     if ($token=~/^error\:/) { 
 2997:         &logthis("<font color=\"blue\">WARNING: ".
 2998:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2999:                  "</font>");
 3000:         return ''; 
 3001:     }
 3002: 
 3003:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 3004:     $token=~tr/a-z/A-Z/;
 3005: 
 3006:     my %infohash=('resource.0.outtoken' => $token,
 3007:                   'resource.0.checkouttime' => $now,
 3008:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 3009: 
 3010:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3011:        return '';
 3012:     } else {
 3013:         &logthis("<font color=\"blue\">WARNING: ".
 3014:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 3015:                  "</font>");
 3016:     }    
 3017: 
 3018:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3019:                          &escape('Checkout '.$infostr.' - '.
 3020:                                                  $token)) ne 'ok') {
 3021: 	return '';
 3022:     } else {
 3023:         &logthis("<font color=\"blue\">WARNING: ".
 3024:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 3025:                  "</font>");
 3026:     }
 3027:     return $token;
 3028: }
 3029: 
 3030: # ------------------------------------------------------------ Check in an item
 3031: 
 3032: sub checkin {
 3033:     my $token=shift;
 3034:     my $now=time;
 3035:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 3036:     $lonhost=~tr/A-Z/a-z/;
 3037:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 3038:     $dtoken=~s/\W/\_/g;
 3039:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 3040:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 3041: 
 3042:     unless (($tuname) && ($tudom)) {
 3043:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 3044:         return '';
 3045:     }
 3046:     
 3047:     unless (&allowed('mgr',$tcrsid)) {
 3048:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 3049:                  $env{'user.name'}.' - '.$env{'user.domain'});
 3050:         return '';
 3051:     }
 3052: 
 3053:     my %infohash=('resource.0.intoken' => $token,
 3054:                   'resource.0.checkintime' => $now,
 3055:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 3056: 
 3057:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3058:        return '';
 3059:     }    
 3060: 
 3061:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3062:                          &escape('Checkin - '.$token)) ne 'ok') {
 3063: 	return '';
 3064:     }
 3065: 
 3066:     return ($symb,$tuname,$tudom,$tcrsid);    
 3067: }
 3068: 
 3069: # --------------------------------------------- Set Expire Date for Spreadsheet
 3070: 
 3071: sub expirespread {
 3072:     my ($uname,$udom,$stype,$usymb)=@_;
 3073:     my $cid=$env{'request.course.id'}; 
 3074:     if ($cid) {
 3075:        my $now=time;
 3076:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3077:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3078:                             $env{'course.'.$cid.'.num'}.
 3079: 	        	    ':nohist_expirationdates:'.
 3080:                             &escape($key).'='.$now,
 3081:                             $env{'course.'.$cid.'.home'})
 3082:     }
 3083:     return 'ok';
 3084: }
 3085: 
 3086: # ----------------------------------------------------- Devalidate Spreadsheets
 3087: 
 3088: sub devalidate {
 3089:     my ($symb,$uname,$udom)=@_;
 3090:     my $cid=$env{'request.course.id'}; 
 3091:     if ($cid) {
 3092:         # delete the stored spreadsheets for
 3093:         # - the student level sheet of this user in course's homespace
 3094:         # - the assessment level sheet for this resource 
 3095:         #   for this user in user's homespace
 3096: 	# - current conditional state info
 3097: 	my $key=$uname.':'.$udom.':';
 3098:         my $status=
 3099: 	    &del('nohist_calculatedsheets',
 3100: 		 [$key.'studentcalc:'],
 3101: 		 $env{'course.'.$cid.'.domain'},
 3102: 		 $env{'course.'.$cid.'.num'})
 3103: 		.' '.
 3104: 	    &del('nohist_calculatedsheets_'.$cid,
 3105: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3106:         unless ($status eq 'ok ok') {
 3107:            &logthis('Could not devalidate spreadsheet '.
 3108:                     $uname.' at '.$udom.' for '.
 3109: 		    $symb.': '.$status);
 3110:         }
 3111: 	&delenv('user.state.'.$cid);
 3112:     }
 3113: }
 3114: 
 3115: sub get_scalar {
 3116:     my ($string,$end) = @_;
 3117:     my $value;
 3118:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3119: 	$value = $1;
 3120:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3121: 	$value = $1;
 3122:     }
 3123:     return &unescape($value);
 3124: }
 3125: 
 3126: sub array2str {
 3127:   my (@array) = @_;
 3128:   my $result=&arrayref2str(\@array);
 3129:   $result=~s/^__ARRAY_REF__//;
 3130:   $result=~s/__END_ARRAY_REF__$//;
 3131:   return $result;
 3132: }
 3133: 
 3134: sub arrayref2str {
 3135:   my ($arrayref) = @_;
 3136:   my $result='__ARRAY_REF__';
 3137:   foreach my $elem (@$arrayref) {
 3138:     if(ref($elem) eq 'ARRAY') {
 3139:       $result.=&arrayref2str($elem).'&';
 3140:     } elsif(ref($elem) eq 'HASH') {
 3141:       $result.=&hashref2str($elem).'&';
 3142:     } elsif(ref($elem)) {
 3143:       #print("Got a ref of ".(ref($elem))." skipping.");
 3144:     } else {
 3145:       $result.=&escape($elem).'&';
 3146:     }
 3147:   }
 3148:   $result=~s/\&$//;
 3149:   $result .= '__END_ARRAY_REF__';
 3150:   return $result;
 3151: }
 3152: 
 3153: sub hash2str {
 3154:   my (%hash) = @_;
 3155:   my $result=&hashref2str(\%hash);
 3156:   $result=~s/^__HASH_REF__//;
 3157:   $result=~s/__END_HASH_REF__$//;
 3158:   return $result;
 3159: }
 3160: 
 3161: sub hashref2str {
 3162:   my ($hashref)=@_;
 3163:   my $result='__HASH_REF__';
 3164:   foreach my $key (sort(keys(%$hashref))) {
 3165:     if (ref($key) eq 'ARRAY') {
 3166:       $result.=&arrayref2str($key).'=';
 3167:     } elsif (ref($key) eq 'HASH') {
 3168:       $result.=&hashref2str($key).'=';
 3169:     } elsif (ref($key)) {
 3170:       $result.='=';
 3171:       #print("Got a ref of ".(ref($key))." skipping.");
 3172:     } else {
 3173: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3174:     }
 3175: 
 3176:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3177:       $result.=&arrayref2str($hashref->{$key}).'&';
 3178:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3179:       $result.=&hashref2str($hashref->{$key}).'&';
 3180:     } elsif(ref($hashref->{$key})) {
 3181:        $result.='&';
 3182:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3183:     } else {
 3184:       $result.=&escape($hashref->{$key}).'&';
 3185:     }
 3186:   }
 3187:   $result=~s/\&$//;
 3188:   $result .= '__END_HASH_REF__';
 3189:   return $result;
 3190: }
 3191: 
 3192: sub str2hash {
 3193:     my ($string)=@_;
 3194:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3195:     return %$hash;
 3196: }
 3197: 
 3198: sub str2hashref {
 3199:   my ($string) = @_;
 3200: 
 3201:   my %hash;
 3202: 
 3203:   if($string !~ /^__HASH_REF__/) {
 3204:       if (! ($string eq '' || !defined($string))) {
 3205: 	  $hash{'error'}='Not hash reference';
 3206:       }
 3207:       return (\%hash, $string);
 3208:   }
 3209: 
 3210:   $string =~ s/^__HASH_REF__//;
 3211: 
 3212:   while($string !~ /^__END_HASH_REF__/) {
 3213:       #key
 3214:       my $key='';
 3215:       if($string =~ /^__HASH_REF__/) {
 3216:           ($key, $string)=&str2hashref($string);
 3217:           if(defined($key->{'error'})) {
 3218:               $hash{'error'}='Bad data';
 3219:               return (\%hash, $string);
 3220:           }
 3221:       } elsif($string =~ /^__ARRAY_REF__/) {
 3222:           ($key, $string)=&str2arrayref($string);
 3223:           if($key->[0] eq 'Array reference error') {
 3224:               $hash{'error'}='Bad data';
 3225:               return (\%hash, $string);
 3226:           }
 3227:       } else {
 3228:           $string =~ s/^(.*?)=//;
 3229: 	  $key=&unescape($1);
 3230:       }
 3231:       $string =~ s/^=//;
 3232: 
 3233:       #value
 3234:       my $value='';
 3235:       if($string =~ /^__HASH_REF__/) {
 3236:           ($value, $string)=&str2hashref($string);
 3237:           if(defined($value->{'error'})) {
 3238:               $hash{'error'}='Bad data';
 3239:               return (\%hash, $string);
 3240:           }
 3241:       } elsif($string =~ /^__ARRAY_REF__/) {
 3242:           ($value, $string)=&str2arrayref($string);
 3243:           if($value->[0] eq 'Array reference error') {
 3244:               $hash{'error'}='Bad data';
 3245:               return (\%hash, $string);
 3246:           }
 3247:       } else {
 3248: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3249:       }
 3250:       $string =~ s/^&//;
 3251: 
 3252:       $hash{$key}=$value;
 3253:   }
 3254: 
 3255:   $string =~ s/^__END_HASH_REF__//;
 3256: 
 3257:   return (\%hash, $string);
 3258: }
 3259: 
 3260: sub str2array {
 3261:     my ($string)=@_;
 3262:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3263:     return @$array;
 3264: }
 3265: 
 3266: sub str2arrayref {
 3267:   my ($string) = @_;
 3268:   my @array;
 3269: 
 3270:   if($string !~ /^__ARRAY_REF__/) {
 3271:       if (! ($string eq '' || !defined($string))) {
 3272: 	  $array[0]='Array reference error';
 3273:       }
 3274:       return (\@array, $string);
 3275:   }
 3276: 
 3277:   $string =~ s/^__ARRAY_REF__//;
 3278: 
 3279:   while($string !~ /^__END_ARRAY_REF__/) {
 3280:       my $value='';
 3281:       if($string =~ /^__HASH_REF__/) {
 3282:           ($value, $string)=&str2hashref($string);
 3283:           if(defined($value->{'error'})) {
 3284:               $array[0] ='Array reference error';
 3285:               return (\@array, $string);
 3286:           }
 3287:       } elsif($string =~ /^__ARRAY_REF__/) {
 3288:           ($value, $string)=&str2arrayref($string);
 3289:           if($value->[0] eq 'Array reference error') {
 3290:               $array[0] ='Array reference error';
 3291:               return (\@array, $string);
 3292:           }
 3293:       } else {
 3294: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3295:       }
 3296:       $string =~ s/^&//;
 3297: 
 3298:       push(@array, $value);
 3299:   }
 3300: 
 3301:   $string =~ s/^__END_ARRAY_REF__//;
 3302: 
 3303:   return (\@array, $string);
 3304: }
 3305: 
 3306: # -------------------------------------------------------------------Temp Store
 3307: 
 3308: sub tmpreset {
 3309:   my ($symb,$namespace,$domain,$stuname) = @_;
 3310:   if (!$symb) {
 3311:     $symb=&symbread();
 3312:     if (!$symb) { $symb= $env{'request.url'}; }
 3313:   }
 3314:   $symb=escape($symb);
 3315: 
 3316:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3317:   $namespace=~s/\//\_/g;
 3318:   $namespace=~s/\W//g;
 3319: 
 3320:   if (!$domain) { $domain=$env{'user.domain'}; }
 3321:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3322:   if ($domain eq 'public' && $stuname eq 'public') {
 3323:       $stuname=$ENV{'REMOTE_ADDR'};
 3324:   }
 3325:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3326:   my %hash;
 3327:   if (tie(%hash,'GDBM_File',
 3328: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3329: 	  &GDBM_WRCREAT(),0640)) {
 3330:     foreach my $key (keys %hash) {
 3331:       if ($key=~ /:$symb/) {
 3332: 	delete($hash{$key});
 3333:       }
 3334:     }
 3335:   }
 3336: }
 3337: 
 3338: sub tmpstore {
 3339:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3340: 
 3341:   if (!$symb) {
 3342:     $symb=&symbread();
 3343:     if (!$symb) { $symb= $env{'request.url'}; }
 3344:   }
 3345:   $symb=escape($symb);
 3346: 
 3347:   if (!$namespace) {
 3348:     # I don't think we would ever want to store this for a course.
 3349:     # it seems this will only be used if we don't have a course.
 3350:     #$namespace=$env{'request.course.id'};
 3351:     #if (!$namespace) {
 3352:       $namespace=$env{'request.state'};
 3353:     #}
 3354:   }
 3355:   $namespace=~s/\//\_/g;
 3356:   $namespace=~s/\W//g;
 3357:   if (!$domain) { $domain=$env{'user.domain'}; }
 3358:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3359:   if ($domain eq 'public' && $stuname eq 'public') {
 3360:       $stuname=$ENV{'REMOTE_ADDR'};
 3361:   }
 3362:   my $now=time;
 3363:   my %hash;
 3364:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3365:   if (tie(%hash,'GDBM_File',
 3366: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3367: 	  &GDBM_WRCREAT(),0640)) {
 3368:     $hash{"version:$symb"}++;
 3369:     my $version=$hash{"version:$symb"};
 3370:     my $allkeys=''; 
 3371:     foreach my $key (keys(%$storehash)) {
 3372:       $allkeys.=$key.':';
 3373:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3374:     }
 3375:     $hash{"$version:$symb:timestamp"}=$now;
 3376:     $allkeys.='timestamp';
 3377:     $hash{"$version:keys:$symb"}=$allkeys;
 3378:     if (untie(%hash)) {
 3379:       return 'ok';
 3380:     } else {
 3381:       return "error:$!";
 3382:     }
 3383:   } else {
 3384:     return "error:$!";
 3385:   }
 3386: }
 3387: 
 3388: # -----------------------------------------------------------------Temp Restore
 3389: 
 3390: sub tmprestore {
 3391:   my ($symb,$namespace,$domain,$stuname) = @_;
 3392: 
 3393:   if (!$symb) {
 3394:     $symb=&symbread();
 3395:     if (!$symb) { $symb= $env{'request.url'}; }
 3396:   }
 3397:   $symb=escape($symb);
 3398: 
 3399:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3400: 
 3401:   if (!$domain) { $domain=$env{'user.domain'}; }
 3402:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3403:   if ($domain eq 'public' && $stuname eq 'public') {
 3404:       $stuname=$ENV{'REMOTE_ADDR'};
 3405:   }
 3406:   my %returnhash;
 3407:   $namespace=~s/\//\_/g;
 3408:   $namespace=~s/\W//g;
 3409:   my %hash;
 3410:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3411:   if (tie(%hash,'GDBM_File',
 3412: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3413: 	  &GDBM_READER(),0640)) {
 3414:     my $version=$hash{"version:$symb"};
 3415:     $returnhash{'version'}=$version;
 3416:     my $scope;
 3417:     for ($scope=1;$scope<=$version;$scope++) {
 3418:       my $vkeys=$hash{"$scope:keys:$symb"};
 3419:       my @keys=split(/:/,$vkeys);
 3420:       my $key;
 3421:       $returnhash{"$scope:keys"}=$vkeys;
 3422:       foreach $key (@keys) {
 3423: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3424: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3425:       }
 3426:     }
 3427:     if (!(untie(%hash))) {
 3428:       return "error:$!";
 3429:     }
 3430:   } else {
 3431:     return "error:$!";
 3432:   }
 3433:   return %returnhash;
 3434: }
 3435: 
 3436: # ----------------------------------------------------------------------- Store
 3437: 
 3438: sub store {
 3439:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3440:     my $home='';
 3441: 
 3442:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3443: 
 3444:     $symb=&symbclean($symb);
 3445:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3446: 
 3447:     if (!$domain) { $domain=$env{'user.domain'}; }
 3448:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3449: 
 3450:     &devalidate($symb,$stuname,$domain);
 3451: 
 3452:     $symb=escape($symb);
 3453:     if (!$namespace) { 
 3454:        unless ($namespace=$env{'request.course.id'}) { 
 3455:           return ''; 
 3456:        } 
 3457:     }
 3458:     if (!$home) { $home=$env{'user.home'}; }
 3459: 
 3460:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3461:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3462: 
 3463:     my $namevalue='';
 3464:     foreach my $key (keys(%$storehash)) {
 3465:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3466:     }
 3467:     $namevalue=~s/\&$//;
 3468:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3469:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3470: }
 3471: 
 3472: # -------------------------------------------------------------- Critical Store
 3473: 
 3474: sub cstore {
 3475:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3476:     my $home='';
 3477: 
 3478:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3479: 
 3480:     $symb=&symbclean($symb);
 3481:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3482: 
 3483:     if (!$domain) { $domain=$env{'user.domain'}; }
 3484:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3485: 
 3486:     &devalidate($symb,$stuname,$domain);
 3487: 
 3488:     $symb=escape($symb);
 3489:     if (!$namespace) { 
 3490:        unless ($namespace=$env{'request.course.id'}) { 
 3491:           return ''; 
 3492:        } 
 3493:     }
 3494:     if (!$home) { $home=$env{'user.home'}; }
 3495: 
 3496:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3497:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3498: 
 3499:     my $namevalue='';
 3500:     foreach my $key (keys(%$storehash)) {
 3501:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3502:     }
 3503:     $namevalue=~s/\&$//;
 3504:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3505:     return critical
 3506:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3507: }
 3508: 
 3509: # --------------------------------------------------------------------- Restore
 3510: 
 3511: sub restore {
 3512:     my ($symb,$namespace,$domain,$stuname) = @_;
 3513:     my $home='';
 3514: 
 3515:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3516: 
 3517:     if (!$symb) {
 3518:       unless ($symb=escape(&symbread())) { return ''; }
 3519:     } else {
 3520:       $symb=&escape(&symbclean($symb));
 3521:     }
 3522:     if (!$namespace) { 
 3523:        unless ($namespace=$env{'request.course.id'}) { 
 3524:           return ''; 
 3525:        } 
 3526:     }
 3527:     if (!$domain) { $domain=$env{'user.domain'}; }
 3528:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3529:     if (!$home) { $home=$env{'user.home'}; }
 3530:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3531: 
 3532:     my %returnhash=();
 3533:     foreach my $line (split(/\&/,$answer)) {
 3534: 	my ($name,$value)=split(/\=/,$line);
 3535:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3536:     }
 3537:     my $version;
 3538:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3539:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3540:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3541:        }
 3542:     }
 3543:     return %returnhash;
 3544: }
 3545: 
 3546: # ---------------------------------------------------------- Course Description
 3547: 
 3548: sub coursedescription {
 3549:     my ($courseid,$args)=@_;
 3550:     $courseid=~s/^\///;
 3551:     $courseid=~s/\_/\//g;
 3552:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3553:     my $chome=&homeserver($cnum,$cdomain);
 3554:     my $normalid=$cdomain.'_'.$cnum;
 3555:     # need to always cache even if we get errors otherwise we keep 
 3556:     # trying and trying and trying to get the course description.
 3557:     my %envhash=();
 3558:     my %returnhash=();
 3559:     
 3560:     my $expiretime=600;
 3561:     if ($env{'request.course.id'} eq $normalid) {
 3562: 	$expiretime=120;
 3563:     }
 3564: 
 3565:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3566:     if (!$args->{'freshen_cache'}
 3567: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3568: 	foreach my $key (keys(%env)) {
 3569: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3570: 	    my ($setting) = $1;
 3571: 	    $returnhash{$setting} = $env{$key};
 3572: 	}
 3573: 	return %returnhash;
 3574:     }
 3575: 
 3576:     # get the data agin
 3577:     if (!$args->{'one_time'}) {
 3578: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3579:     }
 3580: 
 3581:     if ($chome ne 'no_host') {
 3582:        %returnhash=&dump('environment',$cdomain,$cnum);
 3583:        if (!exists($returnhash{'con_lost'})) {
 3584:            $returnhash{'home'}= $chome;
 3585: 	   $returnhash{'domain'} = $cdomain;
 3586: 	   $returnhash{'num'} = $cnum;
 3587:            if (!defined($returnhash{'type'})) {
 3588:                $returnhash{'type'} = 'Course';
 3589:            }
 3590:            while (my ($name,$value) = each %returnhash) {
 3591:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3592:            }
 3593:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3594:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3595: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3596:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3597:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3598:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3599:        }
 3600:     }
 3601:     if (!$args->{'one_time'}) {
 3602: 	&appenv(\%envhash);
 3603:     }
 3604:     return %returnhash;
 3605: }
 3606: 
 3607: # -------------------------------------------------See if a user is privileged
 3608: 
 3609: sub privileged {
 3610:     my ($username,$domain)=@_;
 3611:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3612: 			&homeserver($username,$domain));
 3613:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3614:     my $now=time;
 3615:     if ($rolesdump ne '') {
 3616:         foreach my $entry (split(/&/,$rolesdump)) {
 3617: 	    if ($entry!~/^rolesdef_/) {
 3618: 		my ($area,$role)=split(/=/,$entry);
 3619: 		$area=~s/\_\w\w$//;
 3620: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3621: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3622: 		    my $active=1;
 3623: 		    if ($tend) {
 3624: 			if ($tend<$now) { $active=0; }
 3625: 		    }
 3626: 		    if ($tstart) {
 3627: 			if ($tstart>$now) { $active=0; }
 3628: 		    }
 3629: 		    if ($active) { return 1; }
 3630: 		}
 3631: 	    }
 3632: 	}
 3633:     }
 3634:     return 0;
 3635: }
 3636: 
 3637: # -------------------------------------------------------- Get user privileges
 3638: 
 3639: sub rolesinit {
 3640:     my ($domain,$username,$authhost)=@_;
 3641:     my %userroles;
 3642:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3643:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
 3644:     my %allroles=();
 3645:     my %allgroups=();   
 3646:     my $now=time;
 3647:     %userroles = ('user.login.time' => $now);
 3648:     my $group_privs;
 3649: 
 3650:     if ($rolesdump ne '') {
 3651:         foreach my $entry (split(/&/,$rolesdump)) {
 3652: 	  if ($entry!~/^rolesdef_/) {
 3653:             my ($area,$role)=split(/=/,$entry);
 3654: 	    $area=~s/\_\w\w$//;
 3655:             my ($trole,$tend,$tstart,$group_privs);
 3656: 	    if ($role=~/^cr/) { 
 3657: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3658: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3659: 		    ($tend,$tstart)=split('_',$trest);
 3660: 		} else {
 3661: 		    $trole=$role;
 3662: 		}
 3663:             } elsif ($role =~ m|^gr/|) {
 3664:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3665:                 ($trole,$group_privs) = split(/\//,$trole);
 3666:                 $group_privs = &unescape($group_privs);
 3667: 	    } else {
 3668: 		($trole,$tend,$tstart)=split(/_/,$role);
 3669: 	    }
 3670: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3671: 					 $username);
 3672: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3673:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3674:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3675:             if (($area ne '') && ($trole ne '')) {
 3676: 		my $spec=$trole.'.'.$area;
 3677: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3678: 		if ($trole =~ /^cr\//) {
 3679:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3680:                 } elsif ($trole eq 'gr') {
 3681:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3682: 		} else {
 3683:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3684: 		}
 3685:             }
 3686:           }
 3687:         }
 3688:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3689:         $userroles{'user.adv'}    = $adv;
 3690: 	$userroles{'user.author'} = $author;
 3691:         $env{'user.adv'}=$adv;
 3692:     }
 3693:     return \%userroles;  
 3694: }
 3695: 
 3696: sub set_arearole {
 3697:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3698: # log the associated role with the area
 3699:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3700:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3701: }
 3702: 
 3703: sub custom_roleprivs {
 3704:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3705:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3706:     my $homsvr=homeserver($rauthor,$rdomain);
 3707:     if (&hostname($homsvr) ne '') {
 3708:         my ($rdummy,$roledef)=
 3709:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3710:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3711:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3712:             if (defined($syspriv)) {
 3713:                 $$allroles{'cm./'}.=':'.$syspriv;
 3714:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3715:             }
 3716:             if ($tdomain ne '') {
 3717:                 if (defined($dompriv)) {
 3718:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3719:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3720:                 }
 3721:                 if (($trest ne '') && (defined($coursepriv))) {
 3722:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3723:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3724:                 }
 3725:             }
 3726:         }
 3727:     }
 3728: }
 3729: 
 3730: sub group_roleprivs {
 3731:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3732:     my $access = 1;
 3733:     my $now = time;
 3734:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3735:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3736:     if ($access) {
 3737:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3738:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3739:     }
 3740: }
 3741: 
 3742: sub standard_roleprivs {
 3743:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3744:     if (defined($pr{$trole.':s'})) {
 3745:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3746:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3747:     }
 3748:     if ($tdomain ne '') {
 3749:         if (defined($pr{$trole.':d'})) {
 3750:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3751:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3752:         }
 3753:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3754:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3755:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3756:         }
 3757:     }
 3758: }
 3759: 
 3760: sub set_userprivs {
 3761:     my ($userroles,$allroles,$allgroups) = @_; 
 3762:     my $author=0;
 3763:     my $adv=0;
 3764:     my %grouproles = ();
 3765:     if (keys(%{$allgroups}) > 0) {
 3766:         foreach my $role (keys %{$allroles}) {
 3767:             my ($trole,$area,$sec,$extendedarea);
 3768:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3769:                 $trole = $1;
 3770:                 $area = $2;
 3771:                 $sec = $3;
 3772:                 $extendedarea = $area.$sec;
 3773:                 if (exists($$allgroups{$area})) {
 3774:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3775:                         my $spec = $trole.'.'.$extendedarea;
 3776:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3777:                                                 $$allgroups{$area}{$group};
 3778:                     }
 3779:                 }
 3780:             }
 3781:         }
 3782:     }
 3783:     foreach my $group (keys(%grouproles)) {
 3784:         $$allroles{$group} = $grouproles{$group};
 3785:     }
 3786:     foreach my $role (keys(%{$allroles})) {
 3787:         my %thesepriv;
 3788:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3789:         foreach my $item (split(/:/,$$allroles{$role})) {
 3790:             if ($item ne '') {
 3791:                 my ($privilege,$restrictions)=split(/&/,$item);
 3792:                 if ($restrictions eq '') {
 3793:                     $thesepriv{$privilege}='F';
 3794:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3795:                     $thesepriv{$privilege}.=$restrictions;
 3796:                 }
 3797:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3798:             }
 3799:         }
 3800:         my $thesestr='';
 3801:         foreach my $priv (keys(%thesepriv)) {
 3802: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3803: 	}
 3804:         $userroles->{'user.priv.'.$role} = $thesestr;
 3805:     }
 3806:     return ($author,$adv);
 3807: }
 3808: 
 3809: # --------------------------------------------------------------- get interface
 3810: 
 3811: sub get {
 3812:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3813:    my $items='';
 3814:    foreach my $item (@$storearr) {
 3815:        $items.=&escape($item).'&';
 3816:    }
 3817:    $items=~s/\&$//;
 3818:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3819:    if (!$uname) { $uname=$env{'user.name'}; }
 3820:    my $uhome=&homeserver($uname,$udomain);
 3821: 
 3822:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3823:    my @pairs=split(/\&/,$rep);
 3824:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3825:      return @pairs;
 3826:    }
 3827:    my %returnhash=();
 3828:    my $i=0;
 3829:    foreach my $item (@$storearr) {
 3830:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3831:       $i++;
 3832:    }
 3833:    return %returnhash;
 3834: }
 3835: 
 3836: # --------------------------------------------------------------- del interface
 3837: 
 3838: sub del {
 3839:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3840:    my $items='';
 3841:    foreach my $item (@$storearr) {
 3842:        $items.=&escape($item).'&';
 3843:    }
 3844:    $items=~s/\&$//;
 3845:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3846:    if (!$uname) { $uname=$env{'user.name'}; }
 3847:    my $uhome=&homeserver($uname,$udomain);
 3848: 
 3849:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3850: }
 3851: 
 3852: # -------------------------------------------------------------- dump interface
 3853: 
 3854: sub dump {
 3855:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3856:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3857:     if (!$uname) { $uname=$env{'user.name'}; }
 3858:     my $uhome=&homeserver($uname,$udomain);
 3859:     if ($regexp) {
 3860: 	$regexp=&escape($regexp);
 3861:     } else {
 3862: 	$regexp='.';
 3863:     }
 3864:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3865:     my @pairs=split(/\&/,$rep);
 3866:     my %returnhash=();
 3867:     foreach my $item (@pairs) {
 3868: 	my ($key,$value)=split(/=/,$item,2);
 3869: 	$key = &unescape($key);
 3870: 	next if ($key =~ /^error: 2 /);
 3871: 	$returnhash{$key}=&thaw_unescape($value);
 3872:     }
 3873:     return %returnhash;
 3874: }
 3875: 
 3876: # --------------------------------------------------------- dumpstore interface
 3877: 
 3878: sub dumpstore {
 3879:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3880:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3881:    if (!$uname) { $uname=$env{'user.name'}; }
 3882:    my $uhome=&homeserver($uname,$udomain);
 3883:    if ($regexp) {
 3884:        $regexp=&escape($regexp);
 3885:    } else {
 3886:        $regexp='.';
 3887:    }
 3888:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3889:    my @pairs=split(/\&/,$rep);
 3890:    my %returnhash=();
 3891:    foreach my $item (@pairs) {
 3892:        my ($key,$value)=split(/=/,$item,2);
 3893:        next if ($key =~ /^error: 2 /);
 3894:        $returnhash{$key}=&thaw_unescape($value);
 3895:    }
 3896:    return %returnhash;
 3897: }
 3898: 
 3899: # -------------------------------------------------------------- keys interface
 3900: 
 3901: sub getkeys {
 3902:    my ($namespace,$udomain,$uname)=@_;
 3903:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3904:    if (!$uname) { $uname=$env{'user.name'}; }
 3905:    my $uhome=&homeserver($uname,$udomain);
 3906:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3907:    my @keyarray=();
 3908:    foreach my $key (split(/\&/,$rep)) {
 3909:       next if ($key =~ /^error: 2 /);
 3910:       push(@keyarray,&unescape($key));
 3911:    }
 3912:    return @keyarray;
 3913: }
 3914: 
 3915: # --------------------------------------------------------------- currentdump
 3916: sub currentdump {
 3917:    my ($courseid,$sdom,$sname)=@_;
 3918:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3919:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3920:    $sname    = $env{'user.name'}         if (! defined($sname));
 3921:    my $uhome = &homeserver($sname,$sdom);
 3922:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3923:    return if ($rep =~ /^(error:|no_such_host)/);
 3924:    #
 3925:    my %returnhash=();
 3926:    #
 3927:    if ($rep eq "unknown_cmd") { 
 3928:        # an old lond will not know currentdump
 3929:        # Do a dump and make it look like a currentdump
 3930:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3931:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3932:        my %hash = @tmp;
 3933:        @tmp=();
 3934:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3935:    } else {
 3936:        my @pairs=split(/\&/,$rep);
 3937:        foreach my $pair (@pairs) {
 3938:            my ($key,$value)=split(/=/,$pair,2);
 3939:            my ($symb,$param) = split(/:/,$key);
 3940:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3941:                                                         &thaw_unescape($value);
 3942:        }
 3943:    }
 3944:    return %returnhash;
 3945: }
 3946: 
 3947: sub convert_dump_to_currentdump{
 3948:     my %hash = %{shift()};
 3949:     my %returnhash;
 3950:     # Code ripped from lond, essentially.  The only difference
 3951:     # here is the unescaping done by lonnet::dump().  Conceivably
 3952:     # we might run in to problems with parameter names =~ /^v\./
 3953:     while (my ($key,$value) = each(%hash)) {
 3954:         my ($v,$symb,$param) = split(/:/,$key);
 3955: 	$symb  = &unescape($symb);
 3956: 	$param = &unescape($param);
 3957:         next if ($v eq 'version' || $symb eq 'keys');
 3958:         next if (exists($returnhash{$symb}) &&
 3959:                  exists($returnhash{$symb}->{$param}) &&
 3960:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3961:         $returnhash{$symb}->{$param}=$value;
 3962:         $returnhash{$symb}->{'v.'.$param}=$v;
 3963:     }
 3964:     #
 3965:     # Remove all of the keys in the hashes which keep track of
 3966:     # the version of the parameter.
 3967:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3968:         # use a foreach because we are going to delete from the hash.
 3969:         foreach my $key (keys(%$param_hash)) {
 3970:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3971:         }
 3972:     }
 3973:     return \%returnhash;
 3974: }
 3975: 
 3976: # ------------------------------------------------------ critical inc interface
 3977: 
 3978: sub cinc {
 3979:     return &inc(@_,'critical');
 3980: }
 3981: 
 3982: # --------------------------------------------------------------- inc interface
 3983: 
 3984: sub inc {
 3985:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3986:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3987:     if (!$uname) { $uname=$env{'user.name'}; }
 3988:     my $uhome=&homeserver($uname,$udomain);
 3989:     my $items='';
 3990:     if (! ref($store)) {
 3991:         # got a single value, so use that instead
 3992:         $items = &escape($store).'=&';
 3993:     } elsif (ref($store) eq 'SCALAR') {
 3994:         $items = &escape($$store).'=&';        
 3995:     } elsif (ref($store) eq 'ARRAY') {
 3996:         $items = join('=&',map {&escape($_);} @{$store});
 3997:     } elsif (ref($store) eq 'HASH') {
 3998:         while (my($key,$value) = each(%{$store})) {
 3999:             $items.= &escape($key).'='.&escape($value).'&';
 4000:         }
 4001:     }
 4002:     $items=~s/\&$//;
 4003:     if ($critical) {
 4004: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 4005:     } else {
 4006: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 4007:     }
 4008: }
 4009: 
 4010: # --------------------------------------------------------------- put interface
 4011: 
 4012: sub put {
 4013:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4014:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4015:    if (!$uname) { $uname=$env{'user.name'}; }
 4016:    my $uhome=&homeserver($uname,$udomain);
 4017:    my $items='';
 4018:    foreach my $item (keys(%$storehash)) {
 4019:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4020:    }
 4021:    $items=~s/\&$//;
 4022:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4023: }
 4024: 
 4025: # ------------------------------------------------------------ newput interface
 4026: 
 4027: sub newput {
 4028:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4029:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4030:    if (!$uname) { $uname=$env{'user.name'}; }
 4031:    my $uhome=&homeserver($uname,$udomain);
 4032:    my $items='';
 4033:    foreach my $key (keys(%$storehash)) {
 4034:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4035:    }
 4036:    $items=~s/\&$//;
 4037:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 4038: }
 4039: 
 4040: # ---------------------------------------------------------  putstore interface
 4041: 
 4042: sub putstore {
 4043:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4044:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4045:    if (!$uname) { $uname=$env{'user.name'}; }
 4046:    my $uhome=&homeserver($uname,$udomain);
 4047:    my $items='';
 4048:    foreach my $key (keys(%$storehash)) {
 4049:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 4050:    }
 4051:    $items=~s/\&$//;
 4052:    my $esc_symb=&escape($symb);
 4053:    my $esc_v=&escape($version);
 4054:    my $reply =
 4055:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 4056: 	      $uhome);
 4057:    if ($reply eq 'unknown_cmd') {
 4058:        # gfall back to way things use to be done
 4059:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 4060: 			    $uname);
 4061:    }
 4062:    return $reply;
 4063: }
 4064: 
 4065: sub old_putstore {
 4066:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4067:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4068:     if (!$uname) { $uname=$env{'user.name'}; }
 4069:     my $uhome=&homeserver($uname,$udomain);
 4070:     my %newstorehash;
 4071:     foreach my $item (keys(%$storehash)) {
 4072: 	my $key = $version.':'.&escape($symb).':'.$item;
 4073: 	$newstorehash{$key} = $storehash->{$item};
 4074:     }
 4075:     my $items='';
 4076:     my %allitems = ();
 4077:     foreach my $item (keys(%newstorehash)) {
 4078: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 4079: 	    my $key = $1.':keys:'.$2;
 4080: 	    $allitems{$key} .= $3.':';
 4081: 	}
 4082: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 4083:     }
 4084:     foreach my $item (keys(%allitems)) {
 4085: 	$allitems{$item} =~ s/\:$//;
 4086: 	$items.= $item.'='.$allitems{$item}.'&';
 4087:     }
 4088:     $items=~s/\&$//;
 4089:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4090: }
 4091: 
 4092: # ------------------------------------------------------ critical put interface
 4093: 
 4094: sub cput {
 4095:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4096:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4097:    if (!$uname) { $uname=$env{'user.name'}; }
 4098:    my $uhome=&homeserver($uname,$udomain);
 4099:    my $items='';
 4100:    foreach my $item (keys(%$storehash)) {
 4101:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4102:    }
 4103:    $items=~s/\&$//;
 4104:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 4105: }
 4106: 
 4107: # -------------------------------------------------------------- eget interface
 4108: 
 4109: sub eget {
 4110:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4111:    my $items='';
 4112:    foreach my $item (@$storearr) {
 4113:        $items.=&escape($item).'&';
 4114:    }
 4115:    $items=~s/\&$//;
 4116:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4117:    if (!$uname) { $uname=$env{'user.name'}; }
 4118:    my $uhome=&homeserver($uname,$udomain);
 4119:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 4120:    my @pairs=split(/\&/,$rep);
 4121:    my %returnhash=();
 4122:    my $i=0;
 4123:    foreach my $item (@$storearr) {
 4124:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4125:       $i++;
 4126:    }
 4127:    return %returnhash;
 4128: }
 4129: 
 4130: # ------------------------------------------------------------ tmpput interface
 4131: sub tmpput {
 4132:     my ($storehash,$server,$context)=@_;
 4133:     my $items='';
 4134:     foreach my $item (keys(%$storehash)) {
 4135: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4136:     }
 4137:     $items=~s/\&$//;
 4138:     if (defined($context)) {
 4139:         $items .= ':'.&escape($context);
 4140:     }
 4141:     return &reply("tmpput:$items",$server);
 4142: }
 4143: 
 4144: # ------------------------------------------------------------ tmpget interface
 4145: sub tmpget {
 4146:     my ($token,$server)=@_;
 4147:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4148:     my $rep=&reply("tmpget:$token",$server);
 4149:     my %returnhash;
 4150:     foreach my $item (split(/\&/,$rep)) {
 4151: 	my ($key,$value)=split(/=/,$item);
 4152:         next if ($key =~ /^error: 2 /);
 4153: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 4154:     }
 4155:     return %returnhash;
 4156: }
 4157: 
 4158: # ------------------------------------------------------------ tmpget interface
 4159: sub tmpdel {
 4160:     my ($token,$server)=@_;
 4161:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4162:     return &reply("tmpdel:$token",$server);
 4163: }
 4164: 
 4165: # -------------------------------------------------- portfolio access checking
 4166: 
 4167: sub portfolio_access {
 4168:     my ($requrl) = @_;
 4169:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4170:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4171:     if ($result) {
 4172:         my %setters;
 4173:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4174:             my ($startblock,$endblock) =
 4175:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4176:             if ($startblock && $endblock) {
 4177:                 return 'B';
 4178:             }
 4179:         } else {
 4180:             my ($startblock,$endblock) =
 4181:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4182:             if ($startblock && $endblock) {
 4183:                 return 'B';
 4184:             }
 4185:         }
 4186:     }
 4187:     if ($result eq 'ok') {
 4188:        return 'F';
 4189:     } elsif ($result =~ /^[^:]+:guest_/) {
 4190:        return 'A';
 4191:     }
 4192:     return '';
 4193: }
 4194: 
 4195: sub get_portfolio_access {
 4196:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4197: 
 4198:     if (!ref($access_hash)) {
 4199: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4200: 	my %access_controls = &get_access_controls($current_perms,$group,
 4201: 						   $file_name);
 4202: 	$access_hash = $access_controls{$file_name};
 4203:     }
 4204: 
 4205:     my ($public,$guest,@domains,@users,@courses,@groups);
 4206:     my $now = time;
 4207:     if (ref($access_hash) eq 'HASH') {
 4208:         foreach my $key (keys(%{$access_hash})) {
 4209:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4210:             if ($start > $now) {
 4211:                 next;
 4212:             }
 4213:             if ($end && $end<$now) {
 4214:                 next;
 4215:             }
 4216:             if ($scope eq 'public') {
 4217:                 $public = $key;
 4218:                 last;
 4219:             } elsif ($scope eq 'guest') {
 4220:                 $guest = $key;
 4221:             } elsif ($scope eq 'domains') {
 4222:                 push(@domains,$key);
 4223:             } elsif ($scope eq 'users') {
 4224:                 push(@users,$key);
 4225:             } elsif ($scope eq 'course') {
 4226:                 push(@courses,$key);
 4227:             } elsif ($scope eq 'group') {
 4228:                 push(@groups,$key);
 4229:             }
 4230:         }
 4231:         if ($public) {
 4232:             return 'ok';
 4233:         }
 4234:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4235:             if ($guest) {
 4236:                 return $guest;
 4237:             }
 4238:         } else {
 4239:             if (@domains > 0) {
 4240:                 foreach my $domkey (@domains) {
 4241:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4242:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4243:                             return 'ok';
 4244:                         }
 4245:                     }
 4246:                 }
 4247:             }
 4248:             if (@users > 0) {
 4249:                 foreach my $userkey (@users) {
 4250:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4251:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4252:                             if (ref($item) eq 'HASH') {
 4253:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4254:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4255:                                     return 'ok';
 4256:                                 }
 4257:                             }
 4258:                         }
 4259:                     } 
 4260:                 }
 4261:             }
 4262:             my %roleshash;
 4263:             my @courses_and_groups = @courses;
 4264:             push(@courses_and_groups,@groups); 
 4265:             if (@courses_and_groups > 0) {
 4266:                 my (%allgroups,%allroles); 
 4267:                 my ($start,$end,$role,$sec,$group);
 4268:                 foreach my $envkey (%env) {
 4269:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4270:                         my $cid = $2.'_'.$3; 
 4271:                         if ($1 eq 'gr') {
 4272:                             $group = $4;
 4273:                             $allgroups{$cid}{$group} = $env{$envkey};
 4274:                         } else {
 4275:                             if ($4 eq '') {
 4276:                                 $sec = 'none';
 4277:                             } else {
 4278:                                 $sec = $4;
 4279:                             }
 4280:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4281:                         }
 4282:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4283:                         my $cid = $2.'_'.$3;
 4284:                         if ($4 eq '') {
 4285:                             $sec = 'none';
 4286:                         } else {
 4287:                             $sec = $4;
 4288:                         }
 4289:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4290:                     }
 4291:                 }
 4292:                 if (keys(%allroles) == 0) {
 4293:                     return;
 4294:                 }
 4295:                 foreach my $key (@courses_and_groups) {
 4296:                     my %content = %{$$access_hash{$key}};
 4297:                     my $cnum = $content{'number'};
 4298:                     my $cdom = $content{'domain'};
 4299:                     my $cid = $cdom.'_'.$cnum;
 4300:                     if (!exists($allroles{$cid})) {
 4301:                         next;
 4302:                     }    
 4303:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4304:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4305:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4306:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4307:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4308:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4309:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4310:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4311:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4312:                                         if (grep/^all$/,@sections) {
 4313:                                             return 'ok';
 4314:                                         } else {
 4315:                                             if (grep/^$sec$/,@sections) {
 4316:                                                 return 'ok';
 4317:                                             }
 4318:                                         }
 4319:                                     }
 4320:                                 }
 4321:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4322:                                     if (grep/^none$/,@groups) {
 4323:                                         return 'ok';
 4324:                                     }
 4325:                                 } else {
 4326:                                     if (grep/^all$/,@groups) {
 4327:                                         return 'ok';
 4328:                                     } 
 4329:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4330:                                         if (grep/^$group$/,@groups) {
 4331:                                             return 'ok';
 4332:                                         }
 4333:                                     }
 4334:                                 } 
 4335:                             }
 4336:                         }
 4337:                     }
 4338:                 }
 4339:             }
 4340:             if ($guest) {
 4341:                 return $guest;
 4342:             }
 4343:         }
 4344:     }
 4345:     return;
 4346: }
 4347: 
 4348: sub course_group_datechecker {
 4349:     my ($dates,$now,$status) = @_;
 4350:     my ($start,$end) = split(/\./,$dates);
 4351:     if (!$start && !$end) {
 4352:         return 'ok';
 4353:     }
 4354:     if (grep/^active$/,@{$status}) {
 4355:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4356:             return 'ok';
 4357:         }
 4358:     }
 4359:     if (grep/^previous$/,@{$status}) {
 4360:         if ($end > $now ) {
 4361:             return 'ok';
 4362:         }
 4363:     }
 4364:     if (grep/^future$/,@{$status}) {
 4365:         if ($start > $now) {
 4366:             return 'ok';
 4367:         }
 4368:     }
 4369:     return; 
 4370: }
 4371: 
 4372: sub parse_portfolio_url {
 4373:     my ($url) = @_;
 4374: 
 4375:     my ($type,$udom,$unum,$group,$file_name);
 4376:     
 4377:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4378: 	$type = 1;
 4379:         $udom = $1;
 4380:         $unum = $2;
 4381:         $file_name = $3;
 4382:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4383: 	$type = 2;
 4384:         $udom = $1;
 4385:         $unum = $2;
 4386:         $group = $3;
 4387:         $file_name = $3.'/'.$4;
 4388:     }
 4389:     if (wantarray) {
 4390: 	return ($type,$udom,$unum,$file_name,$group);
 4391:     }
 4392:     return $type;
 4393: }
 4394: 
 4395: sub is_portfolio_url {
 4396:     my ($url) = @_;
 4397:     return scalar(&parse_portfolio_url($url));
 4398: }
 4399: 
 4400: sub is_portfolio_file {
 4401:     my ($file) = @_;
 4402:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4403:         return 1;
 4404:     }
 4405:     return;
 4406: }
 4407: 
 4408: sub usertools_access {
 4409:     my ($uname,$udom,$tool) = @_;
 4410:     my $access;
 4411:     my %tools = (
 4412:                   aboutme   => 1,
 4413:                   blog      => 1,
 4414:                   portfolio => 1,
 4415:                 );
 4416:     return if (!defined($tools{$tool}));
 4417: 
 4418:     if ((!defined($udom)) || (!defined($uname))) {
 4419:         $udom = $env{'user.domain'};
 4420:         $uname = $env{'user.name'};
 4421:     }
 4422: 
 4423:     my $hashid=$uname.':'.$udom;
 4424:     my ($result,$cached) = &is_cached_new('usertools.'.$tool,$hashid);
 4425:     if (defined($cached)) {
 4426:         return $result;
 4427:     }
 4428: 
 4429:     my ($toolstatus,$inststatus);
 4430: 
 4431:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4432:         $toolstatus = $env{'environment.tools.'.$tool};
 4433:         $inststatus = $env{'environment.inststatus'};
 4434:     } else {
 4435:         my %userenv = &userenvironment($udom,$uname,'tools.'.$tool);
 4436:         $toolstatus = $userenv{'tools.'.$tool};
 4437:         $inststatus = $userenv{'inststatus'};
 4438:     }
 4439: 
 4440:     if ($toolstatus ne '') {
 4441:         if ($toolstatus) {
 4442:             $access = 1;
 4443:         } else {
 4444:             $access = 0;
 4445:         }
 4446:         &do_cache_new('usertools.'.$tool,$hashid,$access,600);
 4447:         return $access;
 4448:     }
 4449: 
 4450:     my $is_adv = &is_advanced_user($udom,$uname);
 4451:     my %domdef = &get_domain_defaults($udom);
 4452:     if (ref($domdef{$tool}) eq 'HASH') {
 4453:         if ($is_adv) {
 4454:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 4455:                 if ($domdef{$tool}{'_LC_adv'}) { 
 4456:                     $access = 1;
 4457:                 } else {
 4458:                     $access = 0;
 4459:                 }
 4460:                 &do_cache_new('usertools.'.$tool,$hashid,$access,600);
 4461:                 return $access;
 4462:             }
 4463:         }
 4464:         if ($inststatus ne '') {
 4465:             my ($hasaccess,$hasnoaccess);
 4466:             foreach my $affiliation (split(/:/,$inststatus)) {
 4467:                 if ($domdef{$tool}{$affiliation} ne '') { 
 4468:                     if ($domdef{$tool}{$affiliation}) {
 4469:                         $hasaccess = 1;
 4470:                     } else {
 4471:                         $hasnoaccess = 1;
 4472:                     }
 4473:                 }
 4474:             }
 4475:             if ($hasaccess || $hasnoaccess) {
 4476:                 if ($hasaccess) {
 4477:                     $access = 1;
 4478:                 } elsif ($hasnoaccess) {
 4479:                     $access = 0; 
 4480:                 }
 4481:                 &do_cache_new('usertools.'.$tool,$hashid,$access,600);
 4482:                 return $access;
 4483:             }
 4484:         } else {
 4485:             if ($domdef{$tool}{'default'} ne '') {
 4486:                 if ($domdef{$tool}{'default'}) {
 4487:                     $access = 1;
 4488:                 } elsif ($domdef{$tool}{'default'} == 0) {
 4489:                     $access = 0;
 4490:                 }
 4491:                 &do_cache_new('usertools.'.$tool,$hashid,$access,600);
 4492:                 return $access;
 4493:             }
 4494:         }
 4495:     } else {
 4496:         $access = 1;
 4497:         &do_cache_new('usertools.'.$tool,$hashid,$access,600);
 4498:         return $access;
 4499:     }
 4500: }
 4501: 
 4502: sub is_advanced_user {
 4503:     my ($udom,$uname) = @_;
 4504:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 4505:     my %allroles;
 4506:     my $is_adv;
 4507:     foreach my $role (keys(%roleshash)) {
 4508:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 4509:         my $area = '/'.$tdomain.'/'.$trest;
 4510:         if ($sec ne '') {
 4511:             $area .= '/'.$sec;
 4512:         }
 4513:         if (($area ne '') && ($trole ne '')) {
 4514:             my $spec=$trole.'.'.$area;
 4515:             if ($trole =~ /^cr\//) {
 4516:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4517:             } elsif ($trole ne 'gr') {
 4518:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4519:             }
 4520:         }
 4521:     }
 4522:     foreach my $role (keys(%allroles)) {
 4523:         last if ($is_adv);
 4524:         foreach my $item (split(/:/,$allroles{$role})) {
 4525:             if ($item ne '') {
 4526:                 my ($privilege,$restrictions)=split(/&/,$item);
 4527:                 if ($privilege eq 'adv') {
 4528:                     $is_adv = 1;
 4529:                     last;
 4530:                 }
 4531:             }
 4532:         }
 4533:     }
 4534:     return $is_adv;
 4535: }
 4536: 
 4537: # ---------------------------------------------- Custom access rule evaluation
 4538: 
 4539: sub customaccess {
 4540:     my ($priv,$uri)=@_;
 4541:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4542:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4543:     $udom = &LONCAPA::clean_domain($udom);
 4544:     $ucrs = &LONCAPA::clean_username($ucrs);
 4545:     my $access=0;
 4546:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4547: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4548: 	if ($type eq 'user') {
 4549: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4550: 		my ($tdom,$tuname)=split(m{/},$scope);
 4551: 		if ($tdom) {
 4552: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4553: 		}
 4554: 		if ($tuname) {
 4555: 		    if ($tuname ne $env{'user.name'}) { next; }
 4556: 		}
 4557: 		$access=($effect eq 'allow');
 4558: 		last;
 4559: 	    }
 4560: 	} else {
 4561: 	    if ($role) {
 4562: 		if ($role ne $urole) { next; }
 4563: 	    }
 4564: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4565: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4566: 		if ($tdom) {
 4567: 		    if ($tdom ne $udom) { next; }
 4568: 		}
 4569: 		if ($tcrs) {
 4570: 		    if ($tcrs ne $ucrs) { next; }
 4571: 		}
 4572: 		if ($tsec) {
 4573: 		    if ($tsec ne $usec) { next; }
 4574: 		}
 4575: 		$access=($effect eq 'allow');
 4576: 		last;
 4577: 	    }
 4578: 	    if ($realm eq '' && $role eq '') {
 4579: 		$access=($effect eq 'allow');
 4580: 	    }
 4581: 	}
 4582:     }
 4583:     return $access;
 4584: }
 4585: 
 4586: # ------------------------------------------------- Check for a user privilege
 4587: 
 4588: sub allowed {
 4589:     my ($priv,$uri,$symb,$role)=@_;
 4590:     my $ver_orguri=$uri;
 4591:     $uri=&deversion($uri);
 4592:     my $orguri=$uri;
 4593:     $uri=&declutter($uri);
 4594: 
 4595:     if ($priv eq 'evb') {
 4596: # Evade communication block restrictions for specified role in a course
 4597:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4598:             return $1;
 4599:         } else {
 4600:             return;
 4601:         }
 4602:     }
 4603: 
 4604:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4605: # Free bre access to adm and meta resources
 4606:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4607: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4608: 	&& ($priv eq 'bre')) {
 4609: 	return 'F';
 4610:     }
 4611: 
 4612: # Free bre access to user's own portfolio contents
 4613:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4614:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4615: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4616:         my %setters;
 4617:         my ($startblock,$endblock) = 
 4618:             &Apache::loncommon::blockcheck(\%setters,'port');
 4619:         if ($startblock && $endblock) {
 4620:             return 'B';
 4621:         } else {
 4622:             return 'F';
 4623:         }
 4624:     }
 4625: 
 4626: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4627:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4628:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4629:         if (exists($env{'request.course.id'})) {
 4630:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4631:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4632:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4633:                 my $courseprivid=$env{'request.course.id'};
 4634:                 $courseprivid=~s/\_/\//;
 4635:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4636:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4637:                     return $1; 
 4638:                 } else {
 4639:                     if ($env{'request.course.sec'}) {
 4640:                         $courseprivid.='/'.$env{'request.course.sec'};
 4641:                     }
 4642:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4643:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4644:                         return $2;
 4645:                     }
 4646:                 }
 4647:             }
 4648:         }
 4649:     }
 4650: 
 4651: # Free bre to public access
 4652: 
 4653:     if ($priv eq 'bre') {
 4654:         my $copyright=&metadata($uri,'copyright');
 4655: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4656:            return 'F'; 
 4657:         }
 4658:         if ($copyright eq 'priv') {
 4659:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4660: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4661: 		return '';
 4662:             }
 4663:         }
 4664:         if ($copyright eq 'domain') {
 4665:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4666: 	    unless (($env{'user.domain'} eq $1) ||
 4667:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4668: 		return '';
 4669:             }
 4670:         }
 4671:         if ($env{'request.role'}=~ /li\.\//) {
 4672:             # Library role, so allow browsing of resources in this domain.
 4673:             return 'F';
 4674:         }
 4675:         if ($copyright eq 'custom') {
 4676: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4677:         }
 4678:     }
 4679:     # Domain coordinator is trying to create a course
 4680:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4681:         # uri is the requested domain in this case.
 4682:         # comparison to 'request.role.domain' shows if the user has selected
 4683:         # a role of dc for the domain in question.
 4684:         return 'F' if ($uri eq $env{'request.role.domain'});
 4685:     }
 4686: 
 4687:     my $thisallowed='';
 4688:     my $statecond=0;
 4689:     my $courseprivid='';
 4690: 
 4691: # Course
 4692: 
 4693:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4694:        $thisallowed.=$1;
 4695:     }
 4696: 
 4697: # Domain
 4698: 
 4699:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4700:        =~/\Q$priv\E\&([^\:]*)/) {
 4701:        $thisallowed.=$1;
 4702:     }
 4703: 
 4704: # Course: uri itself is a course
 4705:     my $courseuri=$uri;
 4706:     $courseuri=~s/\_(\d)/\/$1/;
 4707:     $courseuri=~s/^([^\/])/\/$1/;
 4708: 
 4709:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 4710:        =~/\Q$priv\E\&([^\:]*)/) {
 4711:        $thisallowed.=$1;
 4712:     }
 4713: 
 4714: # URI is an uploaded document for this course, default permissions don't matter
 4715: # not allowing 'edit' access (editupload) to uploaded course docs
 4716:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 4717: 	$thisallowed='';
 4718:         my ($match)=&is_on_map($uri);
 4719:         if ($match) {
 4720:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 4721:                   =~/\Q$priv\E\&([^\:]*)/) {
 4722:                 $thisallowed.=$1;
 4723:             }
 4724:         } else {
 4725:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 4726:             if ($refuri) {
 4727:                 if ($refuri =~ m|^/adm/|) {
 4728:                     $thisallowed='F';
 4729:                 } else {
 4730:                     $refuri=&declutter($refuri);
 4731:                     my ($match) = &is_on_map($refuri);
 4732:                     if ($match) {
 4733:                         $thisallowed='F';
 4734:                     }
 4735:                 }
 4736:             }
 4737:         }
 4738:     }
 4739: 
 4740:     if ($priv eq 'bre'
 4741: 	&& $thisallowed ne 'F' 
 4742: 	&& $thisallowed ne '2'
 4743: 	&& &is_portfolio_url($uri)) {
 4744: 	$thisallowed = &portfolio_access($uri);
 4745:     }
 4746:     
 4747: # Full access at system, domain or course-wide level? Exit.
 4748:     if ($thisallowed=~/F/) {
 4749: 	return 'F';
 4750:     }
 4751: 
 4752: # If this is generating or modifying users, exit with special codes
 4753: 
 4754:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4755: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4756: 	    my ($audom,$auname)=split('/',$uri);
 4757: # no author name given, so this just checks on the general right to make a co-author in this domain
 4758: 	    unless ($auname) { return $thisallowed; }
 4759: # an author name is given, so we are about to actually make a co-author for a certain account
 4760: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4761: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 4762: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 4763: 	}
 4764: 	return $thisallowed;
 4765:     }
 4766: #
 4767: # Gathered so far: system, domain and course wide privileges
 4768: #
 4769: # Course: See if uri or referer is an individual resource that is part of 
 4770: # the course
 4771: 
 4772:     if ($env{'request.course.id'}) {
 4773: 
 4774:        $courseprivid=$env{'request.course.id'};
 4775:        if ($env{'request.course.sec'}) {
 4776:           $courseprivid.='/'.$env{'request.course.sec'};
 4777:        }
 4778:        $courseprivid=~s/\_/\//;
 4779:        my $checkreferer=1;
 4780:        my ($match,$cond)=&is_on_map($uri);
 4781:        if ($match) {
 4782:            $statecond=$cond;
 4783:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4784:                =~/\Q$priv\E\&([^\:]*)/) {
 4785:                $thisallowed.=$1;
 4786:                $checkreferer=0;
 4787:            }
 4788:        }
 4789:        
 4790:        if ($checkreferer) {
 4791: 	  my $refuri=$env{'httpref.'.$orguri};
 4792:             unless ($refuri) {
 4793:                 foreach my $key (keys(%env)) {
 4794: 		    if ($key=~/^httpref\..*\*/) {
 4795: 			my $pattern=$key;
 4796:                         $pattern=~s/^httpref\.\/res\///;
 4797:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4798:                         $pattern=~s/\//\\\//g;
 4799:                         if ($orguri=~/$pattern/) {
 4800: 			    $refuri=$env{$key};
 4801:                         }
 4802:                     }
 4803:                 }
 4804:             }
 4805: 
 4806:          if ($refuri) { 
 4807: 	  $refuri=&declutter($refuri);
 4808:           my ($match,$cond)=&is_on_map($refuri);
 4809:             if ($match) {
 4810:               my $refstatecond=$cond;
 4811:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4812:                   =~/\Q$priv\E\&([^\:]*)/) {
 4813:                   $thisallowed.=$1;
 4814:                   $uri=$refuri;
 4815:                   $statecond=$refstatecond;
 4816:               }
 4817:           }
 4818:         }
 4819:        }
 4820:    }
 4821: 
 4822: #
 4823: # Gathered now: all privileges that could apply, and condition number
 4824: # 
 4825: #
 4826: # Full or no access?
 4827: #
 4828: 
 4829:     if ($thisallowed=~/F/) {
 4830: 	return 'F';
 4831:     }
 4832: 
 4833:     unless ($thisallowed) {
 4834:         return '';
 4835:     }
 4836: 
 4837: # Restrictions exist, deal with them
 4838: #
 4839: #   C:according to course preferences
 4840: #   R:according to resource settings
 4841: #   L:unless locked
 4842: #   X:according to user session state
 4843: #
 4844: 
 4845: # Possibly locked functionality, check all courses
 4846: # Locks might take effect only after 10 minutes cache expiration for other
 4847: # courses, and 2 minutes for current course
 4848: 
 4849:     my $envkey;
 4850:     if ($thisallowed=~/L/) {
 4851:         foreach $envkey (keys %env) {
 4852:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 4853:                my $courseid=$2;
 4854:                my $roleid=$1.'.'.$2;
 4855:                $courseid=~s/^\///;
 4856:                my $expiretime=600;
 4857:                if ($env{'request.role'} eq $roleid) {
 4858: 		  $expiretime=120;
 4859:                }
 4860: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 4861:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 4862:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 4863: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 4864:                }
 4865:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4866:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4867: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4868:                        &log($env{'user.domain'},$env{'user.name'},
 4869:                             $env{'user.home'},
 4870:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4871:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4872:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4873: 		       return '';
 4874:                    }
 4875:                }
 4876:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4877:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4878: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4879:                        &log($env{'user.domain'},$env{'user.name'},
 4880:                             $env{'user.home'},
 4881:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4882:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4883:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4884: 		       return '';
 4885:                    }
 4886:                }
 4887: 	   }
 4888:        }
 4889:     }
 4890:    
 4891: #
 4892: # Rest of the restrictions depend on selected course
 4893: #
 4894: 
 4895:     unless ($env{'request.course.id'}) {
 4896: 	if ($thisallowed eq 'A') {
 4897: 	    return 'A';
 4898:         } elsif ($thisallowed eq 'B') {
 4899:             return 'B';
 4900: 	} else {
 4901: 	    return '1';
 4902: 	}
 4903:     }
 4904: 
 4905: #
 4906: # Now user is definitely in a course
 4907: #
 4908: 
 4909: 
 4910: # Course preferences
 4911: 
 4912:    if ($thisallowed=~/C/) {
 4913:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4914:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4915:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4916: 	   =~/\Q$rolecode\E/) {
 4917: 	   if ($priv ne 'pch') { 
 4918: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4919: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4920: 			$env{'request.course.id'});
 4921: 	   }
 4922:            return '';
 4923:        }
 4924: 
 4925:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4926: 	   =~/\Q$unamedom\E/) {
 4927: 	   if ($priv ne 'pch') { 
 4928: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4929: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4930: 			$env{'request.course.id'});
 4931: 	   }
 4932:            return '';
 4933:        }
 4934:    }
 4935: 
 4936: # Resource preferences
 4937: 
 4938:    if ($thisallowed=~/R/) {
 4939:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4940:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4941: 	   if ($priv ne 'pch') { 
 4942: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4943: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4944: 	   }
 4945: 	   return '';
 4946:        }
 4947:    }
 4948: 
 4949: # Restricted by state or randomout?
 4950: 
 4951:    if ($thisallowed=~/X/) {
 4952:       if ($env{'acc.randomout'}) {
 4953: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4954:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4955:             return ''; 
 4956:          }
 4957:       }
 4958:       if (&condval($statecond)) {
 4959: 	 return '2';
 4960:       } else {
 4961:          return '';
 4962:       }
 4963:    }
 4964: 
 4965:     if ($thisallowed eq 'A') {
 4966: 	return 'A';
 4967:     } elsif ($thisallowed eq 'B') {
 4968:         return 'B';
 4969:     }
 4970:    return 'F';
 4971: }
 4972: 
 4973: sub split_uri_for_cond {
 4974:     my $uri=&deversion(&declutter(shift));
 4975:     my @uriparts=split(/\//,$uri);
 4976:     my $filename=pop(@uriparts);
 4977:     my $pathname=join('/',@uriparts);
 4978:     return ($pathname,$filename);
 4979: }
 4980: # --------------------------------------------------- Is a resource on the map?
 4981: 
 4982: sub is_on_map {
 4983:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 4984:     #Trying to find the conditional for the file
 4985:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 4986: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 4987:     if ($match) {
 4988: 	return (1,$1);
 4989:     } else {
 4990: 	return (0,0);
 4991:     }
 4992: }
 4993: 
 4994: # --------------------------------------------------------- Get symb from alias
 4995: 
 4996: sub get_symb_from_alias {
 4997:     my $symb=shift;
 4998:     my ($map,$resid,$url)=&decode_symb($symb);
 4999: # Already is a symb
 5000:     if ($url) { return $symb; }
 5001: # Must be an alias
 5002:     my $aliassymb='';
 5003:     my %bighash;
 5004:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5005:                             &GDBM_READER(),0640)) {
 5006:         my $rid=$bighash{'mapalias_'.$symb};
 5007: 	if ($rid) {
 5008: 	    my ($mapid,$resid)=split(/\./,$rid);
 5009: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 5010: 				    $resid,$bighash{'src_'.$rid});
 5011: 	}
 5012:         untie %bighash;
 5013:     }
 5014:     return $aliassymb;
 5015: }
 5016: 
 5017: # ----------------------------------------------------------------- Define Role
 5018: 
 5019: sub definerole {
 5020:   if (allowed('mcr','/')) {
 5021:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 5022:     foreach my $role (split(':',$sysrole)) {
 5023: 	my ($crole,$cqual)=split(/\&/,$role);
 5024:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 5025:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 5026: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5027:                return "refused:s:$crole&$cqual"; 
 5028:             }
 5029:         }
 5030:     }
 5031:     foreach my $role (split(':',$domrole)) {
 5032: 	my ($crole,$cqual)=split(/\&/,$role);
 5033:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 5034:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 5035: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 5036:                return "refused:d:$crole&$cqual"; 
 5037:             }
 5038:         }
 5039:     }
 5040:     foreach my $role (split(':',$courole)) {
 5041: 	my ($crole,$cqual)=split(/\&/,$role);
 5042:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 5043:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 5044: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5045:                return "refused:c:$crole&$cqual"; 
 5046:             }
 5047:         }
 5048:     }
 5049:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5050:                 "$env{'user.domain'}:$env{'user.name'}:".
 5051: 	        "rolesdef_$rolename=".
 5052:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 5053:     return reply($command,$env{'user.home'});
 5054:   } else {
 5055:     return 'refused';
 5056:   }
 5057: }
 5058: 
 5059: # ---------------- Make a metadata query against the network of library servers
 5060: 
 5061: sub metadata_query {
 5062:     my ($query,$custom,$customshow,$server_array)=@_;
 5063:     my %rhash;
 5064:     my %libserv = &all_library();
 5065:     my @server_list = (defined($server_array) ? @$server_array
 5066:                                               : keys(%libserv) );
 5067:     for my $server (@server_list) {
 5068: 	unless ($custom or $customshow) {
 5069: 	    my $reply=&reply("querysend:".&escape($query),$server);
 5070: 	    $rhash{$server}=$reply;
 5071: 	}
 5072: 	else {
 5073: 	    my $reply=&reply("querysend:".&escape($query).':'.
 5074: 			     &escape($custom).':'.&escape($customshow),
 5075: 			     $server);
 5076: 	    $rhash{$server}=$reply;
 5077: 	}
 5078:     }
 5079:     return \%rhash;
 5080: }
 5081: 
 5082: # ----------------------------------------- Send log queries and wait for reply
 5083: 
 5084: sub log_query {
 5085:     my ($uname,$udom,$query,%filters)=@_;
 5086:     my $uhome=&homeserver($uname,$udom);
 5087:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 5088:     my $uhost=&hostname($uhome);
 5089:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 5090:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 5091:                        $uhome);
 5092:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 5093:     return get_query_reply($queryid);
 5094: }
 5095: 
 5096: # -------------------------- Update MySQL table for portfolio file
 5097: 
 5098: sub update_portfolio_table {
 5099:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 5100:     if ($group ne '') {
 5101:         $file_name =~s /^\Q$group\E//;
 5102:     }
 5103:     my $homeserver = &homeserver($uname,$udom);
 5104:     my $queryid=
 5105:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 5106:                ':'.&escape($file_name).':'.$action,$homeserver);
 5107:     my $reply = &get_query_reply($queryid);
 5108:     return $reply;
 5109: }
 5110: 
 5111: # -------------------------- Update MySQL allusers table
 5112: 
 5113: sub update_allusers_table {
 5114:     my ($uname,$udom,$names) = @_;
 5115:     my $homeserver = &homeserver($uname,$udom);
 5116:     my $queryid=
 5117:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 5118:                'lastname='.&escape($names->{'lastname'}).'%%'.
 5119:                'firstname='.&escape($names->{'firstname'}).'%%'.
 5120:                'middlename='.&escape($names->{'middlename'}).'%%'.
 5121:                'generation='.&escape($names->{'generation'}).'%%'.
 5122:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 5123:                'id='.&escape($names->{'id'}),$homeserver);
 5124:     my $reply = &get_query_reply($queryid);
 5125:     return $reply;
 5126: }
 5127: 
 5128: # ------- Request retrieval of institutional classlists for course(s)
 5129: 
 5130: sub fetch_enrollment_query {
 5131:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 5132:     my $homeserver;
 5133:     my $maxtries = 1;
 5134:     if ($context eq 'automated') {
 5135:         $homeserver = $perlvar{'lonHostID'};
 5136:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 5137:     } else {
 5138:         $homeserver = &homeserver($cnum,$dom);
 5139:     }
 5140:     my $host=&hostname($homeserver);
 5141:     my $cmd = '';
 5142:     foreach my $affiliate (keys %{$affiliatesref}) {
 5143:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5144:     }
 5145:     $cmd =~ s/%%$//;
 5146:     $cmd = &escape($cmd);
 5147:     my $query = 'fetchenrollment';
 5148:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 5149:     unless ($queryid=~/^\Q$host\E\_/) { 
 5150:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 5151:         return 'error: '.$queryid;
 5152:     }
 5153:     my $reply = &get_query_reply($queryid);
 5154:     my $tries = 1;
 5155:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5156:         $reply = &get_query_reply($queryid);
 5157:         $tries ++;
 5158:     }
 5159:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5160:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5161:     } else {
 5162:         my @responses = split(/:/,$reply);
 5163:         if ($homeserver eq $perlvar{'lonHostID'}) {
 5164:             foreach my $line (@responses) {
 5165:                 my ($key,$value) = split(/=/,$line,2);
 5166:                 $$replyref{$key} = $value;
 5167:             }
 5168:         } else {
 5169:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 5170:             foreach my $line (@responses) {
 5171:                 my ($key,$value) = split(/=/,$line);
 5172:                 $$replyref{$key} = $value;
 5173:                 if ($value > 0) {
 5174:                     foreach my $item (@{$$affiliatesref{$key}}) {
 5175:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 5176:                         my $destname = $pathname.'/'.$filename;
 5177:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 5178:                         if ($xml_classlist =~ /^error/) {
 5179:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 5180:                         } else {
 5181:                             if ( open(FILE,">$destname") ) {
 5182:                                 print FILE &unescape($xml_classlist);
 5183:                                 close(FILE);
 5184:                             } else {
 5185:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 5186:                             }
 5187:                         }
 5188:                     }
 5189:                 }
 5190:             }
 5191:         }
 5192:         return 'ok';
 5193:     }
 5194:     return 'error';
 5195: }
 5196: 
 5197: sub get_query_reply {
 5198:     my $queryid=shift;
 5199:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 5200:     my $reply='';
 5201:     for (1..100) {
 5202: 	sleep 2;
 5203:         if (-e $replyfile.'.end') {
 5204: 	    if (open(my $fh,$replyfile)) {
 5205: 		$reply = join('',<$fh>);
 5206: 		close($fh);
 5207: 	   } else { return 'error: reply_file_error'; }
 5208:            return &unescape($reply);
 5209: 	}
 5210:     }
 5211:     return 'timeout:'.$queryid;
 5212: }
 5213: 
 5214: sub courselog_query {
 5215: #
 5216: # possible filters:
 5217: # url: url or symb
 5218: # username
 5219: # domain
 5220: # action: view, submit, grade
 5221: # start: timestamp
 5222: # end: timestamp
 5223: #
 5224:     my (%filters)=@_;
 5225:     unless ($env{'request.course.id'}) { return 'no_course'; }
 5226:     if ($filters{'url'}) {
 5227: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 5228:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 5229:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 5230:     }
 5231:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5232:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5233:     return &log_query($cname,$cdom,'courselog',%filters);
 5234: }
 5235: 
 5236: sub userlog_query {
 5237: #
 5238: # possible filters:
 5239: # action: log check role
 5240: # start: timestamp
 5241: # end: timestamp
 5242: #
 5243:     my ($uname,$udom,%filters)=@_;
 5244:     return &log_query($uname,$udom,'userlog',%filters);
 5245: }
 5246: 
 5247: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 5248: 
 5249: sub auto_run {
 5250:     my ($cnum,$cdom) = @_;
 5251:     my $response = 0;
 5252:     my $settings;
 5253:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 5254:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5255:         $settings = $domconfig{'autoenroll'};
 5256:         if ($settings->{'run'} eq '1') {
 5257:             $response = 1;
 5258:         }
 5259:     } else {
 5260:         my $homeserver;
 5261:         if (&is_course($cdom,$cnum)) {
 5262:             $homeserver = &homeserver($cnum,$cdom);
 5263:         } else {
 5264:             $homeserver = &domain($cdom,'primary');
 5265:         }
 5266:         if ($homeserver ne 'no_host') {
 5267:             $response = &reply('autorun:'.$cdom,$homeserver);
 5268:         }
 5269:     }
 5270:     return $response;
 5271: }
 5272: 
 5273: sub auto_get_sections {
 5274:     my ($cnum,$cdom,$inst_coursecode) = @_;
 5275:     my $homeserver = &homeserver($cnum,$cdom);
 5276:     my @secs = ();
 5277:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 5278:     unless ($response eq 'refused') {
 5279:         @secs = split(/:/,$response);
 5280:     }
 5281:     return @secs;
 5282: }
 5283: 
 5284: sub auto_new_course {
 5285:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 5286:     my $homeserver = &homeserver($cnum,$cdom);
 5287:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 5288:     return $response;
 5289: }
 5290: 
 5291: sub auto_validate_courseID {
 5292:     my ($cnum,$cdom,$inst_course_id) = @_;
 5293:     my $homeserver = &homeserver($cnum,$cdom);
 5294:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5295:     return $response;
 5296: }
 5297: 
 5298: sub auto_create_password {
 5299:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5300:     my ($homeserver,$response);
 5301:     my $create_passwd = 0;
 5302:     my $authchk = '';
 5303:     if ($udom =~ /^$match_domain$/) {
 5304:         $homeserver = &domain($udom,'primary');
 5305:     }
 5306:     if ($homeserver eq '') {
 5307:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5308:             $homeserver = &homeserver($cnum,$cdom);
 5309:         }
 5310:     }
 5311:     if ($homeserver eq '') {
 5312:         $authchk = 'nodomain';
 5313:     } else {
 5314:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5315:         if ($response eq 'refused') {
 5316:             $authchk = 'refused';
 5317:         } else {
 5318:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5319:         }
 5320:     }
 5321:     return ($authparam,$create_passwd,$authchk);
 5322: }
 5323: 
 5324: sub auto_photo_permission {
 5325:     my ($cnum,$cdom,$students) = @_;
 5326:     my $homeserver = &homeserver($cnum,$cdom);
 5327:     my ($outcome,$perm_reqd,$conditions) = 
 5328: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5329:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5330: 	return (undef,undef);
 5331:     }
 5332:     return ($outcome,$perm_reqd,$conditions);
 5333: }
 5334: 
 5335: sub auto_checkphotos {
 5336:     my ($uname,$udom,$pid) = @_;
 5337:     my $homeserver = &homeserver($uname,$udom);
 5338:     my ($result,$resulttype);
 5339:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5340: 				   &escape($uname).':'.&escape($pid),
 5341: 				   $homeserver));
 5342:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5343: 	return (undef,undef);
 5344:     }
 5345:     if ($outcome) {
 5346:         ($result,$resulttype) = split(/:/,$outcome);
 5347:     } 
 5348:     return ($result,$resulttype);
 5349: }
 5350: 
 5351: sub auto_photochoice {
 5352:     my ($cnum,$cdom) = @_;
 5353:     my $homeserver = &homeserver($cnum,$cdom);
 5354:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5355: 						       &escape($cdom),
 5356: 						       $homeserver)));
 5357:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5358: 	return (undef,undef);
 5359:     }
 5360:     return ($update,$comment);
 5361: }
 5362: 
 5363: sub auto_photoupdate {
 5364:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5365:     my $homeserver = &homeserver($cnum,$dom);
 5366:     my $host=&hostname($homeserver);
 5367:     my $cmd = '';
 5368:     my $maxtries = 1;
 5369:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5370:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5371:     }
 5372:     $cmd =~ s/%%$//;
 5373:     $cmd = &escape($cmd);
 5374:     my $query = 'institutionalphotos';
 5375:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5376:     unless ($queryid=~/^\Q$host\E\_/) {
 5377:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5378:         return 'error: '.$queryid;
 5379:     }
 5380:     my $reply = &get_query_reply($queryid);
 5381:     my $tries = 1;
 5382:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5383:         $reply = &get_query_reply($queryid);
 5384:         $tries ++;
 5385:     }
 5386:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5387:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5388:     } else {
 5389:         my @responses = split(/:/,$reply);
 5390:         my $outcome = shift(@responses); 
 5391:         foreach my $item (@responses) {
 5392:             my ($key,$value) = split(/=/,$item);
 5393:             $$photo{$key} = $value;
 5394:         }
 5395:         return $outcome;
 5396:     }
 5397:     return 'error';
 5398: }
 5399: 
 5400: sub auto_instcode_format {
 5401:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5402: 	$cat_order) = @_;
 5403:     my $courses = '';
 5404:     my @homeservers;
 5405:     if ($caller eq 'global') {
 5406: 	my %servers = &get_servers($codedom,'library');
 5407: 	foreach my $tryserver (keys(%servers)) {
 5408: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5409: 		push(@homeservers,$tryserver);
 5410: 	    }
 5411:         }
 5412:     } else {
 5413:         push(@homeservers,&homeserver($caller,$codedom));
 5414:     }
 5415:     foreach my $code (keys(%{$instcodes})) {
 5416:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5417:     }
 5418:     chop($courses);
 5419:     my $ok_response = 0;
 5420:     my $response;
 5421:     while (@homeservers > 0 && $ok_response == 0) {
 5422:         my $server = shift(@homeservers); 
 5423:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5424:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5425:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5426: 		split(/:/,$response);
 5427:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5428:             push(@{$codetitles},&str2array($codetitles_str));
 5429:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5430:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5431:             $ok_response = 1;
 5432:         }
 5433:     }
 5434:     if ($ok_response) {
 5435:         return 'ok';
 5436:     } else {
 5437:         return $response;
 5438:     }
 5439: }
 5440: 
 5441: sub auto_instcode_defaults {
 5442:     my ($domain,$returnhash,$code_order) = @_;
 5443:     my @homeservers;
 5444: 
 5445:     my %servers = &get_servers($domain,'library');
 5446:     foreach my $tryserver (keys(%servers)) {
 5447: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5448: 	    push(@homeservers,$tryserver);
 5449: 	}
 5450:     }
 5451: 
 5452:     my $response;
 5453:     foreach my $server (@homeservers) {
 5454:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5455:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5456: 	
 5457: 	foreach my $pair (split(/\&/,$response)) {
 5458: 	    my ($name,$value)=split(/\=/,$pair);
 5459: 	    if ($name eq 'code_order') {
 5460: 		@{$code_order} = split(/\&/,&unescape($value));
 5461: 	    } else {
 5462: 		$returnhash->{&unescape($name)}=&unescape($value);
 5463: 	    }
 5464: 	}
 5465: 	return 'ok';
 5466:     }
 5467: 
 5468:     return $response;
 5469: } 
 5470: 
 5471: sub auto_validate_class_sec {
 5472:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5473:     my $homeserver = &homeserver($cnum,$cdom);
 5474:     my $ownerlist;
 5475:     if (ref($owners) eq 'ARRAY') {
 5476:         $ownerlist = join(',',@{$owners});
 5477:     } else {
 5478:         $ownerlist = $owners;
 5479:     }
 5480:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 5481:                         &escape($ownerlist).':'.$cdom,$homeserver);
 5482:     return $response;
 5483: }
 5484: 
 5485: # ------------------------------------------------------- Course Group routines
 5486: 
 5487: sub get_coursegroups {
 5488:     my ($cdom,$cnum,$group,$namespace) = @_;
 5489:     return(&dump($namespace,$cdom,$cnum,$group));
 5490: }
 5491: 
 5492: sub modify_coursegroup {
 5493:     my ($cdom,$cnum,$groupsettings) = @_;
 5494:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 5495: }
 5496: 
 5497: sub toggle_coursegroup_status {
 5498:     my ($cdom,$cnum,$group,$action) = @_;
 5499:     my ($from_namespace,$to_namespace);
 5500:     if ($action eq 'delete') {
 5501:         $from_namespace = 'coursegroups';
 5502:         $to_namespace = 'deleted_groups';
 5503:     } else {
 5504:         $from_namespace = 'deleted_groups';
 5505:         $to_namespace = 'coursegroups';
 5506:     }
 5507:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 5508:     if (my $tmp = &error(%curr_group)) {
 5509:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 5510:         return ('read error',$tmp);
 5511:     } else {
 5512:         my %savedsettings = %curr_group; 
 5513:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 5514:         my $deloutcome;
 5515:         if ($result eq 'ok') {
 5516:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 5517:         } else {
 5518:             return ('write error',$result);
 5519:         }
 5520:         if ($deloutcome eq 'ok') {
 5521:             return 'ok';
 5522:         } else {
 5523:             return ('delete error',$deloutcome);
 5524:         }
 5525:     }
 5526: }
 5527: 
 5528: sub modify_group_roles {
 5529:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 5530:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 5531:     my $role = 'gr/'.&escape($userprivs);
 5532:     my ($uname,$udom) = split(/:/,$user);
 5533:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 5534:     if ($result eq 'ok') {
 5535:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 5536:     }
 5537:     return $result;
 5538: }
 5539: 
 5540: sub modify_coursegroup_membership {
 5541:     my ($cdom,$cnum,$membership) = @_;
 5542:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 5543:     return $result;
 5544: }
 5545: 
 5546: sub get_active_groups {
 5547:     my ($udom,$uname,$cdom,$cnum) = @_;
 5548:     my $now = time;
 5549:     my %groups = ();
 5550:     foreach my $key (keys(%env)) {
 5551:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 5552:             my ($start,$end) = split(/\./,$env{$key});
 5553:             if (($end!=0) && ($end<$now)) { next; }
 5554:             if (($start!=0) && ($start>$now)) { next; }
 5555:             if ($1 eq $cdom && $2 eq $cnum) {
 5556:                 $groups{$3} = $env{$key} ;
 5557:             }
 5558:         }
 5559:     }
 5560:     return %groups;
 5561: }
 5562: 
 5563: sub get_group_membership {
 5564:     my ($cdom,$cnum,$group) = @_;
 5565:     return(&dump('groupmembership',$cdom,$cnum,$group));
 5566: }
 5567: 
 5568: sub get_users_groups {
 5569:     my ($udom,$uname,$courseid) = @_;
 5570:     my @usersgroups;
 5571:     my $cachetime=1800;
 5572: 
 5573:     my $hashid="$udom:$uname:$courseid";
 5574:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 5575:     if (defined($cached)) {
 5576:         @usersgroups = split(/:/,$grouplist);
 5577:     } else {  
 5578:         $grouplist = '';
 5579:         my $courseurl = &courseid_to_courseurl($courseid);
 5580:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 5581:         my $access_end = $env{'course.'.$courseid.
 5582:                               '.default_enrollment_end_date'};
 5583:         my $now = time;
 5584:         foreach my $key (keys(%roleshash)) {
 5585:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 5586:                 my $group = $1;
 5587:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 5588:                     my $start = $2;
 5589:                     my $end = $1;
 5590:                     if ($start == -1) { next; } # deleted from group
 5591:                     if (($start!=0) && ($start>$now)) { next; }
 5592:                     if (($end!=0) && ($end<$now)) {
 5593:                         if ($access_end && $access_end < $now) {
 5594:                             if ($access_end - $end < 86400) {
 5595:                                 push(@usersgroups,$group);
 5596:                             }
 5597:                         }
 5598:                         next;
 5599:                     }
 5600:                     push(@usersgroups,$group);
 5601:                 }
 5602:             }
 5603:         }
 5604:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 5605:         $grouplist = join(':',@usersgroups);
 5606:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 5607:     }
 5608:     return @usersgroups;
 5609: }
 5610: 
 5611: sub devalidate_getgroups_cache {
 5612:     my ($udom,$uname,$cdom,$cnum)=@_;
 5613:     my $courseid = $cdom.'_'.$cnum;
 5614: 
 5615:     my $hashid="$udom:$uname:$courseid";
 5616:     &devalidate_cache_new('getgroups',$hashid);
 5617: }
 5618: 
 5619: # ------------------------------------------------------------------ Plain Text
 5620: 
 5621: sub plaintext {
 5622:     my ($short,$type,$cid) = @_;
 5623:     if ($short =~ /^cr/) {
 5624: 	return (split('/',$short))[-1];
 5625:     }
 5626:     if (!defined($cid)) {
 5627:         $cid = $env{'request.course.id'};
 5628:     }
 5629:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 5630:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 5631:                                           '.plaintext'});
 5632:     }
 5633:     my %rolenames = (
 5634:                       Course => 'std',
 5635:                       Group => 'alt1',
 5636:                     );
 5637:     if (defined($type) && 
 5638:          defined($rolenames{$type}) && 
 5639:          defined($prp{$short}{$rolenames{$type}})) {
 5640:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 5641:     } else {
 5642:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 5643:     }
 5644: }
 5645: 
 5646: # ----------------------------------------------------------------- Assign Role
 5647: 
 5648: sub assignrole {
 5649:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 5650:         $context)=@_;
 5651:     my $mrole;
 5652:     if ($role =~ /^cr\//) {
 5653:         my $cwosec=$url;
 5654:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5655: 	unless (&allowed('ccr',$cwosec)) {
 5656:            &logthis('Refused custom assignrole: '.
 5657:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5658: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 5659:            return 'refused'; 
 5660:         }
 5661:         $mrole='cr';
 5662:     } elsif ($role =~ /^gr\//) {
 5663:         my $cwogrp=$url;
 5664:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 5665:         unless (&allowed('mdg',$cwogrp)) {
 5666:             &logthis('Refused group assignrole: '.
 5667:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5668:                     $env{'user.name'}.' at '.$env{'user.domain'});
 5669:             return 'refused';
 5670:         }
 5671:         $mrole='gr';
 5672:     } else {
 5673:         my $cwosec=$url;
 5674:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5675:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 5676:             my $refused;
 5677:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 5678:                 if (!(&allowed('c'.$role,$url))) {
 5679:                     $refused = 1;
 5680:                 }
 5681:             } else {
 5682:                 $refused = 1;
 5683:             }
 5684:             if ($refused) {
 5685:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5686:                     $refused = '';
 5687:                 } else {
 5688:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 5689:                              ' '.$role.' '.$end.' '.$start.' by '.
 5690: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 5691:                     return 'refused';
 5692:                 }
 5693:             }
 5694:         }
 5695:         $mrole=$role;
 5696:     }
 5697:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5698:                 "$udom:$uname:$url".'_'."$mrole=$role";
 5699:     if ($end) { $command.='_'.$end; }
 5700:     if ($start) {
 5701: 	if ($end) { 
 5702:            $command.='_'.$start; 
 5703:         } else {
 5704:            $command.='_0_'.$start;
 5705:         }
 5706:     }
 5707:     my $origstart = $start;
 5708:     my $origend = $end;
 5709:     my $delflag;
 5710: # actually delete
 5711:     if ($deleteflag) {
 5712: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 5713: # modify command to delete the role
 5714:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 5715:                 "$udom:$uname:$url".'_'."$mrole";
 5716: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 5717: # set start and finish to negative values for userrolelog
 5718:            $start=-1;
 5719:            $end=-1;
 5720:            $delflag = 1;
 5721:         }
 5722:     }
 5723: # send command
 5724:     my $answer=&reply($command,&homeserver($uname,$udom));
 5725: # log new user role if status is ok
 5726:     if ($answer eq 'ok') {
 5727: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 5728: # for course roles, perform group memberships changes triggered by role change.
 5729:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 5730:         unless ($role =~ /^gr/) {
 5731:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 5732:                                              $origstart,$selfenroll,$context);
 5733:         }
 5734:     }
 5735:     return $answer;
 5736: }
 5737: 
 5738: # -------------------------------------------------- Modify user authentication
 5739: # Overrides without validation
 5740: 
 5741: sub modifyuserauth {
 5742:     my ($udom,$uname,$umode,$upass)=@_;
 5743:     my $uhome=&homeserver($uname,$udom);
 5744:     unless (&allowed('mau',$udom)) { return 'refused'; }
 5745:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 5746:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5747:              ' in domain '.$env{'request.role.domain'});  
 5748:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 5749: 		     &escape($upass),$uhome);
 5750:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 5751:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 5752:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5753:     &log($udom,,$uname,$uhome,
 5754:         'Authentication changed by '.$env{'user.domain'}.', '.
 5755:                                      $env{'user.name'}.', '.$umode.
 5756:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5757:     unless ($reply eq 'ok') {
 5758:         &logthis('Authentication mode error: '.$reply);
 5759: 	return 'error: '.$reply;
 5760:     }   
 5761:     return 'ok';
 5762: }
 5763: 
 5764: # --------------------------------------------------------------- Modify a user
 5765: 
 5766: sub modifyuser {
 5767:     my ($udom,    $uname, $uid,
 5768:         $umode,   $upass, $first,
 5769:         $middle,  $last,  $gene,
 5770:         $forceid, $desiredhome, $email, $inststatus)=@_;
 5771:     $udom= &LONCAPA::clean_domain($udom);
 5772:     $uname=&LONCAPA::clean_username($uname);
 5773:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 5774:              $umode.', '.$first.', '.$middle.', '.
 5775: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 5776:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 5777:                                      ' desiredhome not specified'). 
 5778:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5779:              ' in domain '.$env{'request.role.domain'});
 5780:     my $uhome=&homeserver($uname,$udom,'true');
 5781: # ----------------------------------------------------------------- Create User
 5782:     if (($uhome eq 'no_host') && 
 5783: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 5784:         my $unhome='';
 5785:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 5786:             $unhome = $desiredhome;
 5787: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 5788: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 5789:         } else { # load balancing routine for determining $unhome
 5790:             my $loadm=10000000;
 5791: 	    my %servers = &get_servers($udom,'library');
 5792: 	    foreach my $tryserver (keys(%servers)) {
 5793: 		my $answer=reply('load',$tryserver);
 5794: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 5795: 		    $loadm=$answer;
 5796: 		    $unhome=$tryserver;
 5797: 		}
 5798: 	    }
 5799:         }
 5800:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 5801: 	    return 'error: unable to find a home server for '.$uname.
 5802:                    ' in domain '.$udom;
 5803:         }
 5804:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 5805:                          &escape($upass),$unhome);
 5806: 	unless ($reply eq 'ok') {
 5807:             return 'error: '.$reply;
 5808:         }   
 5809:         $uhome=&homeserver($uname,$udom,'true');
 5810:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 5811: 	    return 'error: unable verify users home machine.';
 5812:         }
 5813:     }   # End of creation of new user
 5814: # ---------------------------------------------------------------------- Add ID
 5815:     if ($uid) {
 5816:        $uid=~tr/A-Z/a-z/;
 5817:        my %uidhash=&idrget($udom,$uname);
 5818:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 5819:          && (!$forceid)) {
 5820: 	  unless ($uid eq $uidhash{$uname}) {
 5821: 	      return 'error: user id "'.$uid.'" does not match '.
 5822:                   'current user id "'.$uidhash{$uname}.'".';
 5823:           }
 5824:        } else {
 5825: 	  &idput($udom,($uname => $uid));
 5826:        }
 5827:     }
 5828: # -------------------------------------------------------------- Add names, etc
 5829:     my @tmp=&get('environment',
 5830: 		   ['firstname','middlename','lastname','generation','id',
 5831:                     'permanentemail','inststatus'],
 5832: 		   $udom,$uname);
 5833:     my %names;
 5834:     if ($tmp[0] =~ m/^error:.*/) { 
 5835:         %names=(); 
 5836:     } else {
 5837:         %names = @tmp;
 5838:     }
 5839: #
 5840: # Make sure to not trash student environment if instructor does not bother
 5841: # to supply name and email information
 5842: #
 5843:     if ($first)  { $names{'firstname'}  = $first; }
 5844:     if (defined($middle)) { $names{'middlename'} = $middle; }
 5845:     if ($last)   { $names{'lastname'}   = $last; }
 5846:     if (defined($gene))   { $names{'generation'} = $gene; }
 5847:     if ($email) {
 5848:        $email=~s/[^\w\@\.\-\,]//gs;
 5849:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 5850:     }
 5851:     if ($uid) { $names{'id'}  = $uid; }
 5852:     if (defined($inststatus)) { $names{'inststatus'} = $inststatus; } 
 5853:     my $reply = &put('environment', \%names, $udom,$uname);
 5854:     if ($reply ne 'ok') { return 'error: '.$reply; }
 5855:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 5856:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 5857:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 5858:                  $umode.', '.$first.', '.$middle.', '.
 5859: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
 5860:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 5861:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 5862:     } else {
 5863:         $logmsg .= ' during self creation';
 5864:     }
 5865:     &logthis($logmsg);
 5866:     return 'ok';
 5867: }
 5868: 
 5869: # -------------------------------------------------------------- Modify student
 5870: 
 5871: sub modifystudent {
 5872:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 5873:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 5874:         $selfenroll,$context)=@_;
 5875:     if (!$cid) {
 5876: 	unless ($cid=$env{'request.course.id'}) {
 5877: 	    return 'not_in_class';
 5878: 	}
 5879:     }
 5880: # --------------------------------------------------------------- Make the user
 5881:     my $reply=&modifyuser
 5882: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 5883:          $desiredhome,$email);
 5884:     unless ($reply eq 'ok') { return $reply; }
 5885:     # This will cause &modify_student_enrollment to get the uid from the
 5886:     # students environment
 5887:     $uid = undef if (!$forceid);
 5888:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 5889: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 5890:     return $reply;
 5891: }
 5892: 
 5893: sub modify_student_enrollment {
 5894:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 5895:     my ($cdom,$cnum,$chome);
 5896:     if (!$cid) {
 5897: 	unless ($cid=$env{'request.course.id'}) {
 5898: 	    return 'not_in_class';
 5899: 	}
 5900: 	$cdom=$env{'course.'.$cid.'.domain'};
 5901: 	$cnum=$env{'course.'.$cid.'.num'};
 5902:     } else {
 5903: 	($cdom,$cnum)=split(/_/,$cid);
 5904:     }
 5905:     $chome=$env{'course.'.$cid.'.home'};
 5906:     if (!$chome) {
 5907: 	$chome=&homeserver($cnum,$cdom);
 5908:     }
 5909:     if (!$chome) { return 'unknown_course'; }
 5910:     # Make sure the user exists
 5911:     my $uhome=&homeserver($uname,$udom);
 5912:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5913: 	return 'error: no such user';
 5914:     }
 5915:     # Get student data if we were not given enough information
 5916:     if (!defined($first)  || $first  eq '' || 
 5917:         !defined($last)   || $last   eq '' || 
 5918:         !defined($uid)    || $uid    eq '' || 
 5919:         !defined($middle) || $middle eq '' || 
 5920:         !defined($gene)   || $gene   eq '') {
 5921:         # They did not supply us with enough data to enroll the student, so
 5922:         # we need to pick up more information.
 5923:         my %tmp = &get('environment',
 5924:                        ['firstname','middlename','lastname', 'generation','id']
 5925:                        ,$udom,$uname);
 5926: 
 5927:         #foreach my $key (keys(%tmp)) {
 5928:         #    &logthis("key $key = ".$tmp{$key});
 5929:         #}
 5930:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 5931:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 5932:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 5933:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 5934:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 5935:     }
 5936:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 5937:     my $reply=cput('classlist',
 5938: 		   {"$uname:$udom" => 
 5939: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 5940: 		   $cdom,$cnum);
 5941:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 5942: 	return 'error: '.$reply;
 5943:     } else {
 5944: 	&devalidate_getsection_cache($udom,$uname,$cid);
 5945:     }
 5946:     # Add student role to user
 5947:     my $uurl='/'.$cid;
 5948:     $uurl=~s/\_/\//g;
 5949:     if ($usec) {
 5950: 	$uurl.='/'.$usec;
 5951:     }
 5952:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 5953: }
 5954: 
 5955: sub format_name {
 5956:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 5957:     my $name;
 5958:     if ($first ne 'lastname') {
 5959: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 5960:     } else {
 5961: 	if ($lastname=~/\S/) {
 5962: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 5963: 	    $name=~s/\s+,/,/;
 5964: 	} else {
 5965: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 5966: 	}
 5967:     }
 5968:     $name=~s/^\s+//;
 5969:     $name=~s/\s+$//;
 5970:     $name=~s/\s+/ /g;
 5971:     return $name;
 5972: }
 5973: 
 5974: # ------------------------------------------------- Write to course preferences
 5975: 
 5976: sub writecoursepref {
 5977:     my ($courseid,%prefs)=@_;
 5978:     $courseid=~s/^\///;
 5979:     $courseid=~s/\_/\//g;
 5980:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5981:     my $chome=homeserver($cnum,$cdomain);
 5982:     if (($chome eq '') || ($chome eq 'no_host')) { 
 5983: 	return 'error: no such course';
 5984:     }
 5985:     my $cstring='';
 5986:     foreach my $pref (keys(%prefs)) {
 5987: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 5988:     }
 5989:     $cstring=~s/\&$//;
 5990:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 5991: }
 5992: 
 5993: # ---------------------------------------------------------- Make/modify course
 5994: 
 5995: sub createcourse {
 5996:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 5997:         $course_owner,$crstype)=@_;
 5998:     $url=&declutter($url);
 5999:     my $cid='';
 6000:     unless (&allowed('ccc',$udom)) {
 6001:         return 'refused';
 6002:     }
 6003: # ------------------------------------------------------------------- Create ID
 6004:    my $uname=int(1+rand(9)).
 6005:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6006:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6007:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6008: # ----------------------------------------------- Make sure that does not exist
 6009:    my $uhome=&homeserver($uname,$udom,'true');
 6010:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6011:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6012:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6013:        $uhome=&homeserver($uname,$udom,'true');       
 6014:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6015:            return 'error: unable to generate unique course-ID';
 6016:        } 
 6017:    }
 6018: # ------------------------------------------------ Check supplied server name
 6019:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 6020:     if (! &is_library($course_server)) {
 6021:         return 'error:bad server name '.$course_server;
 6022:     }
 6023: # ------------------------------------------------------------- Make the course
 6024:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 6025:                       $course_server);
 6026:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 6027:     $uhome=&homeserver($uname,$udom,'true');
 6028:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6029: 	return 'error: no such course';
 6030:     }
 6031: # ----------------------------------------------------------------- Course made
 6032: # log existence
 6033:     my $newcourse = {
 6034:                     $udom.'_'.$uname => {
 6035:                                      description => $description,
 6036:                                      inst_code   => $inst_code,
 6037:                                      owner       => $course_owner,
 6038:                                      type        => $crstype,
 6039:                                                 },
 6040:                     };
 6041:     &courseidput($udom,$newcourse,$uhome,'notime');
 6042: # set toplevel url
 6043:     my $topurl=$url;
 6044:     unless ($nonstandard) {
 6045: # ------------------------------------------ For standard courses, make top url
 6046:         my $mapurl=&clutter($url);
 6047:         if ($mapurl eq '/res/') { $mapurl=''; }
 6048:         $env{'form.initmap'}=(<<ENDINITMAP);
 6049: <map>
 6050: <resource id="1" type="start"></resource>
 6051: <resource id="2" src="$mapurl"></resource>
 6052: <resource id="3" type="finish"></resource>
 6053: <link index="1" from="1" to="2"></link>
 6054: <link index="2" from="2" to="3"></link>
 6055: </map>
 6056: ENDINITMAP
 6057:         $topurl=&declutter(
 6058:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 6059:                           );
 6060:     }
 6061: # ----------------------------------------------------------- Write preferences
 6062:     &writecoursepref($udom.'_'.$uname,
 6063:                      ('description' => $description,
 6064:                       'url'         => $topurl));
 6065:     return '/'.$udom.'/'.$uname;
 6066: }
 6067: 
 6068: sub is_course {
 6069:     my ($cdom,$cnum) = @_;
 6070:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 6071: 				undef,'.');
 6072:     if (exists($courses{$cdom.'_'.$cnum})) {
 6073:         return 1;
 6074:     }
 6075:     return 0;
 6076: }
 6077: 
 6078: # ---------------------------------------------------------- Assign Custom Role
 6079: 
 6080: sub assigncustomrole {
 6081:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 6082:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 6083:                        $end,$start,$deleteflag,$selfenroll,$context);
 6084: }
 6085: 
 6086: # ----------------------------------------------------------------- Revoke Role
 6087: 
 6088: sub revokerole {
 6089:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 6090:     my $now=time;
 6091:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 6092: }
 6093: 
 6094: # ---------------------------------------------------------- Revoke Custom Role
 6095: 
 6096: sub revokecustomrole {
 6097:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 6098:     my $now=time;
 6099:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 6100:            $deleteflag,$selfenroll,$context);
 6101: }
 6102: 
 6103: # ------------------------------------------------------------ Disk usage
 6104: sub diskusage {
 6105:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 6106:     $directorypath =~ s/\/$//;
 6107:     my $listing=&reply('du2:'.&escape($directorypath).':'
 6108:                        .&escape($getpropath).':'.&escape($uname).':'
 6109:                        .&escape($udom),homeserver($uname,$udom));
 6110:     if ($listing eq 'unknown_cmd') {
 6111:         if ($getpropath) {
 6112:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 6113:         }
 6114:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 6115:     }
 6116:     return $listing;
 6117: }
 6118: 
 6119: sub is_locked {
 6120:     my ($file_name, $domain, $user) = @_;
 6121:     my @check;
 6122:     my $is_locked;
 6123:     push @check, $file_name;
 6124:     my %locked = &get('file_permissions',\@check,
 6125: 		      $env{'user.domain'},$env{'user.name'});
 6126:     my ($tmp)=keys(%locked);
 6127:     if ($tmp=~/^error:/) { undef(%locked); }
 6128:     
 6129:     if (ref($locked{$file_name}) eq 'ARRAY') {
 6130:         $is_locked = 'false';
 6131:         foreach my $entry (@{$locked{$file_name}}) {
 6132:            if (ref($entry) eq 'ARRAY') { 
 6133:                $is_locked = 'true';
 6134:                last;
 6135:            }
 6136:        }
 6137:     } else {
 6138:         $is_locked = 'false';
 6139:     }
 6140: }
 6141: 
 6142: sub declutter_portfile {
 6143:     my ($file) = @_;
 6144:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 6145:     return $file;
 6146: }
 6147: 
 6148: # ------------------------------------------------------------- Mark as Read Only
 6149: 
 6150: sub mark_as_readonly {
 6151:     my ($domain,$user,$files,$what) = @_;
 6152:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6153:     my ($tmp)=keys(%current_permissions);
 6154:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6155:     foreach my $file (@{$files}) {
 6156: 	$file = &declutter_portfile($file);
 6157:         push(@{$current_permissions{$file}},$what);
 6158:     }
 6159:     &put('file_permissions',\%current_permissions,$domain,$user);
 6160:     return;
 6161: }
 6162: 
 6163: # ------------------------------------------------------------Save Selected Files
 6164: 
 6165: sub save_selected_files {
 6166:     my ($user, $path, @files) = @_;
 6167:     my $filename = $user."savedfiles";
 6168:     my @other_files = &files_not_in_path($user, $path);
 6169:     open (OUT, '>'.$tmpdir.$filename);
 6170:     foreach my $file (@files) {
 6171:         print (OUT $env{'form.currentpath'}.$file."\n");
 6172:     }
 6173:     foreach my $file (@other_files) {
 6174:         print (OUT $file."\n");
 6175:     }
 6176:     close (OUT);
 6177:     return 'ok';
 6178: }
 6179: 
 6180: sub clear_selected_files {
 6181:     my ($user) = @_;
 6182:     my $filename = $user."savedfiles";
 6183:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6184:     print (OUT undef);
 6185:     close (OUT);
 6186:     return ("ok");    
 6187: }
 6188: 
 6189: sub files_in_path {
 6190:     my ($user, $path) = @_;
 6191:     my $filename = $user."savedfiles";
 6192:     my %return_files;
 6193:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6194:     while (my $line_in = <IN>) {
 6195:         chomp ($line_in);
 6196:         my @paths_and_file = split (m!/!, $line_in);
 6197:         my $file_part = pop (@paths_and_file);
 6198:         my $path_part = join ('/', @paths_and_file);
 6199:         $path_part.='/';
 6200:         my $path_and_file = $path_part.$file_part;
 6201:         if ($path_part eq $path) {
 6202:             $return_files{$file_part}= 'selected';
 6203:         }
 6204:     }
 6205:     close (IN);
 6206:     return (\%return_files);
 6207: }
 6208: 
 6209: # called in portfolio select mode, to show files selected NOT in current directory
 6210: sub files_not_in_path {
 6211:     my ($user, $path) = @_;
 6212:     my $filename = $user."savedfiles";
 6213:     my @return_files;
 6214:     my $path_part;
 6215:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6216:     while (my $line = <IN>) {
 6217:         #ok, I know it's clunky, but I want it to work
 6218:         my @paths_and_file = split(m|/|, $line);
 6219:         my $file_part = pop(@paths_and_file);
 6220:         chomp($file_part);
 6221:         my $path_part = join('/', @paths_and_file);
 6222:         $path_part .= '/';
 6223:         my $path_and_file = $path_part.$file_part;
 6224:         if ($path_part ne $path) {
 6225:             push(@return_files, ($path_and_file));
 6226:         }
 6227:     }
 6228:     close(OUT);
 6229:     return (@return_files);
 6230: }
 6231: 
 6232: #----------------------------------------------Get portfolio file permissions
 6233: 
 6234: sub get_portfile_permissions {
 6235:     my ($domain,$user) = @_;
 6236:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6237:     my ($tmp)=keys(%current_permissions);
 6238:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6239:     return \%current_permissions;
 6240: }
 6241: 
 6242: #---------------------------------------------Get portfolio file access controls
 6243: 
 6244: sub get_access_controls {
 6245:     my ($current_permissions,$group,$file) = @_;
 6246:     my %access;
 6247:     my $real_file = $file;
 6248:     $file =~ s/\.meta$//;
 6249:     if (defined($file)) {
 6250:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 6251:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 6252:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 6253:             }
 6254:         }
 6255:     } else {
 6256:         foreach my $key (keys(%{$current_permissions})) {
 6257:             if ($key =~ /\0accesscontrol$/) {
 6258:                 if (defined($group)) {
 6259:                     if ($key !~ m-^\Q$group\E/-) {
 6260:                         next;
 6261:                     }
 6262:                 }
 6263:                 my ($fullpath) = split(/\0/,$key);
 6264:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 6265:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 6266:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 6267:                     }
 6268:                 }
 6269:             }
 6270:         }
 6271:     }
 6272:     return %access;
 6273: }
 6274: 
 6275: sub modify_access_controls {
 6276:     my ($file_name,$changes,$domain,$user)=@_;
 6277:     my ($outcome,$deloutcome);
 6278:     my %store_permissions;
 6279:     my %new_values;
 6280:     my %new_control;
 6281:     my %translation;
 6282:     my @deletions = ();
 6283:     my $now = time;
 6284:     if (exists($$changes{'activate'})) {
 6285:         if (ref($$changes{'activate'}) eq 'HASH') {
 6286:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 6287:             my $numnew = scalar(@newitems);
 6288:             for (my $i=0; $i<$numnew; $i++) {
 6289:                 my $newkey = $newitems[$i];
 6290:                 my $newid = &Apache::loncommon::get_cgi_id();
 6291:                 if ($newkey =~ /^\d+:/) { 
 6292:                     $newkey =~ s/^(\d+)/$newid/;
 6293:                     $translation{$1} = $newid;
 6294:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 6295:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 6296:                     $translation{$1} = $newid;
 6297:                 }
 6298:                 $new_values{$file_name."\0".$newkey} = 
 6299:                                           $$changes{'activate'}{$newitems[$i]};
 6300:                 $new_control{$newkey} = $now;
 6301:             }
 6302:         }
 6303:     }
 6304:     my %todelete;
 6305:     my %changed_items;
 6306:     foreach my $action ('delete','update') {
 6307:         if (exists($$changes{$action})) {
 6308:             if (ref($$changes{$action}) eq 'HASH') {
 6309:                 foreach my $key (keys(%{$$changes{$action}})) {
 6310:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 6311:                     if ($action eq 'delete') { 
 6312:                         $todelete{$itemnum} = 1;
 6313:                     } else {
 6314:                         $changed_items{$itemnum} = $key;
 6315:                     }
 6316:                 }
 6317:             }
 6318:         }
 6319:     }
 6320:     # get lock on access controls for file.
 6321:     my $lockhash = {
 6322:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 6323:                                                        ':'.$env{'user.domain'},
 6324:                    }; 
 6325:     my $tries = 0;
 6326:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6327:    
 6328:     while (($gotlock ne 'ok') && $tries <3) {
 6329:         $tries ++;
 6330:         sleep 1;
 6331:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6332:     }
 6333:     if ($gotlock eq 'ok') {
 6334:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 6335:         my ($tmp)=keys(%curr_permissions);
 6336:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 6337:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 6338:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 6339:             if (ref($curr_controls) eq 'HASH') {
 6340:                 foreach my $control_item (keys(%{$curr_controls})) {
 6341:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 6342:                     if (defined($todelete{$itemnum})) {
 6343:                         push(@deletions,$file_name."\0".$control_item);
 6344:                     } else {
 6345:                         if (defined($changed_items{$itemnum})) {
 6346:                             $new_control{$changed_items{$itemnum}} = $now;
 6347:                             push(@deletions,$file_name."\0".$control_item);
 6348:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 6349:                         } else {
 6350:                             $new_control{$control_item} = $$curr_controls{$control_item};
 6351:                         }
 6352:                     }
 6353:                 }
 6354:             }
 6355:         }
 6356:         my ($group);
 6357:         if (&is_course($domain,$user)) {
 6358:             ($group,my $file) = split(/\//,$file_name,2);
 6359:         }
 6360:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 6361:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 6362:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 6363:         #  remove lock
 6364:         my @del_lock = ($file_name."\0".'locked_access_records');
 6365:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 6366:         my $sqlresult =
 6367:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 6368:                                     $group);
 6369:     } else {
 6370:         $outcome = "error: could not obtain lockfile\n";  
 6371:     }
 6372:     return ($outcome,$deloutcome,\%new_values,\%translation);
 6373: }
 6374: 
 6375: sub make_public_indefinitely {
 6376:     my ($requrl) = @_;
 6377:     my $now = time;
 6378:     my $action = 'activate';
 6379:     my $aclnum = 0;
 6380:     if (&is_portfolio_url($requrl)) {
 6381:         my (undef,$udom,$unum,$file_name,$group) =
 6382:             &parse_portfolio_url($requrl);
 6383:         my $current_perms = &get_portfile_permissions($udom,$unum);
 6384:         my %access_controls = &get_access_controls($current_perms,
 6385:                                                    $group,$file_name);
 6386:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 6387:             my ($num,$scope,$end,$start) = 
 6388:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6389:             if ($scope eq 'public') {
 6390:                 if ($start <= $now && $end == 0) {
 6391:                     $action = 'none';
 6392:                 } else {
 6393:                     $action = 'update';
 6394:                     $aclnum = $num;
 6395:                 }
 6396:                 last;
 6397:             }
 6398:         }
 6399:         if ($action eq 'none') {
 6400:              return 'ok';
 6401:         } else {
 6402:             my %changes;
 6403:             my $newend = 0;
 6404:             my $newstart = $now;
 6405:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 6406:             $changes{$action}{$newkey} = {
 6407:                 type => 'public',
 6408:                 time => {
 6409:                     start => $newstart,
 6410:                     end   => $newend,
 6411:                 },
 6412:             };
 6413:             my ($outcome,$deloutcome,$new_values,$translation) =
 6414:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 6415:             return $outcome;
 6416:         }
 6417:     } else {
 6418:         return 'invalid';
 6419:     }
 6420: }
 6421: 
 6422: #------------------------------------------------------Get Marked as Read Only
 6423: 
 6424: sub get_marked_as_readonly {
 6425:     my ($domain,$user,$what,$group) = @_;
 6426:     my $current_permissions = &get_portfile_permissions($domain,$user);
 6427:     my @readonly_files;
 6428:     my $cmp1=$what;
 6429:     if (ref($what)) { $cmp1=join('',@{$what}) };
 6430:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6431:         if (defined($group)) {
 6432:             if ($file_name !~ m-^\Q$group\E/-) {
 6433:                 next;
 6434:             }
 6435:         }
 6436:         if (ref($value) eq "ARRAY"){
 6437:             foreach my $stored_what (@{$value}) {
 6438:                 my $cmp2=$stored_what;
 6439:                 if (ref($stored_what) eq 'ARRAY') {
 6440:                     $cmp2=join('',@{$stored_what});
 6441:                 }
 6442:                 if ($cmp1 eq $cmp2) {
 6443:                     push(@readonly_files, $file_name);
 6444:                     last;
 6445:                 } elsif (!defined($what)) {
 6446:                     push(@readonly_files, $file_name);
 6447:                     last;
 6448:                 }
 6449:             }
 6450:         }
 6451:     }
 6452:     return @readonly_files;
 6453: }
 6454: #-----------------------------------------------------------Get Marked as Read Only Hash
 6455: 
 6456: sub get_marked_as_readonly_hash {
 6457:     my ($current_permissions,$group,$what) = @_;
 6458:     my %readonly_files;
 6459:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6460:         if (defined($group)) {
 6461:             if ($file_name !~ m-^\Q$group\E/-) {
 6462:                 next;
 6463:             }
 6464:         }
 6465:         if (ref($value) eq "ARRAY"){
 6466:             foreach my $stored_what (@{$value}) {
 6467:                 if (ref($stored_what) eq 'ARRAY') {
 6468:                     foreach my $lock_descriptor(@{$stored_what}) {
 6469:                         if ($lock_descriptor eq 'graded') {
 6470:                             $readonly_files{$file_name} = 'graded';
 6471:                         } elsif ($lock_descriptor eq 'handback') {
 6472:                             $readonly_files{$file_name} = 'handback';
 6473:                         } else {
 6474:                             if (!exists($readonly_files{$file_name})) {
 6475:                                 $readonly_files{$file_name} = 'locked';
 6476:                             }
 6477:                         }
 6478:                     }
 6479:                 } 
 6480:             }
 6481:         } 
 6482:     }
 6483:     return %readonly_files;
 6484: }
 6485: # ------------------------------------------------------------ Unmark as Read Only
 6486: 
 6487: sub unmark_as_readonly {
 6488:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 6489:     # for portfolio submissions, $what contains [$symb,$crsid] 
 6490:     my ($domain,$user,$what,$file_name,$group) = @_;
 6491:     $file_name = &declutter_portfile($file_name);
 6492:     my $symb_crs = $what;
 6493:     if (ref($what)) { $symb_crs=join('',@$what); }
 6494:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 6495:     my ($tmp)=keys(%current_permissions);
 6496:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6497:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 6498:     foreach my $file (@readonly_files) {
 6499: 	my $clean_file = &declutter_portfile($file);
 6500: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 6501: 	my $current_locks = $current_permissions{$file};
 6502:         my @new_locks;
 6503:         my @del_keys;
 6504:         if (ref($current_locks) eq "ARRAY"){
 6505:             foreach my $locker (@{$current_locks}) {
 6506:                 my $compare=$locker;
 6507:                 if (ref($locker) eq 'ARRAY') {
 6508:                     $compare=join('',@{$locker});
 6509:                     if ($compare ne $symb_crs) {
 6510:                         push(@new_locks, $locker);
 6511:                     }
 6512:                 }
 6513:             }
 6514:             if (scalar(@new_locks) > 0) {
 6515:                 $current_permissions{$file} = \@new_locks;
 6516:             } else {
 6517:                 push(@del_keys, $file);
 6518:                 &del('file_permissions',\@del_keys, $domain, $user);
 6519:                 delete($current_permissions{$file});
 6520:             }
 6521:         }
 6522:     }
 6523:     &put('file_permissions',\%current_permissions,$domain,$user);
 6524:     return;
 6525: }
 6526: 
 6527: # ------------------------------------------------------------ Directory lister
 6528: 
 6529: sub dirlist {
 6530:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 6531:     $uri=~s/^\///;
 6532:     $uri=~s/\/$//;
 6533:     my ($udom, $uname);
 6534:     if ($getuserdir) {
 6535:         $udom = $userdomain;
 6536:         $uname = $username;
 6537:     } else {
 6538:         (undef,$udom,$uname)=split(/\//,$uri);
 6539:         if(defined($userdomain)) {
 6540:             $udom = $userdomain;
 6541:         }
 6542:         if(defined($username)) {
 6543:             $uname = $username;
 6544:         }
 6545:     }
 6546:     my ($dirRoot,$listing,@listing_results);
 6547: 
 6548:     $dirRoot = $perlvar{'lonDocRoot'};
 6549:     if (defined($getpropath)) {
 6550:         $dirRoot = &propath($udom,$uname);
 6551:         $dirRoot =~ s/\/$//;
 6552:     } elsif (defined($getuserdir)) {
 6553:         my $subdir=$uname.'__';
 6554:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 6555:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 6556:                    ."/$udom/$subdir/$uname";
 6557:     } elsif (defined($alternateRoot)) {
 6558:         $dirRoot = $alternateRoot;
 6559:     }
 6560: 
 6561:     if($udom) {
 6562:         if($uname) {
 6563:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 6564:                               .$getuserdir.':'.&escape($dirRoot)
 6565:                               .':'.&escape($uname).':'.&escape($udom),
 6566:                               &homeserver($uname,$udom));
 6567:             if ($listing eq 'unknown_cmd') {
 6568:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 6569:                                   &homeserver($uname,$udom));
 6570:             } else {
 6571:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6572:             }
 6573:             if ($listing eq 'unknown_cmd') {
 6574:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 6575: 				  &homeserver($uname,$udom));
 6576:                 @listing_results = split(/:/,$listing);
 6577:             } else {
 6578:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6579:             }
 6580:             return @listing_results;
 6581:         } elsif(!$alternateRoot) {
 6582:             my %allusers;
 6583: 	    my %servers = &get_servers($udom,'library');
 6584:  	    foreach my $tryserver (keys(%servers)) {
 6585:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 6586:                                   &escape($udom),$tryserver);
 6587:                 if ($listing eq 'unknown_cmd') {
 6588: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 6589: 				      $udom, $tryserver);
 6590:                 } else {
 6591:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 6592:                 }
 6593: 		if ($listing eq 'unknown_cmd') {
 6594: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 6595: 				      $udom, $tryserver);
 6596: 		    @listing_results = split(/:/,$listing);
 6597: 		} else {
 6598: 		    @listing_results =
 6599: 			map { &unescape($_); } split(/:/,$listing);
 6600: 		}
 6601: 		if ($listing_results[0] ne 'no_such_dir' && 
 6602: 		    $listing_results[0] ne 'empty'       &&
 6603: 		    $listing_results[0] ne 'con_lost') {
 6604: 		    foreach my $line (@listing_results) {
 6605: 			my ($entry) = split(/&/,$line,2);
 6606: 			$allusers{$entry} = 1;
 6607: 		    }
 6608: 		}
 6609:             }
 6610:             my $alluserstr='';
 6611:             foreach my $user (sort(keys(%allusers))) {
 6612:                 $alluserstr.=$user.'&user:';
 6613:             }
 6614:             $alluserstr=~s/:$//;
 6615:             return split(/:/,$alluserstr);
 6616:         } else {
 6617:             return ('missing user name');
 6618:         }
 6619:     } elsif(!defined($getpropath)) {
 6620:         my @all_domains = sort(&all_domains());
 6621:         foreach my $domain (@all_domains) {
 6622:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 6623:         }
 6624:         return @all_domains;
 6625:     } else {
 6626:         return ('missing domain');
 6627:     }
 6628: }
 6629: 
 6630: # --------------------------------------------- GetFileTimestamp
 6631: # This function utilizes dirlist and returns the date stamp for
 6632: # when it was last modified.  It will also return an error of -1
 6633: # if an error occurs
 6634: 
 6635: sub GetFileTimestamp {
 6636:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 6637:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 6638:     $studentName   = &LONCAPA::clean_username($studentName);
 6639:     my ($fileStat) = 
 6640:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
 6641:                                  undef,$getuserdir);
 6642:     my @stats = split('&', $fileStat);
 6643:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6644:         # @stats contains first the filename, then the stat output
 6645:         return $stats[10]; # so this is 10 instead of 9.
 6646:     } else {
 6647:         return -1;
 6648:     }
 6649: }
 6650: 
 6651: sub stat_file {
 6652:     my ($uri) = @_;
 6653:     $uri = &clutter_with_no_wrapper($uri);
 6654: 
 6655:     my ($udom,$uname,$file);
 6656:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 6657: 	($udom,$uname,$file) =
 6658: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 6659: 	$file = 'userfiles/'.$file;
 6660:     }
 6661:     if ($uri =~ m-^/res/-) {
 6662: 	($udom,$uname) = 
 6663: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 6664: 	$file = $uri;
 6665:     }
 6666: 
 6667:     if (!$udom || !$uname || !$file) {
 6668: 	# unable to handle the uri
 6669: 	return ();
 6670:     }
 6671:     my $getpropath;
 6672:     if ($file =~ /^userfiles\//) {
 6673:         $getpropath = 1;
 6674:     }
 6675:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
 6676:     my @stats = split('&', $result);
 6677:     
 6678:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6679: 	shift(@stats); #filename is first
 6680: 	return @stats;
 6681:     }
 6682:     return ();
 6683: }
 6684: 
 6685: # -------------------------------------------------------- Value of a Condition
 6686: 
 6687: # gets the value of a specific preevaluated condition
 6688: #    stored in the string  $env{user.state.<cid>}
 6689: # or looks up a condition reference in the bighash and if if hasn't
 6690: # already been evaluated recurses into docondval to get the value of
 6691: # the condition, then memoizing it to 
 6692: #   $env{user.state.<cid>.<condition>}
 6693: sub directcondval {
 6694:     my $number=shift;
 6695:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 6696: 	&Apache::lonuserstate::evalstate();
 6697:     }
 6698:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 6699: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 6700:     } elsif ($number =~ /^_/) {
 6701: 	my $sub_condition;
 6702: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6703: 		&GDBM_READER(),0640)) {
 6704: 	    $sub_condition=$bighash{'conditions'.$number};
 6705: 	    untie(%bighash);
 6706: 	}
 6707: 	my $value = &docondval($sub_condition);
 6708: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 6709: 	return $value;
 6710:     }
 6711:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 6712:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 6713:     } else {
 6714:        return 2;
 6715:     }
 6716: }
 6717: 
 6718: # get the collection of conditions for this resource
 6719: sub condval {
 6720:     my $condidx=shift;
 6721:     my $allpathcond='';
 6722:     foreach my $cond (split(/\|/,$condidx)) {
 6723: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 6724: 	    $allpathcond.=
 6725: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 6726: 	}
 6727:     }
 6728:     $allpathcond=~s/\|$//;
 6729:     return &docondval($allpathcond);
 6730: }
 6731: 
 6732: #evaluates an expression of conditions
 6733: sub docondval {
 6734:     my ($allpathcond) = @_;
 6735:     my $result=0;
 6736:     if ($env{'request.course.id'}
 6737: 	&& defined($allpathcond)) {
 6738: 	my $operand='|';
 6739: 	my @stack;
 6740: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 6741: 	    if ($chunk eq '(') {
 6742: 		push @stack,($operand,$result);
 6743: 	    } elsif ($chunk eq ')') {
 6744: 		my $before=pop @stack;
 6745: 		if (pop @stack eq '&') {
 6746: 		    $result=$result>$before?$before:$result;
 6747: 		} else {
 6748: 		    $result=$result>$before?$result:$before;
 6749: 		}
 6750: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 6751: 		$operand=$chunk;
 6752: 	    } else {
 6753: 		my $new=directcondval($chunk);
 6754: 		if ($operand eq '&') {
 6755: 		    $result=$result>$new?$new:$result;
 6756: 		} else {
 6757: 		    $result=$result>$new?$result:$new;
 6758: 		}
 6759: 	    }
 6760: 	}
 6761:     }
 6762:     return $result;
 6763: }
 6764: 
 6765: # ---------------------------------------------------- Devalidate courseresdata
 6766: 
 6767: sub devalidatecourseresdata {
 6768:     my ($coursenum,$coursedomain)=@_;
 6769:     my $hashid=$coursenum.':'.$coursedomain;
 6770:     &devalidate_cache_new('courseres',$hashid);
 6771: }
 6772: 
 6773: 
 6774: # --------------------------------------------------- Course Resourcedata Query
 6775: #
 6776: #  Parameters:
 6777: #      $coursenum    - Number of the course.
 6778: #      $coursedomain - Domain at which the course was created.
 6779: #  Returns:
 6780: #     A hash of the course parameters along (I think) with timestamps
 6781: #     and version info.
 6782: 
 6783: sub get_courseresdata {
 6784:     my ($coursenum,$coursedomain)=@_;
 6785:     my $coursehom=&homeserver($coursenum,$coursedomain);
 6786:     my $hashid=$coursenum.':'.$coursedomain;
 6787:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 6788:     my %dumpreply;
 6789:     unless (defined($cached)) {
 6790: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 6791: 	$result=\%dumpreply;
 6792: 	my ($tmp) = keys(%dumpreply);
 6793: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6794: 	    &do_cache_new('courseres',$hashid,$result,600);
 6795: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 6796: 	    return $tmp;
 6797: 	} elsif ($tmp =~ /^(error)/) {
 6798: 	    $result=undef;
 6799: 	    &do_cache_new('courseres',$hashid,$result,600);
 6800: 	}
 6801:     }
 6802:     return $result;
 6803: }
 6804: 
 6805: sub devalidateuserresdata {
 6806:     my ($uname,$udom)=@_;
 6807:     my $hashid="$udom:$uname";
 6808:     &devalidate_cache_new('userres',$hashid);
 6809: }
 6810: 
 6811: sub get_userresdata {
 6812:     my ($uname,$udom)=@_;
 6813:     #most student don\'t have any data set, check if there is some data
 6814:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 6815: 
 6816:     my $hashid="$udom:$uname";
 6817:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 6818:     if (!defined($cached)) {
 6819: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 6820: 	$result=\%resourcedata;
 6821: 	&do_cache_new('userres',$hashid,$result,600);
 6822:     }
 6823:     my ($tmp)=keys(%$result);
 6824:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 6825: 	return $result;
 6826:     }
 6827:     #error 2 occurs when the .db doesn't exist
 6828:     if ($tmp!~/error: 2 /) {
 6829: 	&logthis("<font color=\"blue\">WARNING:".
 6830: 		 " Trying to get resource data for ".
 6831: 		 $uname." at ".$udom.": ".
 6832: 		 $tmp."</font>");
 6833:     } elsif ($tmp=~/error: 2 /) {
 6834: 	#&EXT_cache_set($udom,$uname);
 6835: 	&do_cache_new('userres',$hashid,undef,600);
 6836: 	undef($tmp); # not really an error so don't send it back
 6837:     }
 6838:     return $tmp;
 6839: }
 6840: #----------------------------------------------- resdata - return resource data
 6841: #  Purpose:
 6842: #    Return resource data for either users or for a course.
 6843: #  Parameters:
 6844: #     $name      - Course/user name.
 6845: #     $domain    - Name of the domain the user/course is registered on.
 6846: #     $type      - Type of thing $name is (must be 'course' or 'user'
 6847: #     @which     - Array of names of resources desired.
 6848: #  Returns:
 6849: #     The value of the first reasource in @which that is found in the
 6850: #     resource hash.
 6851: #  Exceptional Conditions:
 6852: #     If the $type passed in is not valid (not the string 'course' or 
 6853: #     'user', an undefined  reference is returned.
 6854: #     If none of the resources are found, an undef is returned
 6855: sub resdata {
 6856:     my ($name,$domain,$type,@which)=@_;
 6857:     my $result;
 6858:     if ($type eq 'course') {
 6859: 	$result=&get_courseresdata($name,$domain);
 6860:     } elsif ($type eq 'user') {
 6861: 	$result=&get_userresdata($name,$domain);
 6862:     }
 6863:     if (!ref($result)) { return $result; }    
 6864:     foreach my $item (@which) {
 6865: 	if (defined($result->{$item->[0]})) {
 6866: 	    return [$result->{$item->[0]},$item->[1]];
 6867: 	}
 6868:     }
 6869:     return undef;
 6870: }
 6871: 
 6872: #
 6873: # EXT resource caching routines
 6874: #
 6875: 
 6876: sub clear_EXT_cache_status {
 6877:     &delenv('cache.EXT.');
 6878: }
 6879: 
 6880: sub EXT_cache_status {
 6881:     my ($target_domain,$target_user) = @_;
 6882:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6883:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 6884:         # We know already the user has no data
 6885:         return 1;
 6886:     } else {
 6887:         return 0;
 6888:     }
 6889: }
 6890: 
 6891: sub EXT_cache_set {
 6892:     my ($target_domain,$target_user) = @_;
 6893:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6894:     #&appenv({$cachename => time});
 6895: }
 6896: 
 6897: # --------------------------------------------------------- Value of a Variable
 6898: sub EXT {
 6899: 
 6900:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 6901:     unless ($varname) { return ''; }
 6902:     #get real user name/domain, courseid and symb
 6903:     my $courseid;
 6904:     my $publicuser;
 6905:     if ($symbparm) {
 6906: 	$symbparm=&get_symb_from_alias($symbparm);
 6907:     }
 6908:     if (!($uname && $udom)) {
 6909:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 6910:       if (!$symbparm) {	$symbparm=$cursymb; }
 6911:     } else {
 6912: 	$courseid=$env{'request.course.id'};
 6913:     }
 6914:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 6915:     my $rest;
 6916:     if (defined($therest[0])) {
 6917:        $rest=join('.',@therest);
 6918:     } else {
 6919:        $rest='';
 6920:     }
 6921: 
 6922:     my $qualifierrest=$qualifier;
 6923:     if ($rest) { $qualifierrest.='.'.$rest; }
 6924:     my $spacequalifierrest=$space;
 6925:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 6926:     if ($realm eq 'user') {
 6927: # --------------------------------------------------------------- user.resource
 6928: 	if ($space eq 'resource') {
 6929: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 6930: 		  || defined($Apache::lonhomework::parsing_a_task))
 6931: 		 &&
 6932: 		 ($symbparm eq &symbread()) ) {	
 6933: 		# if we are in the middle of processing the resource the
 6934: 		# get the value we are planning on committing
 6935:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 6936:                     return $Apache::lonhomework::results{$qualifierrest};
 6937:                 } else {
 6938:                     return $Apache::lonhomework::history{$qualifierrest};
 6939:                 }
 6940: 	    } else {
 6941: 		my %restored;
 6942: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 6943: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 6944: 		} else {
 6945: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 6946: 		}
 6947: 		return $restored{$qualifierrest};
 6948: 	    }
 6949: # ----------------------------------------------------------------- user.access
 6950:         } elsif ($space eq 'access') {
 6951: 	    # FIXME - not supporting calls for a specific user
 6952:             return &allowed($qualifier,$rest);
 6953: # ------------------------------------------ user.preferences, user.environment
 6954:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 6955: 	    if (($uname eq $env{'user.name'}) &&
 6956: 		($udom eq $env{'user.domain'})) {
 6957: 		return $env{join('.',('environment',$qualifierrest))};
 6958: 	    } else {
 6959: 		my %returnhash;
 6960: 		if (!$publicuser) {
 6961: 		    %returnhash=&userenvironment($udom,$uname,
 6962: 						 $qualifierrest);
 6963: 		}
 6964: 		return $returnhash{$qualifierrest};
 6965: 	    }
 6966: # ----------------------------------------------------------------- user.course
 6967:         } elsif ($space eq 'course') {
 6968: 	    # FIXME - not supporting calls for a specific user
 6969:             return $env{join('.',('request.course',$qualifier))};
 6970: # ------------------------------------------------------------------- user.role
 6971:         } elsif ($space eq 'role') {
 6972: 	    # FIXME - not supporting calls for a specific user
 6973:             my ($role,$where)=split(/\./,$env{'request.role'});
 6974:             if ($qualifier eq 'value') {
 6975: 		return $role;
 6976:             } elsif ($qualifier eq 'extent') {
 6977:                 return $where;
 6978:             }
 6979: # ----------------------------------------------------------------- user.domain
 6980:         } elsif ($space eq 'domain') {
 6981:             return $udom;
 6982: # ------------------------------------------------------------------- user.name
 6983:         } elsif ($space eq 'name') {
 6984:             return $uname;
 6985: # ---------------------------------------------------- Any other user namespace
 6986:         } else {
 6987: 	    my %reply;
 6988: 	    if (!$publicuser) {
 6989: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 6990: 	    }
 6991: 	    return $reply{$qualifierrest};
 6992:         }
 6993:     } elsif ($realm eq 'query') {
 6994: # ---------------------------------------------- pull stuff out of query string
 6995:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 6996: 						[$spacequalifierrest]);
 6997: 	return $env{'form.'.$spacequalifierrest}; 
 6998:    } elsif ($realm eq 'request') {
 6999: # ------------------------------------------------------------- request.browser
 7000:         if ($space eq 'browser') {
 7001: 	    if ($qualifier eq 'textremote') {
 7002: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 7003: 		    return 1;
 7004: 		} else {
 7005: 		    return 0;
 7006: 		}
 7007: 	    } else {
 7008: 		return $env{'browser.'.$qualifier};
 7009: 	    }
 7010: # ------------------------------------------------------------ request.filename
 7011:         } else {
 7012:             return $env{'request.'.$spacequalifierrest};
 7013:         }
 7014:     } elsif ($realm eq 'course') {
 7015: # ---------------------------------------------------------- course.description
 7016:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 7017:     } elsif ($realm eq 'resource') {
 7018: 
 7019: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 7020: 	    if (!$symbparm) { $symbparm=&symbread(); }
 7021: 	}
 7022: 
 7023: 	if ($space eq 'title') {
 7024: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 7025: 	    return &gettitle($symbparm);
 7026: 	}
 7027: 	
 7028: 	if ($space eq 'map') {
 7029: 	    my ($map) = &decode_symb($symbparm);
 7030: 	    return &symbread($map);
 7031: 	}
 7032: 	if ($space eq 'filename') {
 7033: 	    if ($symbparm) {
 7034: 		return &clutter((&decode_symb($symbparm))[2]);
 7035: 	    }
 7036: 	    return &hreflocation('',$env{'request.filename'});
 7037: 	}
 7038: 
 7039: 	my ($section, $group, @groups);
 7040: 	my ($courselevelm,$courselevel);
 7041: 	if ($symbparm && defined($courseid) && 
 7042: 	    $courseid eq $env{'request.course.id'}) {
 7043: 
 7044: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 7045: 
 7046: # ----------------------------------------------------- Cascading lookup scheme
 7047: 	    my $symbp=$symbparm;
 7048: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 7049: 
 7050: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 7051: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 7052: 
 7053: 	    if (($env{'user.name'} eq $uname) &&
 7054: 		($env{'user.domain'} eq $udom)) {
 7055: 		$section=$env{'request.course.sec'};
 7056:                 @groups = split(/:/,$env{'request.course.groups'});  
 7057:                 @groups=&sort_course_groups($courseid,@groups); 
 7058: 	    } else {
 7059: 		if (! defined($usection)) {
 7060: 		    $section=&getsection($udom,$uname,$courseid);
 7061: 		} else {
 7062: 		    $section = $usection;
 7063: 		}
 7064:                 @groups = &get_users_groups($udom,$uname,$courseid);
 7065: 	    }
 7066: 
 7067: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 7068: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 7069: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 7070: 
 7071: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 7072: 	    my $courselevelr=$courseid.'.'.$symbparm;
 7073: 	    $courselevelm=$courseid.'.'.$mapparm;
 7074: 
 7075: # ----------------------------------------------------------- first, check user
 7076: 
 7077: 	    my $userreply=&resdata($uname,$udom,'user',
 7078: 				       ([$courselevelr,'resource'],
 7079: 					[$courselevelm,'map'     ],
 7080: 					[$courselevel, 'course'  ]));
 7081: 	    if (defined($userreply)) { return &get_reply($userreply); }
 7082: 
 7083: # ------------------------------------------------ second, check some of course
 7084:             my $coursereply;
 7085:             if (@groups > 0) {
 7086:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 7087:                                        $mapparm,$spacequalifierrest);
 7088:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 7089:             }
 7090: 
 7091: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7092: 				  $env{'course.'.$courseid.'.domain'},
 7093: 				  'course',
 7094: 				  ([$seclevelr,   'resource'],
 7095: 				   [$seclevelm,   'map'     ],
 7096: 				   [$seclevel,    'course'  ],
 7097: 				   [$courselevelr,'resource']));
 7098: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7099: 
 7100: # ------------------------------------------------------ third, check map parms
 7101: 	    my %parmhash=();
 7102: 	    my $thisparm='';
 7103: 	    if (tie(%parmhash,'GDBM_File',
 7104: 		    $env{'request.course.fn'}.'_parms.db',
 7105: 		    &GDBM_READER(),0640)) {
 7106: 		$thisparm=$parmhash{$symbparm};
 7107: 		untie(%parmhash);
 7108: 	    }
 7109: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 7110: 	}
 7111: # ------------------------------------------ fourth, look in resource metadata
 7112: 
 7113: 	$spacequalifierrest=~s/\./\_/;
 7114: 	my $filename;
 7115: 	if (!$symbparm) { $symbparm=&symbread(); }
 7116: 	if ($symbparm) {
 7117: 	    $filename=(&decode_symb($symbparm))[2];
 7118: 	} else {
 7119: 	    $filename=$env{'request.filename'};
 7120: 	}
 7121: 	my $metadata=&metadata($filename,$spacequalifierrest);
 7122: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7123: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 7124: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7125: 
 7126: # ---------------------------------------------- fourth, look in rest of course
 7127: 	if ($symbparm && defined($courseid) && 
 7128: 	    $courseid eq $env{'request.course.id'}) {
 7129: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7130: 				     $env{'course.'.$courseid.'.domain'},
 7131: 				     'course',
 7132: 				     ([$courselevelm,'map'   ],
 7133: 				      [$courselevel, 'course']));
 7134: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7135: 	}
 7136: # ------------------------------------------------------------------ Cascade up
 7137: 	unless ($space eq '0') {
 7138: 	    my @parts=split(/_/,$space);
 7139: 	    my $id=pop(@parts);
 7140: 	    my $part=join('_',@parts);
 7141: 	    if ($part eq '') { $part='0'; }
 7142: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 7143: 				 $symbparm,$udom,$uname,$section,1);
 7144: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 7145: 	}
 7146: 	if ($recurse) { return undef; }
 7147: 	my $pack_def=&packages_tab_default($filename,$varname);
 7148: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 7149: # ---------------------------------------------------- Any other user namespace
 7150:     } elsif ($realm eq 'environment') {
 7151: # ----------------------------------------------------------------- environment
 7152: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 7153: 	    return $env{'environment.'.$spacequalifierrest};
 7154: 	} else {
 7155: 	    if ($uname eq 'anonymous' && $udom eq '') {
 7156: 		return '';
 7157: 	    }
 7158: 	    my %returnhash=&userenvironment($udom,$uname,
 7159: 					    $spacequalifierrest);
 7160: 	    return $returnhash{$spacequalifierrest};
 7161: 	}
 7162:     } elsif ($realm eq 'system') {
 7163: # ----------------------------------------------------------------- system.time
 7164: 	if ($space eq 'time') {
 7165: 	    return time;
 7166:         }
 7167:     } elsif ($realm eq 'server') {
 7168: # ----------------------------------------------------------------- system.time
 7169: 	if ($space eq 'name') {
 7170: 	    return $ENV{'SERVER_NAME'};
 7171:         }
 7172:     }
 7173:     return '';
 7174: }
 7175: 
 7176: sub get_reply {
 7177:     my ($reply_value) = @_;
 7178:     if (ref($reply_value) eq 'ARRAY') {
 7179:         if (wantarray) {
 7180: 	    return @$reply_value;
 7181:         }
 7182:         return $reply_value->[0];
 7183:     } else {
 7184:         return $reply_value;
 7185:     }
 7186: }
 7187: 
 7188: sub check_group_parms {
 7189:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 7190:     my @groupitems = ();
 7191:     my $resultitem;
 7192:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 7193:     foreach my $group (@{$groups}) {
 7194:         foreach my $level (@levels) {
 7195:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 7196:              push(@groupitems,[$item,$level->[1]]);
 7197:         }
 7198:     }
 7199:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 7200:                             $env{'course.'.$courseid.'.domain'},
 7201:                                      'course',@groupitems);
 7202:     return $coursereply;
 7203: }
 7204: 
 7205: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 7206:     my ($courseid,@groups) = @_;
 7207:     @groups = sort(@groups);
 7208:     return @groups;
 7209: }
 7210: 
 7211: sub packages_tab_default {
 7212:     my ($uri,$varname)=@_;
 7213:     my (undef,$part,$name)=split(/\./,$varname);
 7214: 
 7215:     my (@extension,@specifics,$do_default);
 7216:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 7217: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 7218: 	if ($pack_type eq 'default') {
 7219: 	    $do_default=1;
 7220: 	} elsif ($pack_type eq 'extension') {
 7221: 	    push(@extension,[$package,$pack_type,$pack_part]);
 7222: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 7223: 	    # only look at packages defaults for packages that this id is
 7224: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 7225: 	}
 7226:     }
 7227:     # first look for a package that matches the requested part id
 7228:     foreach my $package (@specifics) {
 7229: 	my (undef,$pack_type,$pack_part)=@{$package};
 7230: 	next if ($pack_part ne $part);
 7231: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7232: 	    return $packagetab{"$pack_type&$name&default"};
 7233: 	}
 7234:     }
 7235:     # look for any possible matching non extension_ package
 7236:     foreach my $package (@specifics) {
 7237: 	my (undef,$pack_type,$pack_part)=@{$package};
 7238: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7239: 	    return $packagetab{"$pack_type&$name&default"};
 7240: 	}
 7241: 	if ($pack_type eq 'part') { $pack_part='0'; }
 7242: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 7243: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 7244: 	}
 7245:     }
 7246:     # look for any posible extension_ match
 7247:     foreach my $package (@extension) {
 7248: 	my ($package,$pack_type)=@{$package};
 7249: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7250: 	    return $packagetab{"$pack_type&$name&default"};
 7251: 	}
 7252: 	if (defined($packagetab{$package."&$name&default"})) {
 7253: 	    return $packagetab{$package."&$name&default"};
 7254: 	}
 7255:     }
 7256:     # look for a global default setting
 7257:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 7258: 	return $packagetab{"default&$name&default"};
 7259:     }
 7260:     return undef;
 7261: }
 7262: 
 7263: sub add_prefix_and_part {
 7264:     my ($prefix,$part)=@_;
 7265:     my $keyroot;
 7266:     if (defined($prefix) && $prefix !~ /^__/) {
 7267: 	# prefix that has a part already
 7268: 	$keyroot=$prefix;
 7269:     } elsif (defined($prefix)) {
 7270: 	# prefix that is missing a part
 7271: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 7272:     } else {
 7273: 	# no prefix at all
 7274: 	if (defined($part)) { $keyroot='_'.$part; }
 7275:     }
 7276:     return $keyroot;
 7277: }
 7278: 
 7279: # ---------------------------------------------------------------- Get metadata
 7280: 
 7281: my %metaentry;
 7282: sub metadata {
 7283:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 7284:     $uri=&declutter($uri);
 7285:     # if it is a non metadata possible uri return quickly
 7286:     if (($uri eq '') || 
 7287: 	(($uri =~ m|^/*adm/|) && 
 7288: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 7289:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 7290: 	return undef;
 7291:     }
 7292:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 7293: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 7294: 	return undef;
 7295:     }
 7296:     my $filename=$uri;
 7297:     $uri=~s/\.meta$//;
 7298: #
 7299: # Is the metadata already cached?
 7300: # Look at timestamp of caching
 7301: # Everything is cached by the main uri, libraries are never directly cached
 7302: #
 7303:     if (!defined($liburi)) {
 7304: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 7305: 	if (defined($cached)) { return $result->{':'.$what}; }
 7306:     }
 7307:     {
 7308: #
 7309: # Is this a recursive call for a library?
 7310: #
 7311: #	if (! exists($metacache{$uri})) {
 7312: #	    $metacache{$uri}={};
 7313: #	}
 7314: 	my $cachetime = 60*60;
 7315:         if ($liburi) {
 7316: 	    $liburi=&declutter($liburi);
 7317:             $filename=$liburi;
 7318:         } else {
 7319: 	    &devalidate_cache_new('meta',$uri);
 7320: 	    undef(%metaentry);
 7321: 	}
 7322:         my %metathesekeys=();
 7323:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 7324: 	my $metastring;
 7325: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 7326: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 7327: 	    $metastring = 
 7328: 		&Apache::lonnet::ssi_body($which,
 7329: 					  ('grade_target' => 'meta'));
 7330: 	    $cachetime = 1; # only want this cached in the child not long term
 7331: 	} elsif ($uri !~ m -^(editupload)/-) {
 7332: 	    my $file=&filelocation('',&clutter($filename));
 7333: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 7334: 	    $metastring=&getfile($file);
 7335: 	}
 7336:         my $parser=HTML::LCParser->new(\$metastring);
 7337:         my $token;
 7338:         undef %metathesekeys;
 7339:         while ($token=$parser->get_token) {
 7340: 	    if ($token->[0] eq 'S') {
 7341: 		if (defined($token->[2]->{'package'})) {
 7342: #
 7343: # This is a package - get package info
 7344: #
 7345: 		    my $package=$token->[2]->{'package'};
 7346: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7347: 		    if (defined($token->[2]->{'id'})) { 
 7348: 			$keyroot.='_'.$token->[2]->{'id'}; 
 7349: 		    }
 7350: 		    if ($metaentry{':packages'}) {
 7351: 			$metaentry{':packages'}.=','.$package.$keyroot;
 7352: 		    } else {
 7353: 			$metaentry{':packages'}=$package.$keyroot;
 7354: 		    }
 7355: 		    foreach my $pack_entry (keys(%packagetab)) {
 7356: 			my $part=$keyroot;
 7357: 			$part=~s/^\_//;
 7358: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 7359: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 7360: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 7361: 			    # ignore package.tab specified default values
 7362:                             # here &package_tab_default() will fetch those
 7363: 			    if ($subp eq 'default') { next; }
 7364: 			    my $value=$packagetab{$pack_entry};
 7365: 			    my $unikey;
 7366: 			    if ($pack =~ /_0$/) {
 7367: 				$unikey='parameter_0_'.$name;
 7368: 				$part=0;
 7369: 			    } else {
 7370: 				$unikey='parameter'.$keyroot.'_'.$name;
 7371: 			    }
 7372: 			    if ($subp eq 'display') {
 7373: 				$value.=' [Part: '.$part.']';
 7374: 			    }
 7375: 			    $metaentry{':'.$unikey.'.part'}=$part;
 7376: 			    $metathesekeys{$unikey}=1;
 7377: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7378: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 7379: 			    }
 7380: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 7381: 				$metaentry{':'.$unikey}=
 7382: 				    $metaentry{':'.$unikey.'.default'};
 7383: 			    }
 7384: 			}
 7385: 		    }
 7386: 		} else {
 7387: #
 7388: # This is not a package - some other kind of start tag
 7389: #
 7390: 		    my $entry=$token->[1];
 7391: 		    my $unikey;
 7392: 		    if ($entry eq 'import') {
 7393: 			$unikey='';
 7394: 		    } else {
 7395: 			$unikey=$entry;
 7396: 		    }
 7397: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7398: 
 7399: 		    if (defined($token->[2]->{'id'})) { 
 7400: 			$unikey.='_'.$token->[2]->{'id'}; 
 7401: 		    }
 7402: 
 7403: 		    if ($entry eq 'import') {
 7404: #
 7405: # Importing a library here
 7406: #
 7407: 			if ($depthcount<20) {
 7408: 			    my $location=$parser->get_text('/import');
 7409: 			    my $dir=$filename;
 7410: 			    $dir=~s|[^/]*$||;
 7411: 			    $location=&filelocation($dir,$location);
 7412: 			    my $metadata = 
 7413: 				&metadata($uri,'keys', $location,$unikey,
 7414: 					  $depthcount+1);
 7415: 			    foreach my $meta (split(',',$metadata)) {
 7416: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 7417: 				$metathesekeys{$meta}=1;
 7418: 			    }
 7419: 			}
 7420: 		    } else { 
 7421: 			
 7422: 			if (defined($token->[2]->{'name'})) { 
 7423: 			    $unikey.='_'.$token->[2]->{'name'}; 
 7424: 			}
 7425: 			$metathesekeys{$unikey}=1;
 7426: 			foreach my $param (@{$token->[3]}) {
 7427: 			    $metaentry{':'.$unikey.'.'.$param} =
 7428: 				$token->[2]->{$param};
 7429: 			}
 7430: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 7431: 			my $default=$metaentry{':'.$unikey.'.default'};
 7432: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 7433: 		 # only ws inside the tag, and not in default, so use default
 7434: 		 # as value
 7435: 			    $metaentry{':'.$unikey}=$default;
 7436: 			} elsif ( $internaltext =~ /\S/ ) {
 7437: 		  # something interesting inside the tag
 7438: 			    $metaentry{':'.$unikey}=$internaltext;
 7439: 			} else {
 7440: 		  # no interesting values, don't set a default
 7441: 			}
 7442: # end of not-a-package not-a-library import
 7443: 		    }
 7444: # end of not-a-package start tag
 7445: 		}
 7446: # the next is the end of "start tag"
 7447: 	    }
 7448: 	}
 7449: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 7450: 	$extension = lc($extension);
 7451: 	if ($extension eq 'htm') { $extension='html'; }
 7452: 
 7453: 	foreach my $key (keys(%packagetab)) {
 7454: 	    #no specific packages #how's our extension
 7455: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 7456: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 7457: 					 \%metathesekeys);
 7458: 	}
 7459: 
 7460: 	if (!exists($metaentry{':packages'})
 7461: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 7462: 	    foreach my $key (keys(%packagetab)) {
 7463: 		#no specific packages well let's get default then
 7464: 		if ($key!~/^default&/) { next; }
 7465: 		&metadata_create_package_def($uri,$key,'default',
 7466: 					     \%metathesekeys);
 7467: 	    }
 7468: 	}
 7469: # are there custom rights to evaluate
 7470: 	if ($metaentry{':copyright'} eq 'custom') {
 7471: 
 7472:     #
 7473:     # Importing a rights file here
 7474:     #
 7475: 	    unless ($depthcount) {
 7476: 		my $location=$metaentry{':customdistributionfile'};
 7477: 		my $dir=$filename;
 7478: 		$dir=~s|[^/]*$||;
 7479: 		$location=&filelocation($dir,$location);
 7480: 		my $rights_metadata =
 7481: 		    &metadata($uri,'keys',$location,'_rights',
 7482: 			      $depthcount+1);
 7483: 		foreach my $rights (split(',',$rights_metadata)) {
 7484: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 7485: 		    $metathesekeys{$rights}=1;
 7486: 		}
 7487: 	    }
 7488: 	}
 7489: 	# uniqifiy package listing
 7490: 	my %seen;
 7491: 	my @uniq_packages =
 7492: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 7493: 	$metaentry{':packages'} = join(',',@uniq_packages);
 7494: 
 7495: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 7496: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 7497: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 7498: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 7499: # this is the end of "was not already recently cached
 7500:     }
 7501:     return $metaentry{':'.$what};
 7502: }
 7503: 
 7504: sub metadata_create_package_def {
 7505:     my ($uri,$key,$package,$metathesekeys)=@_;
 7506:     my ($pack,$name,$subp)=split(/\&/,$key);
 7507:     if ($subp eq 'default') { next; }
 7508:     
 7509:     if (defined($metaentry{':packages'})) {
 7510: 	$metaentry{':packages'}.=','.$package;
 7511:     } else {
 7512: 	$metaentry{':packages'}=$package;
 7513:     }
 7514:     my $value=$packagetab{$key};
 7515:     my $unikey;
 7516:     $unikey='parameter_0_'.$name;
 7517:     $metaentry{':'.$unikey.'.part'}=0;
 7518:     $$metathesekeys{$unikey}=1;
 7519:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7520: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 7521:     }
 7522:     if (defined($metaentry{':'.$unikey.'.default'})) {
 7523: 	$metaentry{':'.$unikey}=
 7524: 	    $metaentry{':'.$unikey.'.default'};
 7525:     }
 7526: }
 7527: 
 7528: sub metadata_generate_part0 {
 7529:     my ($metadata,$metacache,$uri) = @_;
 7530:     my %allnames;
 7531:     foreach my $metakey (keys(%$metadata)) {
 7532: 	if ($metakey=~/^parameter\_(.*)/) {
 7533: 	  my $part=$$metacache{':'.$metakey.'.part'};
 7534: 	  my $name=$$metacache{':'.$metakey.'.name'};
 7535: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 7536: 	    $allnames{$name}=$part;
 7537: 	  }
 7538: 	}
 7539:     }
 7540:     foreach my $name (keys(%allnames)) {
 7541:       $$metadata{"parameter_0_$name"}=1;
 7542:       my $key=":parameter_0_$name";
 7543:       $$metacache{"$key.part"}='0';
 7544:       $$metacache{"$key.name"}=$name;
 7545:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 7546: 					   $allnames{$name}.'_'.$name.
 7547: 					   '.type'};
 7548:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 7549: 			     '.display'};
 7550:       my $expr='[Part: '.$allnames{$name}.']';
 7551:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 7552:       $$metacache{"$key.display"}=$olddis;
 7553:     }
 7554: }
 7555: 
 7556: # ------------------------------------------------------ Devalidate title cache
 7557: 
 7558: sub devalidate_title_cache {
 7559:     my ($url)=@_;
 7560:     if (!$env{'request.course.id'}) { return; }
 7561:     my $symb=&symbread($url);
 7562:     if (!$symb) { return; }
 7563:     my $key=$env{'request.course.id'}."\0".$symb;
 7564:     &devalidate_cache_new('title',$key);
 7565: }
 7566: 
 7567: # ------------------------------------------------- Get the title of a resource
 7568: 
 7569: sub gettitle {
 7570:     my $urlsymb=shift;
 7571:     my $symb=&symbread($urlsymb);
 7572:     if ($symb) {
 7573: 	my $key=$env{'request.course.id'}."\0".$symb;
 7574: 	my ($result,$cached)=&is_cached_new('title',$key);
 7575: 	if (defined($cached)) { 
 7576: 	    return $result;
 7577: 	}
 7578: 	my ($map,$resid,$url)=&decode_symb($symb);
 7579: 	my $title='';
 7580: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 7581: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 7582: 	} else {
 7583: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7584: 		    &GDBM_READER(),0640)) {
 7585: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 7586: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 7587: 		untie(%bighash);
 7588: 	    }
 7589: 	}
 7590: 	$title=~s/\&colon\;/\:/gs;
 7591: 	if ($title) {
 7592: 	    return &do_cache_new('title',$key,$title,600);
 7593: 	}
 7594: 	$urlsymb=$url;
 7595:     }
 7596:     my $title=&metadata($urlsymb,'title');
 7597:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 7598:     return $title;
 7599: }
 7600: 
 7601: sub get_slot {
 7602:     my ($which,$cnum,$cdom)=@_;
 7603:     if (!$cnum || !$cdom) {
 7604: 	(undef,my $courseid)=&whichuser();
 7605: 	$cdom=$env{'course.'.$courseid.'.domain'};
 7606: 	$cnum=$env{'course.'.$courseid.'.num'};
 7607:     }
 7608:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 7609:     my %slotinfo;
 7610:     if (exists($remembered{$key})) {
 7611: 	$slotinfo{$which} = $remembered{$key};
 7612:     } else {
 7613: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 7614: 	&Apache::lonhomework::showhash(%slotinfo);
 7615: 	my ($tmp)=keys(%slotinfo);
 7616: 	if ($tmp=~/^error:/) { return (); }
 7617: 	$remembered{$key} = $slotinfo{$which};
 7618:     }
 7619:     if (ref($slotinfo{$which}) eq 'HASH') {
 7620: 	return %{$slotinfo{$which}};
 7621:     }
 7622:     return $slotinfo{$which};
 7623: }
 7624: # ------------------------------------------------- Update symbolic store links
 7625: 
 7626: sub symblist {
 7627:     my ($mapname,%newhash)=@_;
 7628:     $mapname=&deversion(&declutter($mapname));
 7629:     my %hash;
 7630:     if (($env{'request.course.fn'}) && (%newhash)) {
 7631:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7632:                       &GDBM_WRCREAT(),0640)) {
 7633: 	    foreach my $url (keys %newhash) {
 7634: 		next if ($url eq 'last_known'
 7635: 			 && $env{'form.no_update_last_known'});
 7636: 		$hash{declutter($url)}=&encode_symb($mapname,
 7637: 						    $newhash{$url}->[1],
 7638: 						    $newhash{$url}->[0]);
 7639:             }
 7640:             if (untie(%hash)) {
 7641: 		return 'ok';
 7642:             }
 7643:         }
 7644:     }
 7645:     return 'error';
 7646: }
 7647: 
 7648: # --------------------------------------------------------------- Verify a symb
 7649: 
 7650: sub symbverify {
 7651:     my ($symb,$thisurl)=@_;
 7652:     my $thisfn=$thisurl;
 7653:     $thisfn=&declutter($thisfn);
 7654: # direct jump to resource in page or to a sequence - will construct own symbs
 7655:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 7656: # check URL part
 7657:     my ($map,$resid,$url)=&decode_symb($symb);
 7658: 
 7659:     unless ($url eq $thisfn) { return 0; }
 7660: 
 7661:     $symb=&symbclean($symb);
 7662:     $thisurl=&deversion($thisurl);
 7663:     $thisfn=&deversion($thisfn);
 7664: 
 7665:     my %bighash;
 7666:     my $okay=0;
 7667: 
 7668:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7669:                             &GDBM_READER(),0640)) {
 7670:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 7671:         unless ($ids) { 
 7672:            $ids=$bighash{'ids_/'.$thisurl};
 7673:         }
 7674:         if ($ids) {
 7675: # ------------------------------------------------------------------- Has ID(s)
 7676: 	    foreach my $id (split(/\,/,$ids)) {
 7677: 	       my ($mapid,$resid)=split(/\./,$id);
 7678:                if (
 7679:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 7680:    eq $symb) { 
 7681: 		   if (($env{'request.role.adv'}) ||
 7682: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 7683: 		       $okay=1; 
 7684: 		   }
 7685: 	       }
 7686: 	   }
 7687:         }
 7688: 	untie(%bighash);
 7689:     }
 7690:     return $okay;
 7691: }
 7692: 
 7693: # --------------------------------------------------------------- Clean-up symb
 7694: 
 7695: sub symbclean {
 7696:     my $symb=shift;
 7697:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7698: # remove version from map
 7699:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 7700: 
 7701: # remove version from URL
 7702:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 7703: 
 7704: # remove wrapper
 7705: 
 7706:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 7707:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 7708:     return $symb;
 7709: }
 7710: 
 7711: # ---------------------------------------------- Split symb to find map and url
 7712: 
 7713: sub encode_symb {
 7714:     my ($map,$resid,$url)=@_;
 7715:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 7716: }
 7717: 
 7718: sub decode_symb {
 7719:     my $symb=shift;
 7720:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7721:     my ($map,$resid,$url)=split(/___/,$symb);
 7722:     return (&fixversion($map),$resid,&fixversion($url));
 7723: }
 7724: 
 7725: sub fixversion {
 7726:     my $fn=shift;
 7727:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 7728:     my %bighash;
 7729:     my $uri=&clutter($fn);
 7730:     my $key=$env{'request.course.id'}.'_'.$uri;
 7731: # is this cached?
 7732:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 7733:     if (defined($cached)) { return $result; }
 7734: # unfortunately not cached, or expired
 7735:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7736: 	    &GDBM_READER(),0640)) {
 7737:  	if ($bighash{'version_'.$uri}) {
 7738:  	    my $version=$bighash{'version_'.$uri};
 7739:  	    unless (($version eq 'mostrecent') || 
 7740: 		    ($version==&getversion($uri))) {
 7741:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 7742:  	    }
 7743:  	}
 7744:  	untie %bighash;
 7745:     }
 7746:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 7747: }
 7748: 
 7749: sub deversion {
 7750:     my $url=shift;
 7751:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 7752:     return $url;
 7753: }
 7754: 
 7755: # ------------------------------------------------------ Return symb list entry
 7756: 
 7757: sub symbread {
 7758:     my ($thisfn,$donotrecurse)=@_;
 7759:     my $cache_str='request.symbread.cached.'.$thisfn;
 7760:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 7761: # no filename provided? try from environment
 7762:     unless ($thisfn) {
 7763:         if ($env{'request.symb'}) {
 7764: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 7765: 	}
 7766: 	$thisfn=$env{'request.filename'};
 7767:     }
 7768:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7769: # is that filename actually a symb? Verify, clean, and return
 7770:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 7771: 	if (&symbverify($thisfn,$1)) {
 7772: 	    return $env{$cache_str}=&symbclean($thisfn);
 7773: 	}
 7774:     }
 7775:     $thisfn=declutter($thisfn);
 7776:     my %hash;
 7777:     my %bighash;
 7778:     my $syval='';
 7779:     if (($env{'request.course.fn'}) && ($thisfn)) {
 7780:         my $targetfn = $thisfn;
 7781:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 7782:             $targetfn = 'adm/wrapper/'.$thisfn;
 7783:         }
 7784: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 7785: 	    $targetfn=$1;
 7786: 	}
 7787:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7788:                       &GDBM_READER(),0640)) {
 7789: 	    $syval=$hash{$targetfn};
 7790:             untie(%hash);
 7791:         }
 7792: # ---------------------------------------------------------- There was an entry
 7793:         if ($syval) {
 7794: 	    #unless ($syval=~/\_\d+$/) {
 7795: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 7796: 		    #&appenv({'request.ambiguous' => $thisfn});
 7797: 		    #return $env{$cache_str}='';
 7798: 		#}    
 7799: 		#$syval.=$1;
 7800: 	    #}
 7801:         } else {
 7802: # ------------------------------------------------------- Was not in symb table
 7803:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7804:                             &GDBM_READER(),0640)) {
 7805: # ---------------------------------------------- Get ID(s) for current resource
 7806:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 7807:               unless ($ids) { 
 7808:                  $ids=$bighash{'ids_/'.$thisfn};
 7809:               }
 7810:               unless ($ids) {
 7811: # alias?
 7812: 		  $ids=$bighash{'mapalias_'.$thisfn};
 7813:               }
 7814:               if ($ids) {
 7815: # ------------------------------------------------------------------- Has ID(s)
 7816:                  my @possibilities=split(/\,/,$ids);
 7817:                  if ($#possibilities==0) {
 7818: # ----------------------------------------------- There is only one possibility
 7819: 		     my ($mapid,$resid)=split(/\./,$ids);
 7820: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7821: 						    $resid,$thisfn);
 7822:                  } elsif (!$donotrecurse) {
 7823: # ------------------------------------------ There is more than one possibility
 7824:                      my $realpossible=0;
 7825:                      foreach my $id (@possibilities) {
 7826: 			 my $file=$bighash{'src_'.$id};
 7827:                          if (&allowed('bre',$file)) {
 7828:          		    my ($mapid,$resid)=split(/\./,$id);
 7829:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 7830: 				$realpossible++;
 7831:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7832: 						    $resid,$thisfn);
 7833:                             }
 7834: 			 }
 7835:                      }
 7836: 		     if ($realpossible!=1) { $syval=''; }
 7837:                  } else {
 7838:                      $syval='';
 7839:                  }
 7840: 	      }
 7841:               untie(%bighash)
 7842:            }
 7843:         }
 7844:         if ($syval) {
 7845: 	    return $env{$cache_str}=$syval;
 7846:         }
 7847:     }
 7848:     &appenv({'request.ambiguous' => $thisfn});
 7849:     return $env{$cache_str}='';
 7850: }
 7851: 
 7852: # ---------------------------------------------------------- Return random seed
 7853: 
 7854: sub numval {
 7855:     my $txt=shift;
 7856:     $txt=~tr/A-J/0-9/;
 7857:     $txt=~tr/a-j/0-9/;
 7858:     $txt=~tr/K-T/0-9/;
 7859:     $txt=~tr/k-t/0-9/;
 7860:     $txt=~tr/U-Z/0-5/;
 7861:     $txt=~tr/u-z/0-5/;
 7862:     $txt=~s/\D//g;
 7863:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 7864:     return int($txt);
 7865: }
 7866: 
 7867: sub numval2 {
 7868:     my $txt=shift;
 7869:     $txt=~tr/A-J/0-9/;
 7870:     $txt=~tr/a-j/0-9/;
 7871:     $txt=~tr/K-T/0-9/;
 7872:     $txt=~tr/k-t/0-9/;
 7873:     $txt=~tr/U-Z/0-5/;
 7874:     $txt=~tr/u-z/0-5/;
 7875:     $txt=~s/\D//g;
 7876:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7877:     my $total;
 7878:     foreach my $val (@txts) { $total+=$val; }
 7879:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 7880:     return int($total);
 7881: }
 7882: 
 7883: sub numval3 {
 7884:     use integer;
 7885:     my $txt=shift;
 7886:     $txt=~tr/A-J/0-9/;
 7887:     $txt=~tr/a-j/0-9/;
 7888:     $txt=~tr/K-T/0-9/;
 7889:     $txt=~tr/k-t/0-9/;
 7890:     $txt=~tr/U-Z/0-5/;
 7891:     $txt=~tr/u-z/0-5/;
 7892:     $txt=~s/\D//g;
 7893:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7894:     my $total;
 7895:     foreach my $val (@txts) { $total+=$val; }
 7896:     if ($_64bit) { $total=(($total<<32)>>32); }
 7897:     return $total;
 7898: }
 7899: 
 7900: sub digest {
 7901:     my ($data)=@_;
 7902:     my $digest=&Digest::MD5::md5($data);
 7903:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 7904:     my ($e,$f);
 7905:     {
 7906:         use integer;
 7907:         $e=($a+$b);
 7908:         $f=($c+$d);
 7909:         if ($_64bit) {
 7910:             $e=(($e<<32)>>32);
 7911:             $f=(($f<<32)>>32);
 7912:         }
 7913:     }
 7914:     if (wantarray) {
 7915: 	return ($e,$f);
 7916:     } else {
 7917: 	my $g;
 7918: 	{
 7919: 	    use integer;
 7920: 	    $g=($e+$f);
 7921: 	    if ($_64bit) {
 7922: 		$g=(($g<<32)>>32);
 7923: 	    }
 7924: 	}
 7925: 	return $g;
 7926:     }
 7927: }
 7928: 
 7929: sub latest_rnd_algorithm_id {
 7930:     return '64bit5';
 7931: }
 7932: 
 7933: sub get_rand_alg {
 7934:     my ($courseid)=@_;
 7935:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 7936:     if ($courseid) {
 7937: 	return $env{"course.$courseid.rndseed"};
 7938:     }
 7939:     return &latest_rnd_algorithm_id();
 7940: }
 7941: 
 7942: sub validCODE {
 7943:     my ($CODE)=@_;
 7944:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 7945:     return 0;
 7946: }
 7947: 
 7948: sub getCODE {
 7949:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 7950:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 7951: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 7952: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 7953: 	return $Apache::lonhomework::history{'resource.CODE'};
 7954:     }
 7955:     return undef;
 7956: }
 7957: 
 7958: sub rndseed {
 7959:     my ($symb,$courseid,$domain,$username)=@_;
 7960:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 7961:     if (!defined($symb)) {
 7962: 	unless ($symb=$wsymb) { return time; }
 7963:     }
 7964:     if (!$courseid) { $courseid=$wcourseid; }
 7965:     if (!$domain) { $domain=$wdomain; }
 7966:     if (!$username) { $username=$wusername }
 7967:     my $which=&get_rand_alg();
 7968: 
 7969:     if (defined(&getCODE())) {
 7970: 	if ($which eq '64bit5') {
 7971: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 7972: 	} elsif ($which eq '64bit4') {
 7973: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 7974: 	} else {
 7975: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 7976: 	}
 7977:     } elsif ($which eq '64bit5') {
 7978: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 7979:     } elsif ($which eq '64bit4') {
 7980: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 7981:     } elsif ($which eq '64bit3') {
 7982: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 7983:     } elsif ($which eq '64bit2') {
 7984: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 7985:     } elsif ($which eq '64bit') {
 7986: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 7987:     }
 7988:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 7989: }
 7990: 
 7991: sub rndseed_32bit {
 7992:     my ($symb,$courseid,$domain,$username)=@_;
 7993:     {
 7994: 	use integer;
 7995: 	my $symbchck=unpack("%32C*",$symb) << 27;
 7996: 	my $symbseed=numval($symb) << 22;
 7997: 	my $namechck=unpack("%32C*",$username) << 17;
 7998: 	my $nameseed=numval($username) << 12;
 7999: 	my $domainseed=unpack("%32C*",$domain) << 7;
 8000: 	my $courseseed=unpack("%32C*",$courseid);
 8001: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 8002: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8003: 	#&logthis("rndseed :$num:$symb");
 8004: 	if ($_64bit) { $num=(($num<<32)>>32); }
 8005: 	return $num;
 8006:     }
 8007: }
 8008: 
 8009: sub rndseed_64bit {
 8010:     my ($symb,$courseid,$domain,$username)=@_;
 8011:     {
 8012: 	use integer;
 8013: 	my $symbchck=unpack("%32S*",$symb) << 21;
 8014: 	my $symbseed=numval($symb) << 10;
 8015: 	my $namechck=unpack("%32S*",$username);
 8016: 	
 8017: 	my $nameseed=numval($username) << 21;
 8018: 	my $domainseed=unpack("%32S*",$domain) << 10;
 8019: 	my $courseseed=unpack("%32S*",$courseid);
 8020: 	
 8021: 	my $num1=$symbchck+$symbseed+$namechck;
 8022: 	my $num2=$nameseed+$domainseed+$courseseed;
 8023: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8024: 	#&logthis("rndseed :$num:$symb");
 8025: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8026: 	return "$num1,$num2";
 8027:     }
 8028: }
 8029: 
 8030: sub rndseed_64bit2 {
 8031:     my ($symb,$courseid,$domain,$username)=@_;
 8032:     {
 8033: 	use integer;
 8034: 	# strings need to be an even # of cahracters long, it it is odd the
 8035:         # last characters gets thrown away
 8036: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8037: 	my $symbseed=numval($symb) << 10;
 8038: 	my $namechck=unpack("%32S*",$username.' ');
 8039: 	
 8040: 	my $nameseed=numval($username) << 21;
 8041: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8042: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8043: 	
 8044: 	my $num1=$symbchck+$symbseed+$namechck;
 8045: 	my $num2=$nameseed+$domainseed+$courseseed;
 8046: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8047: 	#&logthis("rndseed :$num:$symb");
 8048: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8049: 	return "$num1,$num2";
 8050:     }
 8051: }
 8052: 
 8053: sub rndseed_64bit3 {
 8054:     my ($symb,$courseid,$domain,$username)=@_;
 8055:     {
 8056: 	use integer;
 8057: 	# strings need to be an even # of cahracters long, it it is odd the
 8058:         # last characters gets thrown away
 8059: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8060: 	my $symbseed=numval2($symb) << 10;
 8061: 	my $namechck=unpack("%32S*",$username.' ');
 8062: 	
 8063: 	my $nameseed=numval2($username) << 21;
 8064: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8065: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8066: 	
 8067: 	my $num1=$symbchck+$symbseed+$namechck;
 8068: 	my $num2=$nameseed+$domainseed+$courseseed;
 8069: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8070: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8071: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8072: 	
 8073: 	return "$num1:$num2";
 8074:     }
 8075: }
 8076: 
 8077: sub rndseed_64bit4 {
 8078:     my ($symb,$courseid,$domain,$username)=@_;
 8079:     {
 8080: 	use integer;
 8081: 	# strings need to be an even # of cahracters long, it it is odd the
 8082:         # last characters gets thrown away
 8083: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8084: 	my $symbseed=numval3($symb) << 10;
 8085: 	my $namechck=unpack("%32S*",$username.' ');
 8086: 	
 8087: 	my $nameseed=numval3($username) << 21;
 8088: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8089: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8090: 	
 8091: 	my $num1=$symbchck+$symbseed+$namechck;
 8092: 	my $num2=$nameseed+$domainseed+$courseseed;
 8093: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8094: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8095: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8096: 	
 8097: 	return "$num1:$num2";
 8098:     }
 8099: }
 8100: 
 8101: sub rndseed_64bit5 {
 8102:     my ($symb,$courseid,$domain,$username)=@_;
 8103:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 8104:     return "$num1:$num2";
 8105: }
 8106: 
 8107: sub rndseed_CODE_64bit {
 8108:     my ($symb,$courseid,$domain,$username)=@_;
 8109:     {
 8110: 	use integer;
 8111: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8112: 	my $symbseed=numval2($symb);
 8113: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8114: 	my $CODEseed=numval(&getCODE());
 8115: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8116: 	my $num1=$symbseed+$CODEchck;
 8117: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8118: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8119: 	#&logthis("rndseed :$num1:$num2:$symb");
 8120: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8121: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8122: 	return "$num1:$num2";
 8123:     }
 8124: }
 8125: 
 8126: sub rndseed_CODE_64bit4 {
 8127:     my ($symb,$courseid,$domain,$username)=@_;
 8128:     {
 8129: 	use integer;
 8130: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8131: 	my $symbseed=numval3($symb);
 8132: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8133: 	my $CODEseed=numval3(&getCODE());
 8134: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8135: 	my $num1=$symbseed+$CODEchck;
 8136: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8137: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8138: 	#&logthis("rndseed :$num1:$num2:$symb");
 8139: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8140: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8141: 	return "$num1:$num2";
 8142:     }
 8143: }
 8144: 
 8145: sub rndseed_CODE_64bit5 {
 8146:     my ($symb,$courseid,$domain,$username)=@_;
 8147:     my $code = &getCODE();
 8148:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 8149:     return "$num1:$num2";
 8150: }
 8151: 
 8152: sub setup_random_from_rndseed {
 8153:     my ($rndseed)=@_;
 8154:     if ($rndseed =~/([,:])/) {
 8155: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 8156: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 8157:     } else {
 8158: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 8159:     }
 8160: }
 8161: 
 8162: sub latest_receipt_algorithm_id {
 8163:     return 'receipt3';
 8164: }
 8165: 
 8166: sub recunique {
 8167:     my $fucourseid=shift;
 8168:     my $unique;
 8169:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 8170: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8171: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 8172:     } else {
 8173: 	$unique=$perlvar{'lonReceipt'};
 8174:     }
 8175:     return unpack("%32C*",$unique);
 8176: }
 8177: 
 8178: sub recprefix {
 8179:     my $fucourseid=shift;
 8180:     my $prefix;
 8181:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 8182: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8183: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 8184:     } else {
 8185: 	$prefix=$perlvar{'lonHostID'};
 8186:     }
 8187:     return unpack("%32C*",$prefix);
 8188: }
 8189: 
 8190: sub ireceipt {
 8191:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 8192: 
 8193:     my $return =&recprefix($fucourseid).'-';
 8194: 
 8195:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 8196: 	$env{'request.state'} eq 'construct') {
 8197: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 8198: 	return $return;
 8199:     }
 8200: 
 8201:     my $cuname=unpack("%32C*",$funame);
 8202:     my $cudom=unpack("%32C*",$fudom);
 8203:     my $cucourseid=unpack("%32C*",$fucourseid);
 8204:     my $cusymb=unpack("%32C*",$fusymb);
 8205:     my $cunique=&recunique($fucourseid);
 8206:     my $cpart=unpack("%32S*",$part);
 8207:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 8208: 
 8209: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 8210: 			       
 8211: 	$return.= ($cunique%$cuname+
 8212: 		   $cunique%$cudom+
 8213: 		   $cusymb%$cuname+
 8214: 		   $cusymb%$cudom+
 8215: 		   $cucourseid%$cuname+
 8216: 		   $cucourseid%$cudom+
 8217: 		   $cpart%$cuname+
 8218: 		   $cpart%$cudom);
 8219:     } else {
 8220: 	$return.= ($cunique%$cuname+
 8221: 		   $cunique%$cudom+
 8222: 		   $cusymb%$cuname+
 8223: 		   $cusymb%$cudom+
 8224: 		   $cucourseid%$cuname+
 8225: 		   $cucourseid%$cudom);
 8226:     }
 8227:     return $return;
 8228: }
 8229: 
 8230: sub receipt {
 8231:     my ($part)=@_;
 8232:     my ($symb,$courseid,$domain,$name) = &whichuser();
 8233:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 8234: }
 8235: 
 8236: sub whichuser {
 8237:     my ($passedsymb)=@_;
 8238:     my ($symb,$courseid,$domain,$name,$publicuser);
 8239:     if (defined($env{'form.grade_symb'})) {
 8240: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 8241: 	my $allowed=&allowed('vgr',$tmp_courseid);
 8242: 	if (!$allowed &&
 8243: 	    exists($env{'request.course.sec'}) &&
 8244: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 8245: 	    $allowed=&allowed('vgr',$tmp_courseid.
 8246: 			      '/'.$env{'request.course.sec'});
 8247: 	}
 8248: 	if ($allowed) {
 8249: 	    ($symb)=&get_env_multiple('form.grade_symb');
 8250: 	    $courseid=$tmp_courseid;
 8251: 	    ($domain)=&get_env_multiple('form.grade_domain');
 8252: 	    ($name)=&get_env_multiple('form.grade_username');
 8253: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 8254: 	}
 8255:     }
 8256:     if (!$passedsymb) {
 8257: 	$symb=&symbread();
 8258:     } else {
 8259: 	$symb=$passedsymb;
 8260:     }
 8261:     $courseid=$env{'request.course.id'};
 8262:     $domain=$env{'user.domain'};
 8263:     $name=$env{'user.name'};
 8264:     if ($name eq 'public' && $domain eq 'public') {
 8265: 	if (!defined($env{'form.username'})) {
 8266: 	    $env{'form.username'}.=time.rand(10000000);
 8267: 	}
 8268: 	$name.=$env{'form.username'};
 8269:     }
 8270:     return ($symb,$courseid,$domain,$name,$publicuser);
 8271: 
 8272: }
 8273: 
 8274: # ------------------------------------------------------------ Serves up a file
 8275: # returns either the contents of the file or 
 8276: # -1 if the file doesn't exist
 8277: #
 8278: # if the target is a file that was uploaded via DOCS, 
 8279: # a check will be made to see if a current copy exists on the local server,
 8280: # if it does this will be served, otherwise a copy will be retrieved from
 8281: # the home server for the course and stored in /home/httpd/html/userfiles on
 8282: # the local server.   
 8283: 
 8284: sub getfile {
 8285:     my ($file) = @_;
 8286:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8287:     &repcopy($file);
 8288:     return &readfile($file);
 8289: }
 8290: 
 8291: sub repcopy_userfile {
 8292:     my ($file)=@_;
 8293:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8294:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 8295:     my ($cdom,$cnum,$filename) = 
 8296: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 8297:     my $uri="/uploaded/$cdom/$cnum/$filename";
 8298:     if (-e "$file") {
 8299: # we already have a local copy, check it out
 8300: 	my @fileinfo = stat($file);
 8301: 	my $rtncode;
 8302: 	my $info;
 8303: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 8304: 	if ($lwpresp ne 'ok') {
 8305: # there is no such file anymore, even though we had a local copy
 8306: 	    if ($rtncode eq '404') {
 8307: 		unlink($file);
 8308: 	    }
 8309: 	    return -1;
 8310: 	}
 8311: 	if ($info < $fileinfo[9]) {
 8312: # nice, the file we have is up-to-date, just say okay
 8313: 	    return 'ok';
 8314: 	} else {
 8315: # the file is outdated, get rid of it
 8316: 	    unlink($file);
 8317: 	}
 8318:     }
 8319: # one way or the other, at this point, we don't have the file
 8320: # construct the correct path for the file
 8321:     my @parts = ($cdom,$cnum); 
 8322:     if ($filename =~ m|^(.+)/[^/]+$|) {
 8323: 	push @parts, split(/\//,$1);
 8324:     }
 8325:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 8326:     foreach my $part (@parts) {
 8327: 	$path .= '/'.$part;
 8328: 	if (!-e $path) {
 8329: 	    mkdir($path,0770);
 8330: 	}
 8331:     }
 8332: # now the path exists for sure
 8333: # get a user agent
 8334:     my $ua=new LWP::UserAgent;
 8335:     my $transferfile=$file.'.in.transfer';
 8336: # FIXME: this should flock
 8337:     if (-e $transferfile) { return 'ok'; }
 8338:     my $request;
 8339:     $uri=~s/^\///;
 8340:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
 8341:     my $response=$ua->request($request,$transferfile);
 8342: # did it work?
 8343:     if ($response->is_error()) {
 8344: 	unlink($transferfile);
 8345: 	&logthis("Userfile repcopy failed for $uri");
 8346: 	return -1;
 8347:     }
 8348: # worked, rename the transfer file
 8349:     rename($transferfile,$file);
 8350:     return 'ok';
 8351: }
 8352: 
 8353: sub tokenwrapper {
 8354:     my $uri=shift;
 8355:     $uri=~s|^http\://([^/]+)||;
 8356:     $uri=~s|^/||;
 8357:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 8358:     my $token=$1;
 8359:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 8360:     if ($udom && $uname && $file) {
 8361: 	$file=~s|(\?\.*)*$||;
 8362:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 8363:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
 8364:                (($uri=~/\?/)?'&':'?').'token='.$token.
 8365:                                '&tokenissued='.$perlvar{'lonHostID'};
 8366:     } else {
 8367:         return '/adm/notfound.html';
 8368:     }
 8369: }
 8370: 
 8371: # call with reqtype HEAD: get last modification time
 8372: # call with reqtype GET: get the file contents
 8373: # Do not call this with reqtype GET for large files! It loads everything into memory
 8374: #
 8375: sub getuploaded {
 8376:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 8377:     $uri=~s/^\///;
 8378:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
 8379:     my $ua=new LWP::UserAgent;
 8380:     my $request=new HTTP::Request($reqtype,$uri);
 8381:     my $response=$ua->request($request);
 8382:     $$rtncode = $response->code;
 8383:     if (! $response->is_success()) {
 8384: 	return 'failed';
 8385:     }      
 8386:     if ($reqtype eq 'HEAD') {
 8387: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 8388:     } elsif ($reqtype eq 'GET') {
 8389: 	$$info = $response->content;
 8390:     }
 8391:     return 'ok';
 8392: }
 8393: 
 8394: sub readfile {
 8395:     my $file = shift;
 8396:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 8397:     my $fh;
 8398:     open($fh,"<$file");
 8399:     my $a='';
 8400:     while (my $line = <$fh>) { $a .= $line; }
 8401:     return $a;
 8402: }
 8403: 
 8404: sub filelocation {
 8405:     my ($dir,$file) = @_;
 8406:     my $location;
 8407:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 8408: 
 8409:     if ($file =~ m-^/adm/-) {
 8410: 	$file=~s-^/adm/wrapper/-/-;
 8411: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8412:     }
 8413: 
 8414:     if ($file=~m:^/~:) { # is a contruction space reference
 8415:         $location = $file;
 8416:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 8417:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 8418: 	# is a correct contruction space reference
 8419:         $location = $file;
 8420:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
 8421:         $location = $file;
 8422:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 8423:         my ($udom,$uname,$filename)=
 8424:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 8425:         my $home=&homeserver($uname,$udom);
 8426:         my $is_me=0;
 8427:         my @ids=&current_machine_ids();
 8428:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 8429:         if ($is_me) {
 8430:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
 8431:         } else {
 8432:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 8433:   	      $udom.'/'.$uname.'/'.$filename;
 8434:         }
 8435:     } elsif ($file =~ m-^/adm/-) {
 8436: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 8437:     } else {
 8438:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8439:         $file=~s:^/res/:/:;
 8440:         if ( !( $file =~ m:^/:) ) {
 8441:             $location = $dir. '/'.$file;
 8442:         } else {
 8443:             $location = '/home/httpd/html/res'.$file;
 8444:         }
 8445:     }
 8446:     $location=~s://+:/:g; # remove duplicate /
 8447:     while ($location=~m{/\.\./}) {
 8448: 	if ($location =~ m{/[^/]+/\.\./}) {
 8449: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 8450: 	} else {
 8451: 	    $location=~ s{/\.\./}{/}g;
 8452: 	}
 8453:     } #remove dir/..
 8454:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 8455:     return $location;
 8456: }
 8457: 
 8458: sub hreflocation {
 8459:     my ($dir,$file)=@_;
 8460:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 8461: 	$file=filelocation($dir,$file);
 8462:     } elsif ($file=~m-^/adm/-) {
 8463: 	$file=~s-^/adm/wrapper/-/-;
 8464: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8465:     }
 8466:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 8467: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 8468:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 8469: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 8470:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 8471: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 8472: 	    -/uploaded/$1/$2/-x;
 8473:     }
 8474:     if ($file=~ m{^/userfiles/}) {
 8475: 	$file =~ s{^/userfiles/}{/uploaded/};
 8476:     }
 8477:     return $file;
 8478: }
 8479: 
 8480: sub current_machine_domains {
 8481:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 8482: }
 8483: 
 8484: sub machine_domains {
 8485:     my ($hostname) = @_;
 8486:     my @domains;
 8487:     my %hostname = &all_hostnames();
 8488:     while( my($id, $name) = each(%hostname)) {
 8489: #	&logthis("-$id-$name-$hostname-");
 8490: 	if ($hostname eq $name) {
 8491: 	    push(@domains,&host_domain($id));
 8492: 	}
 8493:     }
 8494:     return @domains;
 8495: }
 8496: 
 8497: sub current_machine_ids {
 8498:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 8499: }
 8500: 
 8501: sub machine_ids {
 8502:     my ($hostname) = @_;
 8503:     $hostname ||= &hostname($perlvar{'lonHostID'});
 8504:     my @ids;
 8505:     my %name_to_host = &all_names();
 8506:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 8507: 	return @{ $name_to_host{$hostname} };
 8508:     }
 8509:     return;
 8510: }
 8511: 
 8512: sub additional_machine_domains {
 8513:     my @domains;
 8514:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 8515:     while( my $line = <$fh>) {
 8516:         $line =~ s/\s//g;
 8517:         push(@domains,$line);
 8518:     }
 8519:     return @domains;
 8520: }
 8521: 
 8522: sub default_login_domain {
 8523:     my $domain = $perlvar{'lonDefDomain'};
 8524:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 8525:     foreach my $posdom (&current_machine_domains(),
 8526:                         &additional_machine_domains()) {
 8527:         if (lc($posdom) eq lc($testdomain)) {
 8528:             $domain=$posdom;
 8529:             last;
 8530:         }
 8531:     }
 8532:     return $domain;
 8533: }
 8534: 
 8535: # ------------------------------------------------------------- Declutters URLs
 8536: 
 8537: sub declutter {
 8538:     my $thisfn=shift;
 8539:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8540:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8541:     $thisfn=~s/^\///;
 8542:     $thisfn=~s|^adm/wrapper/||;
 8543:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 8544:     $thisfn=~s/^res\///;
 8545:     $thisfn=~s/\?.+$//;
 8546:     return $thisfn;
 8547: }
 8548: 
 8549: # ------------------------------------------------------------- Clutter up URLs
 8550: 
 8551: sub clutter {
 8552:     my $thisfn='/'.&declutter(shift);
 8553:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 8554: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 8555:        $thisfn='/res'.$thisfn; 
 8556:     }
 8557:     if ($thisfn !~m|/adm|) {
 8558: 	if ($thisfn =~ m|/ext/|) {
 8559: 	    $thisfn='/adm/wrapper'.$thisfn;
 8560: 	} else {
 8561: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 8562: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 8563: 	    if ($embstyle eq 'ssi'
 8564: 		|| ($embstyle eq 'hdn')
 8565: 		|| ($embstyle eq 'rat')
 8566: 		|| ($embstyle eq 'prv')
 8567: 		|| ($embstyle eq 'ign')) {
 8568: 		#do nothing with these
 8569: 	    } elsif (($embstyle eq 'img') 
 8570: 		|| ($embstyle eq 'emb')
 8571: 		|| ($embstyle eq 'wrp')) {
 8572: 		$thisfn='/adm/wrapper'.$thisfn;
 8573: 	    } elsif ($embstyle eq 'unk'
 8574: 		     && $thisfn!~/\.(sequence|page)$/) {
 8575: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 8576: 	    } else {
 8577: #		&logthis("Got a blank emb style");
 8578: 	    }
 8579: 	}
 8580:     }
 8581:     return $thisfn;
 8582: }
 8583: 
 8584: sub clutter_with_no_wrapper {
 8585:     my $uri = &clutter(shift);
 8586:     if ($uri =~ m-^/adm/-) {
 8587: 	$uri =~ s-^/adm/wrapper/-/-;
 8588: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 8589:     }
 8590:     return $uri;
 8591: }
 8592: 
 8593: sub freeze_escape {
 8594:     my ($value)=@_;
 8595:     if (ref($value)) {
 8596: 	$value=&nfreeze($value);
 8597: 	return '__FROZEN__'.&escape($value);
 8598:     }
 8599:     return &escape($value);
 8600: }
 8601: 
 8602: 
 8603: sub thaw_unescape {
 8604:     my ($value)=@_;
 8605:     if ($value =~ /^__FROZEN__/) {
 8606: 	substr($value,0,10,undef);
 8607: 	$value=&unescape($value);
 8608: 	return &thaw($value);
 8609:     }
 8610:     return &unescape($value);
 8611: }
 8612: 
 8613: sub correct_line_ends {
 8614:     my ($result)=@_;
 8615:     $$result =~s/\r\n/\n/mg;
 8616:     $$result =~s/\r/\n/mg;
 8617: }
 8618: # ================================================================ Main Program
 8619: 
 8620: sub goodbye {
 8621:    &logthis("Starting Shut down");
 8622: #not converted to using infrastruture and probably shouldn't be
 8623:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 8624: #converted
 8625: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 8626:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 8627: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 8628: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 8629: #1.1 only
 8630: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 8631: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 8632: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 8633: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 8634:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 8635:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 8636:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 8637:    &flushcourselogs();
 8638:    &logthis("Shutting down");
 8639: }
 8640: 
 8641: sub get_dns {
 8642:     my ($url,$func,$ignore_cache) = @_;
 8643:     if (!$ignore_cache) {
 8644: 	my ($content,$cached)=
 8645: 	    &Apache::lonnet::is_cached_new('dns',$url);
 8646: 	if ($cached) {
 8647: 	    &$func($content);
 8648: 	    return;
 8649: 	}
 8650:     }
 8651: 
 8652:     my %alldns;
 8653:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8654:     foreach my $dns (<$config>) {
 8655: 	next if ($dns !~ /^\^(\S*)/x);
 8656: 	$alldns{$1} = 1;
 8657:     }
 8658:     while (%alldns) {
 8659: 	my ($dns) = keys(%alldns);
 8660: 	delete($alldns{$dns});
 8661: 	my $ua=new LWP::UserAgent;
 8662: 	my $request=new HTTP::Request('GET',"http://$dns$url");
 8663: 	my $response=$ua->request($request);
 8664: 	next if ($response->is_error());
 8665: 	my @content = split("\n",$response->content);
 8666: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 8667: 	&$func(\@content);
 8668: 	return;
 8669:     }
 8670:     close($config);
 8671:     my $which = (split('/',$url))[3];
 8672:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 8673:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 8674:     my @content = <$config>;
 8675:     &$func(\@content);
 8676:     return;
 8677: }
 8678: # ------------------------------------------------------------ Read domain file
 8679: {
 8680:     my $loaded;
 8681:     my %domain;
 8682: 
 8683:     sub parse_domain_tab {
 8684: 	my ($lines) = @_;
 8685: 	foreach my $line (@$lines) {
 8686: 	    next if ($line =~ /^(\#|\s*$ )/x);
 8687: 
 8688: 	    chomp($line);
 8689: 	    my ($name,@elements) = split(/:/,$line,9);
 8690: 	    my %this_domain;
 8691: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 8692: 			       'lang_def', 'city', 'longi', 'lati',
 8693: 			       'primary') {
 8694: 		$this_domain{$field} = shift(@elements);
 8695: 	    }
 8696: 	    $domain{$name} = \%this_domain;
 8697: 	}
 8698:     }
 8699: 
 8700:     sub reset_domain_info {
 8701: 	undef($loaded);
 8702: 	undef(%domain);
 8703:     }
 8704: 
 8705:     sub load_domain_tab {
 8706: 	my ($ignore_cache) = @_;
 8707: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 8708: 	my $fh;
 8709: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 8710: 	    my @lines = <$fh>;
 8711: 	    &parse_domain_tab(\@lines);
 8712: 	}
 8713: 	close($fh);
 8714: 	$loaded = 1;
 8715:     }
 8716: 
 8717:     sub domain {
 8718: 	&load_domain_tab() if (!$loaded);
 8719: 
 8720: 	my ($name,$what) = @_;
 8721: 	return if ( !exists($domain{$name}) );
 8722: 
 8723: 	if (!$what) {
 8724: 	    return $domain{$name}{'description'};
 8725: 	}
 8726: 	return $domain{$name}{$what};
 8727:     }
 8728: 
 8729:     sub domain_info {
 8730:         &load_domain_tab() if (!$loaded);
 8731:         return %domain;
 8732:     }
 8733: 
 8734: }
 8735: 
 8736: 
 8737: # ------------------------------------------------------------- Read hosts file
 8738: {
 8739:     my %hostname;
 8740:     my %hostdom;
 8741:     my %libserv;
 8742:     my $loaded;
 8743:     my %name_to_host;
 8744: 
 8745:     sub parse_hosts_tab {
 8746: 	my ($file) = @_;
 8747: 	foreach my $configline (@$file) {
 8748: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 8749: 	    next if ($configline =~ /^\^/);
 8750: 	    chomp($configline);
 8751: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
 8752: 	    $name=~s/\s//g;
 8753: 	    if ($id && $domain && $role && $name) {
 8754: 		$hostname{$id}=$name;
 8755: 		push(@{$name_to_host{$name}}, $id);
 8756: 		$hostdom{$id}=$domain;
 8757: 		if ($role eq 'library') { $libserv{$id}=$name; }
 8758:                 if (defined($protocol)) {
 8759:                     if ($protocol eq 'https') {
 8760:                         $protocol{$id} = $protocol;
 8761:                     } else {
 8762:                         $protocol{$id} = 'http'; 
 8763:                     }
 8764:                 } else {
 8765:                     $protocol{$id} = 'http';
 8766:                 }
 8767: 	    }
 8768: 	}
 8769:     }
 8770:     
 8771:     sub reset_hosts_info {
 8772: 	&purge_remembered();
 8773: 	&reset_domain_info();
 8774: 	&reset_hosts_ip_info();
 8775: 	undef(%name_to_host);
 8776: 	undef(%hostname);
 8777: 	undef(%hostdom);
 8778: 	undef(%libserv);
 8779: 	undef($loaded);
 8780:     }
 8781: 
 8782:     sub load_hosts_tab {
 8783: 	my ($ignore_cache) = @_;
 8784: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 8785: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8786: 	my @config = <$config>;
 8787: 	&parse_hosts_tab(\@config);
 8788: 	close($config);
 8789: 	$loaded=1;
 8790:     }
 8791: 
 8792:     sub hostname {
 8793: 	&load_hosts_tab() if (!$loaded);
 8794: 
 8795: 	my ($lonid) = @_;
 8796: 	return $hostname{$lonid};
 8797:     }
 8798: 
 8799:     sub all_hostnames {
 8800: 	&load_hosts_tab() if (!$loaded);
 8801: 
 8802: 	return %hostname;
 8803:     }
 8804: 
 8805:     sub all_names {
 8806: 	&load_hosts_tab() if (!$loaded);
 8807: 
 8808: 	return %name_to_host;
 8809:     }
 8810: 
 8811:     sub all_host_domain {
 8812:         &load_hosts_tab() if (!$loaded);
 8813:         return %hostdom;
 8814:     }
 8815: 
 8816:     sub is_library {
 8817: 	&load_hosts_tab() if (!$loaded);
 8818: 
 8819: 	return exists($libserv{$_[0]});
 8820:     }
 8821: 
 8822:     sub all_library {
 8823: 	&load_hosts_tab() if (!$loaded);
 8824: 
 8825: 	return %libserv;
 8826:     }
 8827: 
 8828:     sub get_servers {
 8829: 	&load_hosts_tab() if (!$loaded);
 8830: 
 8831: 	my ($domain,$type) = @_;
 8832: 	my %possible_hosts = ($type eq 'library') ? %libserv
 8833: 	                                          : %hostname;
 8834: 	my %result;
 8835: 	if (ref($domain) eq 'ARRAY') {
 8836: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8837: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 8838: 		    $result{$host} = $hostname;
 8839: 		}
 8840: 	    }
 8841: 	} else {
 8842: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8843: 		if ($hostdom{$host} eq $domain) {
 8844: 		    $result{$host} = $hostname;
 8845: 		}
 8846: 	    }
 8847: 	}
 8848: 	return %result;
 8849:     }
 8850: 
 8851:     sub host_domain {
 8852: 	&load_hosts_tab() if (!$loaded);
 8853: 
 8854: 	my ($lonid) = @_;
 8855: 	return $hostdom{$lonid};
 8856:     }
 8857: 
 8858:     sub all_domains {
 8859: 	&load_hosts_tab() if (!$loaded);
 8860: 
 8861: 	my %seen;
 8862: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 8863: 	return @uniq;
 8864:     }
 8865: }
 8866: 
 8867: { 
 8868:     my %iphost;
 8869:     my %name_to_ip;
 8870:     my %lonid_to_ip;
 8871: 
 8872:     sub get_hosts_from_ip {
 8873: 	my ($ip) = @_;
 8874: 	my %iphosts = &get_iphost();
 8875: 	if (ref($iphosts{$ip})) {
 8876: 	    return @{$iphosts{$ip}};
 8877: 	}
 8878: 	return;
 8879:     }
 8880:     
 8881:     sub reset_hosts_ip_info {
 8882: 	undef(%iphost);
 8883: 	undef(%name_to_ip);
 8884: 	undef(%lonid_to_ip);
 8885:     }
 8886: 
 8887:     sub get_host_ip {
 8888: 	my ($lonid) = @_;
 8889: 	if (exists($lonid_to_ip{$lonid})) {
 8890: 	    return $lonid_to_ip{$lonid};
 8891: 	}
 8892: 	my $name=&hostname($lonid);
 8893:    	my $ip = gethostbyname($name);
 8894: 	return if (!$ip || length($ip) ne 4);
 8895: 	$ip=inet_ntoa($ip);
 8896: 	$name_to_ip{$name}   = $ip;
 8897: 	$lonid_to_ip{$lonid} = $ip;
 8898: 	return $ip;
 8899:     }
 8900:     
 8901:     sub get_iphost {
 8902: 	my ($ignore_cache) = @_;
 8903: 
 8904: 	if (!$ignore_cache) {
 8905: 	    if (%iphost) {
 8906: 		return %iphost;
 8907: 	    }
 8908: 	    my ($ip_info,$cached)=
 8909: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 8910: 	    if ($cached) {
 8911: 		%iphost      = %{$ip_info->[0]};
 8912: 		%name_to_ip  = %{$ip_info->[1]};
 8913: 		%lonid_to_ip = %{$ip_info->[2]};
 8914: 		return %iphost;
 8915: 	    }
 8916: 	}
 8917: 
 8918: 	# get yesterday's info for fallback
 8919: 	my %old_name_to_ip;
 8920: 	my ($ip_info,$cached)=
 8921: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 8922: 	if ($cached) {
 8923: 	    %old_name_to_ip = %{$ip_info->[1]};
 8924: 	}
 8925: 
 8926: 	my %name_to_host = &all_names();
 8927: 	foreach my $name (keys(%name_to_host)) {
 8928: 	    my $ip;
 8929: 	    if (!exists($name_to_ip{$name})) {
 8930: 		$ip = gethostbyname($name);
 8931: 		if (!$ip || length($ip) ne 4) {
 8932: 		    if (defined($old_name_to_ip{$name})) {
 8933: 			$ip = $old_name_to_ip{$name};
 8934: 			&logthis("Can't find $name defaulting to old $ip");
 8935: 		    } else {
 8936: 			&logthis("Name $name no IP found");
 8937: 			next;
 8938: 		    }
 8939: 		} else {
 8940: 		    $ip=inet_ntoa($ip);
 8941: 		}
 8942: 		$name_to_ip{$name} = $ip;
 8943: 	    } else {
 8944: 		$ip = $name_to_ip{$name};
 8945: 	    }
 8946: 	    foreach my $id (@{ $name_to_host{$name} }) {
 8947: 		$lonid_to_ip{$id} = $ip;
 8948: 	    }
 8949: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 8950: 	}
 8951: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 8952: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 8953: 				      48*60*60);
 8954: 
 8955: 	return %iphost;
 8956:     }
 8957: }
 8958: 
 8959: BEGIN {
 8960: 
 8961: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 8962:     unless ($readit) {
 8963: {
 8964:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 8965:     %perlvar = (%perlvar,%{$configvars});
 8966: }
 8967: 
 8968: 
 8969: # ------------------------------------------------------ Read spare server file
 8970: {
 8971:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 8972: 
 8973:     while (my $configline=<$config>) {
 8974:        chomp($configline);
 8975:        if ($configline) {
 8976: 	   my ($host,$type) = split(':',$configline,2);
 8977: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 8978: 	   push(@{ $spareid{$type} }, $host);
 8979:        }
 8980:     }
 8981:     close($config);
 8982: }
 8983: # ------------------------------------------------------------ Read permissions
 8984: {
 8985:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 8986: 
 8987:     while (my $configline=<$config>) {
 8988: 	chomp($configline);
 8989: 	if ($configline) {
 8990: 	    my ($role,$perm)=split(/ /,$configline);
 8991: 	    if ($perm ne '') { $pr{$role}=$perm; }
 8992: 	}
 8993:     }
 8994:     close($config);
 8995: }
 8996: 
 8997: # -------------------------------------------- Read plain texts for permissions
 8998: {
 8999:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 9000: 
 9001:     while (my $configline=<$config>) {
 9002: 	chomp($configline);
 9003: 	if ($configline) {
 9004: 	    my ($short,@plain)=split(/:/,$configline);
 9005:             %{$prp{$short}} = ();
 9006: 	    if (@plain > 0) {
 9007:                 $prp{$short}{'std'} = $plain[0];
 9008:                 for (my $i=1; $i<@plain; $i++) {
 9009:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 9010:                 }
 9011:             }
 9012: 	}
 9013:     }
 9014:     close($config);
 9015: }
 9016: 
 9017: # ---------------------------------------------------------- Read package table
 9018: {
 9019:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 9020: 
 9021:     while (my $configline=<$config>) {
 9022: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 9023: 	chomp($configline);
 9024: 	my ($short,$plain)=split(/:/,$configline);
 9025: 	my ($pack,$name)=split(/\&/,$short);
 9026: 	if ($plain ne '') {
 9027: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 9028: 	    $packagetab{$short}=$plain; 
 9029: 	}
 9030:     }
 9031:     close($config);
 9032: }
 9033: 
 9034: # ------------- set up temporary directory
 9035: {
 9036:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 9037: 
 9038: }
 9039: 
 9040: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 9041: 				'compress_threshold'=> 20_000,
 9042:  			        });
 9043: 
 9044: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 9045: $dumpcount=0;
 9046: $locknum=0;
 9047: 
 9048: &logtouch();
 9049: &logthis('<font color="yellow">INFO: Read configuration</font>');
 9050: $readit=1;
 9051:     {
 9052: 	use integer;
 9053: 	my $test=(2**32)+1;
 9054: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 9055: 	&logthis(" Detected 64bit platform ($_64bit)");
 9056:     }
 9057: }
 9058: }
 9059: 
 9060: 1;
 9061: __END__
 9062: 
 9063: =pod
 9064: 
 9065: =head1 NAME
 9066: 
 9067: Apache::lonnet - Subroutines to ask questions about things in the network.
 9068: 
 9069: =head1 SYNOPSIS
 9070: 
 9071: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 9072: 
 9073:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 9074: 
 9075: Common parameters:
 9076: 
 9077: =over 4
 9078: 
 9079: =item *
 9080: 
 9081: $uname : an internal username (if $cname expecting a course Id specifically)
 9082: 
 9083: =item *
 9084: 
 9085: $udom : a domain (if $cdom expecting a course's domain specifically)
 9086: 
 9087: =item *
 9088: 
 9089: $symb : a resource instance identifier
 9090: 
 9091: =item *
 9092: 
 9093: $namespace : the name of a .db file that contains the data needed or
 9094: being set.
 9095: 
 9096: =back
 9097: 
 9098: =head1 OVERVIEW
 9099: 
 9100: lonnet provides subroutines which interact with the
 9101: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 9102: about classes, users, and resources.
 9103: 
 9104: For many of these objects you can also use this to store data about
 9105: them or modify them in various ways.
 9106: 
 9107: =head2 Symbs
 9108: 
 9109: To identify a specific instance of a resource, LON-CAPA uses symbols
 9110: or "symbs"X<symb>. These identifiers are built from the URL of the
 9111: map, the resource number of the resource in the map, and the URL of
 9112: the resource itself. The latter is somewhat redundant, but might help
 9113: if maps change.
 9114: 
 9115: An example is
 9116: 
 9117:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 9118: 
 9119: The respective map entry is
 9120: 
 9121:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 9122:   title="Problem 2">
 9123:  </resource>
 9124: 
 9125: Symbs are used by the random number generator, as well as to store and
 9126: restore data specific to a certain instance of for example a problem.
 9127: 
 9128: =head2 Storing And Retrieving Data
 9129: 
 9130: X<store()>X<cstore()>X<restore()>Three of the most important functions
 9131: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 9132: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 9133: is is the non-critical message twin of cstore. These functions are for
 9134: handlers to store a perl hash to a user's permanent data space in an
 9135: easy manner, and to retrieve it again on another call. It is expected
 9136: that a handler would use this once at the beginning to retrieve data,
 9137: and then again once at the end to send only the new data back.
 9138: 
 9139: The data is stored in the user's data directory on the user's
 9140: homeserver under the ID of the course.
 9141: 
 9142: The hash that is returned by restore will have all of the previous
 9143: value for all of the elements of the hash.
 9144: 
 9145: Example:
 9146: 
 9147:  #creating a hash
 9148:  my %hash;
 9149:  $hash{'foo'}='bar';
 9150: 
 9151:  #storing it
 9152:  &Apache::lonnet::cstore(\%hash);
 9153: 
 9154:  #changing a value
 9155:  $hash{'foo'}='notbar';
 9156: 
 9157:  #adding a new value
 9158:  $hash{'bar'}='foo';
 9159:  &Apache::lonnet::cstore(\%hash);
 9160: 
 9161:  #retrieving the hash
 9162:  my %history=&Apache::lonnet::restore();
 9163: 
 9164:  #print the hash
 9165:  foreach my $key (sort(keys(%history))) {
 9166:    print("\%history{$key} = $history{$key}");
 9167:  }
 9168: 
 9169: Will print out:
 9170: 
 9171:  %history{1:foo} = bar
 9172:  %history{1:keys} = foo:timestamp
 9173:  %history{1:timestamp} = 990455579
 9174:  %history{2:bar} = foo
 9175:  %history{2:foo} = notbar
 9176:  %history{2:keys} = foo:bar:timestamp
 9177:  %history{2:timestamp} = 990455580
 9178:  %history{bar} = foo
 9179:  %history{foo} = notbar
 9180:  %history{timestamp} = 990455580
 9181:  %history{version} = 2
 9182: 
 9183: Note that the special hash entries C<keys>, C<version> and
 9184: C<timestamp> were added to the hash. C<version> will be equal to the
 9185: total number of versions of the data that have been stored. The
 9186: C<timestamp> attribute will be the UNIX time the hash was
 9187: stored. C<keys> is available in every historical section to list which
 9188: keys were added or changed at a specific historical revision of a
 9189: hash.
 9190: 
 9191: B<Warning>: do not store the hash that restore returns directly. This
 9192: will cause a mess since it will restore the historical keys as if the
 9193: were new keys. I.E. 1:foo will become 1:1:foo etc.
 9194: 
 9195: Calling convention:
 9196: 
 9197:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 9198:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 9199: 
 9200: For more detailed information, see lonnet specific documentation.
 9201: 
 9202: =head1 RETURN MESSAGES
 9203: 
 9204: =over 4
 9205: 
 9206: =item * B<con_lost>: unable to contact remote host
 9207: 
 9208: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 9209: when the connection is brought back up
 9210: 
 9211: =item * B<con_failed>: unable to contact remote host and unable to save message
 9212: for later delivery
 9213: 
 9214: =item * B<error:>: an error a occurred, a description of the error follows the :
 9215: 
 9216: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 9217: that was requested
 9218: 
 9219: =back
 9220: 
 9221: =head1 PUBLIC SUBROUTINES
 9222: 
 9223: =head2 Session Environment Functions
 9224: 
 9225: =over 4
 9226: 
 9227: =item * 
 9228: X<appenv()>
 9229: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
 9230: the user envirnoment file, and will be restored for each access this
 9231: user makes during this session, also modifies the %env for the current
 9232: process. Optional rolesarrayref - if defined contains a reference to an array
 9233: of roles which are exempt from the restriction on modifying user.role entries 
 9234: in the user's environment.db and in %env.    
 9235: 
 9236: =item *
 9237: X<delenv()>
 9238: B<delenv($regexp)>: removes all items from the session
 9239: environment file that matches the regular expression in $regexp. The
 9240: values are also delted from the current processes %env.
 9241: 
 9242: =item * get_env_multiple($name) 
 9243: 
 9244: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9245: values may be defined and end up as an array ref.
 9246: 
 9247: returns an array of values
 9248: 
 9249: =back
 9250: 
 9251: =head2 User Information
 9252: 
 9253: =over 4
 9254: 
 9255: =item *
 9256: X<queryauthenticate()>
 9257: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 9258: authentication scheme
 9259: 
 9260: =item *
 9261: X<authenticate()>
 9262: B<authenticate($uname,$upass,$udom)>: try to
 9263: authenticate user from domain's lib servers (first use the current
 9264: one). C<$upass> should be the users password.
 9265: 
 9266: =item *
 9267: X<homeserver()>
 9268: B<homeserver($uname,$udom)>: find the server which has
 9269: the user's directory and files (there must be only one), this caches
 9270: the answer, and also caches if there is a borken connection.
 9271: 
 9272: =item *
 9273: X<idget()>
 9274: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 9275: (IDs are a unique resource in a domain, there must be only 1 ID per
 9276: username, and only 1 username per ID in a specific domain) (returns
 9277: hash: id=>name,id=>name)
 9278: 
 9279: =item *
 9280: X<idrget()>
 9281: B<idrget($udom,@unames)>: find the IDs behind a list of
 9282: usernames (returns hash: name=>id,name=>id)
 9283: 
 9284: =item *
 9285: X<idput()>
 9286: B<idput($udom,%ids)>: store away a list of names and associated IDs
 9287: 
 9288: =item *
 9289: X<rolesinit()>
 9290: B<rolesinit($udom,$username,$authhost)>: get user privileges
 9291: 
 9292: =item *
 9293: X<getsection()>
 9294: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 9295: course $cname, return section name/number or '' for "not in course"
 9296: and '-1' for "no section"
 9297: 
 9298: =item *
 9299: X<userenvironment()>
 9300: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 9301: passed in @what from the requested user's environment, returns a hash
 9302: 
 9303: =item * 
 9304: X<userlog_query()>
 9305: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 9306: activity.log file. %filters defines filters applied when parsing the
 9307: log file. These can be start or end timestamps, or the type of action
 9308: - log to look for Login or Logout events, check for Checkin or
 9309: Checkout, role for role selection. The response is in the form
 9310: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 9311: escaped strings of the action recorded in the activity.log file.
 9312: 
 9313: =back
 9314: 
 9315: =head2 User Roles
 9316: 
 9317: =over 4
 9318: 
 9319: =item *
 9320: 
 9321: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 9322:  F: full access
 9323:  U,I,K: authentication modes (cxx only)
 9324:  '': forbidden
 9325:  1: user needs to choose course
 9326:  2: browse allowed
 9327:  A: passphrase authentication needed
 9328: 
 9329: =item *
 9330: 
 9331: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 9332: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 9333: and course level
 9334: 
 9335: =item *
 9336: 
 9337: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 9338: explanation of a user role term
 9339: 
 9340: =item *
 9341: 
 9342: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
 9343: All arguments are optional. Returns a hash of a roles, either for
 9344: co-author/assistant author roles for a user's Construction Space
 9345: (default), or if $context is 'userroles', roles for the user himself,
 9346: In the hash, keys are set to colon-separated $uname,$udom,$role, and
 9347: (optionally) if $withsec is true, a fourth colon-separated item - $section.
 9348: For each key, value is set to colon-separated start and end times for
 9349: the role.  If no username and domain are specified, will default to
 9350: current user/domain. Types, roles, and roledoms are references to arrays
 9351: of role statuses (active, future or previous), roles 
 9352: (e.g., cc,in, st etc.) and domains of the roles which can be used
 9353: to restrict the list of roles reported. If no array ref is 
 9354: provided for types, will default to return only active roles.
 9355: 
 9356: =back
 9357: 
 9358: =head2 User Modification
 9359: 
 9360: =over 4
 9361: 
 9362: =item *
 9363: 
 9364: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
 9365: user for the level given by URL.  Optional start and end dates (leave empty
 9366: string or zero for "no date")
 9367: 
 9368: =item *
 9369: 
 9370: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 9371: change a users, password, possible return values are: ok,
 9372: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 9373: refused
 9374: 
 9375: =item *
 9376: 
 9377: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 9378: 
 9379: =item *
 9380: 
 9381: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
 9382:            $forceid,$desiredhome,$email,$inststatus) : 
 9383: modify user
 9384: 
 9385: =item *
 9386: 
 9387: modifystudent
 9388: 
 9389: modify a student's enrollment and identification information.
 9390: The course id is resolved based on the current users environment.  
 9391: This means the envoking user must be a course coordinator or otherwise
 9392: associated with a course.
 9393: 
 9394: This call is essentially a wrapper for lonnet::modifyuser and
 9395: lonnet::modify_student_enrollment
 9396: 
 9397: Inputs: 
 9398: 
 9399: =over 4
 9400: 
 9401: =item B<$udom> Student's loncapa domain
 9402: 
 9403: =item B<$uname> Student's loncapa login name
 9404: 
 9405: =item B<$uid> Student/Employee ID
 9406: 
 9407: =item B<$umode> Student's authentication mode
 9408: 
 9409: =item B<$upass> Student's password
 9410: 
 9411: =item B<$first> Student's first name
 9412: 
 9413: =item B<$middle> Student's middle name
 9414: 
 9415: =item B<$last> Student's last name
 9416: 
 9417: =item B<$gene> Student's generation
 9418: 
 9419: =item B<$usec> Student's section in course
 9420: 
 9421: =item B<$end> Unix time of the roles expiration
 9422: 
 9423: =item B<$start> Unix time of the roles start date
 9424: 
 9425: =item B<$forceid> If defined, allow $uid to be changed
 9426: 
 9427: =item B<$desiredhome> server to use as home server for student
 9428: 
 9429: =item B<$email> Student's permanent e-mail address
 9430: 
 9431: =item B<$type> Type of enrollment (auto or manual)
 9432: 
 9433: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
 9434: 
 9435: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
 9436: 
 9437: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
 9438: 
 9439: =item B<$context> role change context (shown in User Management Logs display in a course)
 9440: 
 9441: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
 9442: 
 9443: =back
 9444: 
 9445: =item *
 9446: 
 9447: modify_student_enrollment
 9448: 
 9449: Change a students enrollment status in a class.  The environment variable
 9450: 'role.request.course' must be defined for this function to proceed.
 9451: 
 9452: Inputs:
 9453: 
 9454: =over 4
 9455: 
 9456: =item $udom, students domain
 9457: 
 9458: =item $uname, students name
 9459: 
 9460: =item $uid, students user id
 9461: 
 9462: =item $first, students first name
 9463: 
 9464: =item $middle
 9465: 
 9466: =item $last
 9467: 
 9468: =item $gene
 9469: 
 9470: =item $usec
 9471: 
 9472: =item $end
 9473: 
 9474: =item $start
 9475: 
 9476: =item $type
 9477: 
 9478: =item $locktype
 9479: 
 9480: =item $cid
 9481: 
 9482: =item $selfenroll
 9483: 
 9484: =item $context
 9485: 
 9486: =back
 9487: 
 9488: 
 9489: =item *
 9490: 
 9491: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 9492: custom role; give a custom role to a user for the level given by URL.  Specify
 9493: name and domain of role author, and role name
 9494: 
 9495: =item *
 9496: 
 9497: revokerole($udom,$uname,$url,$role) : revoke a role for url
 9498: 
 9499: =item *
 9500: 
 9501: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 9502: 
 9503: =back
 9504: 
 9505: =head2 Course Infomation
 9506: 
 9507: =over 4
 9508: 
 9509: =item *
 9510: 
 9511: coursedescription($courseid) : returns a hash of information about the
 9512: specified course id, including all environment settings for the
 9513: course, the description of the course will be in the hash under the
 9514: key 'description'
 9515: 
 9516: =item *
 9517: 
 9518: resdata($name,$domain,$type,@which) : request for current parameter
 9519: setting for a specific $type, where $type is either 'course' or 'user',
 9520: @what should be a list of parameters to ask about. This routine caches
 9521: answers for 5 minutes.
 9522: 
 9523: =item *
 9524: 
 9525: get_courseresdata($courseid, $domain) : dump the entire course resource
 9526: data base, returning a hash that is keyed by the resource name and has
 9527: values that are the resource value.  I believe that the timestamps and
 9528: versions are also returned.
 9529: 
 9530: 
 9531: =back
 9532: 
 9533: =head2 Course Modification
 9534: 
 9535: =over 4
 9536: 
 9537: =item *
 9538: 
 9539: writecoursepref($courseid,%prefs) : write preferences (environment
 9540: database) for a course
 9541: 
 9542: =item *
 9543: 
 9544: createcourse($udom,$description,$url) : make/modify course
 9545: 
 9546: =back
 9547: 
 9548: =head2 Resource Subroutines
 9549: 
 9550: =over 4
 9551: 
 9552: =item *
 9553: 
 9554: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 9555: 
 9556: =item *
 9557: 
 9558: repcopy($filename) : subscribes to the requested file, and attempts to
 9559: replicate from the owning library server, Might return
 9560: 'unavailable', 'not_found', 'forbidden', 'ok', or
 9561: 'bad_request', also attempts to grab the metadata for the
 9562: resource. Expects the local filesystem pathname
 9563: (/home/httpd/html/res/....)
 9564: 
 9565: =back
 9566: 
 9567: =head2 Resource Information
 9568: 
 9569: =over 4
 9570: 
 9571: =item *
 9572: 
 9573: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 9574: a vairety of different possible values, $varname should be a request
 9575: string, and the other parameters can be used to specify who and what
 9576: one is asking about.
 9577: 
 9578: Possible values for $varname are environment.lastname (or other item
 9579: from the envirnment hash), user.name (or someother aspect about the
 9580: user), resource.0.maxtries (or some other part and parameter of a
 9581: resource)
 9582: 
 9583: =item *
 9584: 
 9585: directcondval($number) : get current value of a condition; reads from a state
 9586: string
 9587: 
 9588: =item *
 9589: 
 9590: condval($condidx) : value of condition index based on state
 9591: 
 9592: =item *
 9593: 
 9594: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 9595: resource's metadata, $what should be either a specific key, or either
 9596: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 9597: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 9598: 
 9599: this function automatically caches all requests
 9600: 
 9601: =item *
 9602: 
 9603: metadata_query($query,$custom,$customshow) : make a metadata query against the
 9604: network of library servers; returns file handle of where SQL and regex results
 9605: will be stored for query
 9606: 
 9607: =item *
 9608: 
 9609: symbread($filename) : return symbolic list entry (filename argument optional);
 9610: returns the data handle
 9611: 
 9612: =item *
 9613: 
 9614: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 9615: a possible symb for the URL in $thisfn, and if is an encryypted
 9616: resource that the user accessed using /enc/ returns a 1 on success, 0
 9617: on failure, user must be in a course, as it assumes the existance of
 9618: the course initial hash, and uses $env('request.course.id'}
 9619: 
 9620: 
 9621: =item *
 9622: 
 9623: symbclean($symb) : removes versions numbers from a symb, returns the
 9624: cleaned symb
 9625: 
 9626: =item *
 9627: 
 9628: is_on_map($uri) : checks if the $uri is somewhere on the current
 9629: course map, user must be in a course for it to work.
 9630: 
 9631: =item *
 9632: 
 9633: numval($salt) : return random seed value (addend for rndseed)
 9634: 
 9635: =item *
 9636: 
 9637: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 9638: a random seed, all arguments are optional, if they aren't sent it uses the
 9639: environment to derive them. Note: if symb isn't sent and it can't get one
 9640: from &symbread it will use the current time as its return value
 9641: 
 9642: =item *
 9643: 
 9644: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 9645: unfakeable, receipt
 9646: 
 9647: =item *
 9648: 
 9649: receipt() : API to ireceipt working off of env values; given out to users
 9650: 
 9651: =item *
 9652: 
 9653: countacc($url) : count the number of accesses to a given URL
 9654: 
 9655: =item *
 9656: 
 9657: 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
 9658: 
 9659: =item *
 9660: 
 9661: 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)
 9662: 
 9663: =item *
 9664: 
 9665: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 9666: 
 9667: =item *
 9668: 
 9669: devalidate($symb) : devalidate temporary spreadsheet calculations,
 9670: forcing spreadsheet to reevaluate the resource scores next time.
 9671: 
 9672: =back
 9673: 
 9674: =head2 Storing/Retreiving Data
 9675: 
 9676: =over 4
 9677: 
 9678: =item *
 9679: 
 9680: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 9681: for this url; hashref needs to be given and should be a \%hashname; the
 9682: remaining args aren't required and if they aren't passed or are '' they will
 9683: be derived from the env
 9684: 
 9685: =item *
 9686: 
 9687: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 9688: uses critical subroutine
 9689: 
 9690: =item *
 9691: 
 9692: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 9693: all args are optional
 9694: 
 9695: =item *
 9696: 
 9697: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 9698: dumps the complete (or key matching regexp) namespace into a hash
 9699: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 9700: normally &store()ed into
 9701: 
 9702: $range should be either an integer '100' (give me the first 100
 9703:                                            matching records)
 9704:               or be  two integers sperated by a - with no spaces
 9705:                  '30-50' (give me the 30th through the 50th matching
 9706:                           records)
 9707: 
 9708: 
 9709: =item *
 9710: 
 9711: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 9712: replaces a &store() version of data with a replacement set of data
 9713: for a particular resource in a namespace passed in the $storehash hash 
 9714: reference
 9715: 
 9716: =item *
 9717: 
 9718: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 9719: works very similar to store/cstore, but all data is stored in a
 9720: temporary location and can be reset using tmpreset, $storehash should
 9721: be a hash reference, returns nothing on success
 9722: 
 9723: =item *
 9724: 
 9725: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 9726: similar to restore, but all data is stored in a temporary location and
 9727: can be reset using tmpreset. Returns a hash of values on success,
 9728: error string otherwise.
 9729: 
 9730: =item *
 9731: 
 9732: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 9733: deltes all keys for $symb form the temporary storage hash.
 9734: 
 9735: =item *
 9736: 
 9737: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9738: reference filled in from namesp ($udom and $uname are optional)
 9739: 
 9740: =item *
 9741: 
 9742: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 9743: namesp ($udom and $uname are optional)
 9744: 
 9745: =item *
 9746: 
 9747: dump($namespace,$udom,$uname,$regexp,$range) : 
 9748: dumps the complete (or key matching regexp) namespace into a hash
 9749: ($udom, $uname, $regexp, $range are optional)
 9750: 
 9751: $range should be either an integer '100' (give me the first 100
 9752:                                            matching records)
 9753:               or be  two integers sperated by a - with no spaces
 9754:                  '30-50' (give me the 30th through the 50th matching
 9755:                           records)
 9756: =item *
 9757: 
 9758: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 9759: $store can be a scalar, an array reference, or if the amount to be 
 9760: incremented is > 1, a hash reference.
 9761: 
 9762: ($udom and $uname are optional)
 9763: 
 9764: =item *
 9765: 
 9766: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 9767: ($udom and $uname are optional)
 9768: 
 9769: =item *
 9770: 
 9771: cput($namespace,$storehash,$udom,$uname) : critical put
 9772: ($udom and $uname are optional)
 9773: 
 9774: =item *
 9775: 
 9776: newput($namespace,$storehash,$udom,$uname) :
 9777: 
 9778: Attempts to store the items in the $storehash, but only if they don't
 9779: currently exist, if this succeeds you can be certain that you have 
 9780: successfully created a new key value pair in the $namespace db.
 9781: 
 9782: 
 9783: Args:
 9784:  $namespace: name of database to store values to
 9785:  $storehash: hashref to store to the db
 9786:  $udom: (optional) domain of user containing the db
 9787:  $uname: (optional) name of user caontaining the db
 9788: 
 9789: Returns:
 9790:  'ok' -> succeeded in storing all keys of $storehash
 9791:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 9792:                         least <key> already existed in the db (other
 9793:                         requested keys may also already exist)
 9794:  'error: <msg>' -> unable to tie the DB or other error occurred
 9795:  'con_lost' -> unable to contact request server
 9796:  'refused' -> action was not allowed by remote machine
 9797: 
 9798: 
 9799: =item *
 9800: 
 9801: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9802: reference filled in from namesp (encrypts the return communication)
 9803: ($udom and $uname are optional)
 9804: 
 9805: =item *
 9806: 
 9807: log($udom,$name,$home,$message) : write to permanent log for user; use
 9808: critical subroutine
 9809: 
 9810: =item *
 9811: 
 9812: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
 9813: array reference filled in from namespace found in domain level on either
 9814: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
 9815: 
 9816: =item *
 9817: 
 9818: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
 9819: domain level either on specified domain server ($uhome) or primary domain 
 9820: server ($udom and $uhome are optional)
 9821: 
 9822: =item * 
 9823: 
 9824: get_domain_defaults($target_domain) : returns hash with defaults for
 9825: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
 9826: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
 9827: or localauth), initial password or a kerberos realm, language (e.g., en-us).
 9828: Values are retrieved from cache (if current), or from domain's configuration.db
 9829: (if available), or lastly from values in lonTabs/dns_domain,tab, 
 9830: or lonTabs/domain.tab. 
 9831: 
 9832: %domdefaults = &get_auth_defaults($target_domain);
 9833: 
 9834: =back
 9835: 
 9836: =head2 Network Status Functions
 9837: 
 9838: =over 4
 9839: 
 9840: =item *
 9841: 
 9842: dirlist($uri) : return directory list based on URI
 9843: 
 9844: =item *
 9845: 
 9846: spareserver() : find server with least workload from spare.tab
 9847: 
 9848: =back
 9849: 
 9850: =head2 Apache Request
 9851: 
 9852: =over 4
 9853: 
 9854: =item *
 9855: 
 9856: ssi($url,%hash) : server side include, does a complete request cycle on url to
 9857: localhost, posts hash
 9858: 
 9859: =back
 9860: 
 9861: =head2 Data to String to Data
 9862: 
 9863: =over 4
 9864: 
 9865: =item *
 9866: 
 9867: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 9868: and '&' separators, supports elements that are arrayrefs and hashrefs
 9869: 
 9870: =item *
 9871: 
 9872: hashref2str($hashref) : convert a hashref into a string complete with
 9873: escaping and '=' and '&' separators, supports elements that are
 9874: arrayrefs and hashrefs
 9875: 
 9876: =item *
 9877: 
 9878: arrayref2str($arrayref) : convert an arrayref into a string complete
 9879: with escaping and '&' separators, supports elements that are arrayrefs
 9880: and hashrefs
 9881: 
 9882: =item *
 9883: 
 9884: str2hash($string) : convert string to hash using unescaping and
 9885: splitting on '=' and '&', supports elements that are arrayrefs and
 9886: hashrefs
 9887: 
 9888: =item *
 9889: 
 9890: str2array($string) : convert string to hash using unescaping and
 9891: splitting on '&', supports elements that are arrayrefs and hashrefs
 9892: 
 9893: =back
 9894: 
 9895: =head2 Logging Routines
 9896: 
 9897: =over 4
 9898: 
 9899: These routines allow one to make log messages in the lonnet.log and
 9900: lonnet.perm logfiles.
 9901: 
 9902: =item *
 9903: 
 9904: logtouch() : make sure the logfile, lonnet.log, exists
 9905: 
 9906: =item *
 9907: 
 9908: logthis() : append message to the normal lonnet.log file, it gets
 9909: preiodically rolled over and deleted.
 9910: 
 9911: =item *
 9912: 
 9913: logperm() : append a permanent message to lonnet.perm.log, this log
 9914: file never gets deleted by any automated portion of the system, only
 9915: messages of critical importance should go in here.
 9916: 
 9917: =back
 9918: 
 9919: =head2 General File Helper Routines
 9920: 
 9921: =over 4
 9922: 
 9923: =item *
 9924: 
 9925: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 9926: (a) files in /uploaded
 9927:   (i) If a local copy of the file exists - 
 9928:       compares modification date of local copy with last-modified date for 
 9929:       definitive version stored on home server for course. If local copy is 
 9930:       stale, requests a new version from the home server and stores it. 
 9931:       If the original has been removed from the home server, then local copy 
 9932:       is unlinked.
 9933:   (ii) If local copy does not exist -
 9934:       requests the file from the home server and stores it. 
 9935:   
 9936:   If $caller is 'uploadrep':  
 9937:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 9938:     for request for files originally uploaded via DOCS. 
 9939:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 9940:   
 9941:   Otherwise:
 9942:      This indicates a call from the content generation phase of the request.
 9943:      -  returns the entire contents of the file or -1.
 9944:      
 9945: (b) files in /res
 9946:    - returns the entire contents of a file or -1; 
 9947:    it properly subscribes to and replicates the file if neccessary.
 9948: 
 9949: 
 9950: =item *
 9951: 
 9952: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 9953:                   reference
 9954: 
 9955: returns either a stat() list of data about the file or an empty list
 9956: if the file doesn't exist or couldn't find out about it (connection
 9957: problems or user unknown)
 9958: 
 9959: =item *
 9960: 
 9961: filelocation($dir,$file) : returns file system location of a file
 9962: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 9963: directory that relative $file lookups are to looked in ($dir of /a/dir
 9964: and a file of ../bob will become /a/bob)
 9965: 
 9966: =item *
 9967: 
 9968: hreflocation($dir,$file) : returns file system location or a URL; same as
 9969: filelocation except for hrefs
 9970: 
 9971: =item *
 9972: 
 9973: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 9974: 
 9975: =back
 9976: 
 9977: =head2 Usererfile file routines (/uploaded*)
 9978: 
 9979: =over 4
 9980: 
 9981: =item *
 9982: 
 9983: userfileupload(): main rotine for putting a file in a user or course's
 9984:                   filespace, arguments are,
 9985: 
 9986:  formname - required - this is the name of the element in $env where the
 9987:            filename, and the contents of the file to create/modifed exist
 9988:            the filename is in $env{'form.'.$formname.'.filename'} and the
 9989:            contents of the file is located in $env{'form.'.$formname}
 9990:  coursedoc - if true, store the file in the course of the active role
 9991:              of the current user
 9992:  subdir - required - subdirectory to put the file in under ../userfiles/
 9993:          if undefined, it will be placed in "unknown"
 9994: 
 9995:  (This routine calls clean_filename() to remove any dangerous
 9996:  characters from the filename, and then calls finuserfileupload() to
 9997:  complete the transaction)
 9998: 
 9999:  returns either the url of the uploaded file (/uploaded/....) if successful
10000:  and /adm/notfound.html if unsuccessful
10001: 
10002: =item *
10003: 
10004: clean_filename(): routine for cleaing a filename up for storage in
10005:                  userfile space, argument is:
10006: 
10007:  filename - proposed filename
10008: 
10009: returns: the new clean filename
10010: 
10011: =item *
10012: 
10013: finishuserfileupload(): routine that creaes and sends the file to
10014: userspace, probably shouldn't be called directly
10015: 
10016:   docuname: username or courseid of destination for the file
10017:   docudom: domain of user/course of destination for the file
10018:   formname: same as for userfileupload()
10019:   fname: filename (inculding subdirectories) for the file
10020: 
10021:  returns either the url of the uploaded file (/uploaded/....) if successful
10022:  and /adm/notfound.html if unsuccessful
10023: 
10024: =item *
10025: 
10026: renameuserfile(): renames an existing userfile to a new name
10027: 
10028:   Args:
10029:    docuname: username or courseid of destination for the file
10030:    docudom: domain of user/course of destination for the file
10031:    old: current file name (including any subdirs under userfiles)
10032:    new: desired file name (including any subdirs under userfiles)
10033: 
10034: =item *
10035: 
10036: mkdiruserfile(): creates a directory is a userfiles dir
10037: 
10038:   Args:
10039:    docuname: username or courseid of destination for the file
10040:    docudom: domain of user/course of destination for the file
10041:    dir: dir to create (including any subdirs under userfiles)
10042: 
10043: =item *
10044: 
10045: removeuserfile(): removes a file that exists in userfiles
10046: 
10047:   Args:
10048:    docuname: username or courseid of destination for the file
10049:    docudom: domain of user/course of destination for the file
10050:    fname: filname to delete (including any subdirs under userfiles)
10051: 
10052: =item *
10053: 
10054: removeuploadedurl(): convience function for removeuserfile()
10055: 
10056:   Args:
10057:    url:  a full /uploaded/... url to delete
10058: 
10059: =item * 
10060: 
10061: get_portfile_permissions():
10062:   Args:
10063:     domain: domain of user or course contain the portfolio files
10064:     user: name of user or num of course contain the portfolio files
10065:   Returns:
10066:     hashref of a dump of the proper file_permissions.db
10067:    
10068: 
10069: =item * 
10070: 
10071: get_access_controls():
10072: 
10073: Args:
10074:   current_permissions: the hash ref returned from get_portfile_permissions()
10075:   group: (optional) the group you want the files associated with
10076:   file: (optional) the file you want access info on
10077: 
10078: Returns:
10079:     a hash (keys are file names) of hashes containing
10080:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10081:         values are XML containing access control settings (see below) 
10082: 
10083: Internal notes:
10084: 
10085:  access controls are stored in file_permissions.db as key=value pairs.
10086:     key -> path to file/file_name\0uniqueID:scope_end_start
10087:         where scope -> public,guest,course,group,domains or users.
10088:               end -> UNIX time for end of access (0 -> no end date)
10089:               start -> UNIX time for start of access
10090: 
10091:     value -> XML description of access control
10092:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10093:             <start></start>
10094:             <end></end>
10095: 
10096:             <password></password>  for scope type = guest
10097: 
10098:             <domain></domain>     for scope type = course or group
10099:             <number></number>
10100:             <roles id="">
10101:              <role></role>
10102:              <access></access>
10103:              <section></section>
10104:              <group></group>
10105:             </roles>
10106: 
10107:             <dom></dom>         for scope type = domains
10108: 
10109:             <users>             for scope type = users
10110:              <user>
10111:               <uname></uname>
10112:               <udom></udom>
10113:              </user>
10114:             </users>
10115:            </scope> 
10116:               
10117:  Access data is also aggregated for each file in an additional key=value pair:
10118:  key -> path to file/file_name\0accesscontrol 
10119:  value -> reference to hash
10120:           hash contains key = value pairs
10121:           where key = uniqueID:scope_end_start
10122:                 value = UNIX time record was last updated
10123: 
10124:           Used to improve speed of look-ups of access controls for each file.  
10125:  
10126:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10127: 
10128: modify_access_controls():
10129: 
10130: Modifies access controls for a portfolio file
10131: Args
10132: 1. file name
10133: 2. reference to hash of required changes,
10134: 3. domain
10135: 4. username
10136:   where domain,username are the domain of the portfolio owner 
10137:   (either a user or a course) 
10138: 
10139: Returns:
10140: 1. result of additions or updates ('ok' or 'error', with error message). 
10141: 2. result of deletions ('ok' or 'error', with error message).
10142: 3. reference to hash of any new or updated access controls.
10143: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10144:    key = integer (inbound ID)
10145:    value = uniqueID  
10146: 
10147: =back
10148: 
10149: =head2 HTTP Helper Routines
10150: 
10151: =over 4
10152: 
10153: =item *
10154: 
10155: escape() : unpack non-word characters into CGI-compatible hex codes
10156: 
10157: =item *
10158: 
10159: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10160: 
10161: =back
10162: 
10163: =head1 PRIVATE SUBROUTINES
10164: 
10165: =head2 Underlying communication routines (Shouldn't call)
10166: 
10167: =over 4
10168: 
10169: =item *
10170: 
10171: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10172: 
10173: =item *
10174: 
10175: reply() : uses subreply to send a message to remote machine, logs all failures
10176: 
10177: =item *
10178: 
10179: critical() : passes a critical message to another server; if cannot
10180: get through then place message in connection buffer directory and
10181: returns con_delayed, if incapable of saving message, returns
10182: con_failed
10183: 
10184: =item *
10185: 
10186: reconlonc() : tries to reconnect lonc client processes.
10187: 
10188: =back
10189: 
10190: =head2 Resource Access Logging
10191: 
10192: =over 4
10193: 
10194: =item *
10195: 
10196: flushcourselogs() : flush (save) buffer logs and access logs
10197: 
10198: =item *
10199: 
10200: courselog($what) : save message for course in hash
10201: 
10202: =item *
10203: 
10204: courseacclog($what) : save message for course using &courselog().  Perform
10205: special processing for specific resource types (problems, exams, quizzes, etc).
10206: 
10207: =item *
10208: 
10209: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10210: as a PerlChildExitHandler
10211: 
10212: =back
10213: 
10214: =head2 Other
10215: 
10216: =over 4
10217: 
10218: =item *
10219: 
10220: symblist($mapname,%newhash) : update symbolic storage links
10221: 
10222: =back
10223: 
10224: =cut
10225: 

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