File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.733: download - view: text, annotated - select for diffs
Mon May 1 06:17:32 2006 UTC (18 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Determination of parameters for spreadsheet now correctly cascades for cases where a user has multiple active groups. Also groups are passed in argument list for Spreadsheet object as array reference. Lastly lonnet::get_users_groups function modified to only return user's active groups, except in case when user status has expired (and default end access date for students has also passed), in which case user's groups which were still active less than 24 hours before default end date are also included in user's groups. [For consistency with students groups returned by loncoursedata::get_students_groups()].

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.733 2006/05/01 06:17:32 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::lonnet;
   31: 
   32: use strict;
   33: use LWP::UserAgent();
   34: use HTTP::Headers;
   35: use HTTP::Date;
   36: # use Date::Parse;
   37: use vars 
   38: qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom 
   39:    %libserv %pr %prp $memcache %packagetab 
   40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
   41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf
   42:    %domaindescription %domain_auth_def %domain_auth_arg_def 
   43:    %domain_lang_def %domain_city %domain_longi %domain_lati %domain_primary
   44:    $tmpdir $_64bit %env);
   45: 
   46: use IO::Socket;
   47: use GDBM_File;
   48: use HTML::LCParser;
   49: use HTML::Parser;
   50: use Fcntl qw(:flock);
   51: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
   52: use Time::HiRes qw( gettimeofday tv_interval );
   53: use Cache::Memcached;
   54: use Digest::MD5;
   55: 
   56: my $readit;
   57: my $max_connection_retries = 10;     # Or some such value.
   58: 
   59: require Exporter;
   60: 
   61: our @ISA = qw (Exporter);
   62: our @EXPORT = qw(%env);
   63: 
   64: =pod
   65: 
   66: =head1 Package Variables
   67: 
   68: These are largely undocumented, so if you decipher one please note it here.
   69: 
   70: =over 4
   71: 
   72: =item $processmarker
   73: 
   74: Contains the time this process was started and this servers host id.
   75: 
   76: =item $dumpcount
   77: 
   78: Counts the number of times a message log flush has been attempted (regardless
   79: of success) by this process.  Used as part of the filename when messages are
   80: delayed.
   81: 
   82: =back
   83: 
   84: =cut
   85: 
   86: 
   87: # --------------------------------------------------------------------- Logging
   88: {
   89:     my $logid;
   90:     sub instructor_log {
   91: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
   92: 	$logid++;
   93: 	my $id=time().'00000'.$$.'00000'.$logid;
   94: 	return &Apache::lonnet::put('nohist_'.$hash_name,
   95: 				    { $id => {
   96: 					'exe_uname' => $env{'user.name'},
   97: 					'exe_udom'  => $env{'user.domain'},
   98: 					'exe_time'  => time(),
   99: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  100: 					'delflag'   => $delflag,
  101: 					'logentry'  => $storehash,
  102: 					'uname'     => $uname,
  103: 					'udom'      => $udom,
  104: 				    }
  105: 				  },
  106: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
  107: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
  108: 				    );
  109:     }
  110: }
  111: 
  112: sub logtouch {
  113:     my $execdir=$perlvar{'lonDaemons'};
  114:     unless (-e "$execdir/logs/lonnet.log") {	
  115: 	open(my $fh,">>$execdir/logs/lonnet.log");
  116: 	close $fh;
  117:     }
  118:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  119:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  120: }
  121: 
  122: sub logthis {
  123:     my $message=shift;
  124:     my $execdir=$perlvar{'lonDaemons'};
  125:     my $now=time;
  126:     my $local=localtime($now);
  127:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  128: 	print $fh "$local ($$): $message\n";
  129: 	close($fh);
  130:     }
  131:     return 1;
  132: }
  133: 
  134: sub logperm {
  135:     my $message=shift;
  136:     my $execdir=$perlvar{'lonDaemons'};
  137:     my $now=time;
  138:     my $local=localtime($now);
  139:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  140: 	print $fh "$now:$message:$local\n";
  141: 	close($fh);
  142:     }
  143:     return 1;
  144: }
  145: 
  146: # -------------------------------------------------- Non-critical communication
  147: sub subreply {
  148:     my ($cmd,$server)=@_;
  149:     my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
  150:     #
  151:     #  With loncnew process trimming, there's a timing hole between lonc server
  152:     #  process exit and the master server picking up the listen on the AF_UNIX
  153:     #  socket.  In that time interval, a lock file will exist:
  154: 
  155:     my $lockfile=$peerfile.".lock";
  156:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  157: 	sleep(1);
  158:     }
  159:     # At this point, either a loncnew parent is listening or an old lonc
  160:     # or loncnew child is listening so we can connect or everything's dead.
  161:     #
  162:     #   We'll give the connection a few tries before abandoning it.  If
  163:     #   connection is not possible, we'll con_lost back to the client.
  164:     #   
  165:     my $client;
  166:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  167: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  168: 				      Type    => SOCK_STREAM,
  169: 				      Timeout => 10);
  170: 	if($client) {
  171: 	    last;		# Connected!
  172: 	}
  173: 	sleep(1);		# Try again later if failed connection.
  174:     }
  175:     my $answer;
  176:     if ($client) {
  177: 	print $client "sethost:$server:$cmd\n";
  178: 	$answer=<$client>;
  179: 	if (!$answer) { $answer="con_lost"; }
  180: 	chomp($answer);
  181:     } else {
  182: 	$answer = 'con_lost';	# Failed connection.
  183:     }
  184:     return $answer;
  185: }
  186: 
  187: sub reply {
  188:     my ($cmd,$server)=@_;
  189:     unless (defined($hostname{$server})) { return 'no_such_host'; }
  190:     my $answer=subreply($cmd,$server);
  191:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  192:        &logthis("<font color=\"blue\">WARNING:".
  193:                 " $cmd to $server returned $answer</font>");
  194:     }
  195:     return $answer;
  196: }
  197: 
  198: # ----------------------------------------------------------- Send USR1 to lonc
  199: 
  200: sub reconlonc {
  201:     my $peerfile=shift;
  202:     &logthis("Trying to reconnect for $peerfile");
  203:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  204:     if (open(my $fh,"<$loncfile")) {
  205: 	my $loncpid=<$fh>;
  206:         chomp($loncpid);
  207:         if (kill 0 => $loncpid) {
  208: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  209:             kill USR1 => $loncpid;
  210:             sleep 1;
  211:             if (-e "$peerfile") { return; }
  212:             &logthis("$peerfile still not there, give it another try");
  213:             sleep 5;
  214:             if (-e "$peerfile") { return; }
  215:             &logthis(
  216:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
  217:         } else {
  218: 	    &logthis(
  219:                "<font color=\"blue\">WARNING:".
  220:                " lonc at pid $loncpid not responding, giving up</font>");
  221:         }
  222:     } else {
  223:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  224:     }
  225: }
  226: 
  227: # ------------------------------------------------------ Critical communication
  228: 
  229: sub critical {
  230:     my ($cmd,$server)=@_;
  231:     unless ($hostname{$server}) {
  232:         &logthis("<font color=\"blue\">WARNING:".
  233:                " Critical message to unknown server ($server)</font>");
  234:         return 'no_such_host';
  235:     }
  236:     my $answer=reply($cmd,$server);
  237:     if ($answer eq 'con_lost') {
  238: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  239: 	my $answer=reply($cmd,$server);
  240:         if ($answer eq 'con_lost') {
  241:             my $now=time;
  242:             my $middlename=$cmd;
  243:             $middlename=substr($middlename,0,16);
  244:             $middlename=~s/\W//g;
  245:             my $dfilename=
  246:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  247:             $dumpcount++;
  248:             {
  249: 		my $dfh;
  250: 		if (open($dfh,">$dfilename")) {
  251: 		    print $dfh "$cmd\n"; 
  252: 		    close($dfh);
  253: 		}
  254:             }
  255:             sleep 2;
  256:             my $wcmd='';
  257:             {
  258: 		my $dfh;
  259: 		if (open($dfh,"<$dfilename")) {
  260: 		    $wcmd=<$dfh>; 
  261: 		    close($dfh);
  262: 		}
  263:             }
  264:             chomp($wcmd);
  265:             if ($wcmd eq $cmd) {
  266: 		&logthis("<font color=\"blue\">WARNING: ".
  267:                          "Connection buffer $dfilename: $cmd</font>");
  268:                 &logperm("D:$server:$cmd");
  269: 	        return 'con_delayed';
  270:             } else {
  271:                 &logthis("<font color=\"red\">CRITICAL:"
  272:                         ." Critical connection failed: $server $cmd</font>");
  273:                 &logperm("F:$server:$cmd");
  274:                 return 'con_failed';
  275:             }
  276:         }
  277:     }
  278:     return $answer;
  279: }
  280: 
  281: # ------------------------------------------- Transfer profile into environment
  282: 
  283: sub transfer_profile_to_env {
  284:     my ($lonidsdir,$handle)=@_;
  285:     if (!defined($lonidsdir)) {
  286: 	$lonidsdir = $perlvar{'lonIDsDir'};
  287:     }
  288:     if (!defined($handle)) {
  289:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  290:     }
  291: 
  292:     my @profile;
  293:     {
  294: 	open(my $idf,"$lonidsdir/$handle.id");
  295: 	flock($idf,LOCK_SH);
  296: 	@profile=<$idf>;
  297: 	close($idf);
  298:     }
  299:     my $envi;
  300:     my %Remove;
  301:     for ($envi=0;$envi<=$#profile;$envi++) {
  302: 	chomp($profile[$envi]);
  303: 	my ($envname,$envvalue)=split(/=/,$profile[$envi],2);
  304: 	$envname=&unescape($envname);
  305: 	$envvalue=&unescape($envvalue);
  306: 	$env{$envname} = $envvalue;
  307:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  308:             if ($time < time-300) {
  309:                 $Remove{$key}++;
  310:             }
  311:         }
  312:     }
  313:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  314:     foreach my $expired_key (keys(%Remove)) {
  315:         &delenv($expired_key);
  316:     }
  317: }
  318: 
  319: # ---------------------------------------------------------- Append Environment
  320: 
  321: sub appenv {
  322:     my %newenv=@_;
  323:     foreach my $key (keys(%newenv)) {
  324: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
  325:             &logthis("<font color=\"blue\">WARNING: ".
  326:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
  327:                 .'</font>');
  328: 	    delete($newenv{$key});
  329:         } else {
  330:             $env{$key}=$newenv{$key};
  331:         }
  332:     }
  333: 
  334:     my $lockfh;
  335:     unless (open($lockfh,"$env{'user.environment'}")) {
  336: 	return 'error: '.$!;
  337:     }
  338:     unless (flock($lockfh,LOCK_EX)) {
  339:          &logthis("<font color=\"blue\">WARNING: ".
  340:                   'Could not obtain exclusive lock in appenv: '.$!);
  341:          close($lockfh);
  342:          return 'error: '.$!;
  343:     }
  344: 
  345:     my @oldenv;
  346:     {
  347: 	my $fh;
  348: 	unless (open($fh,"$env{'user.environment'}")) {
  349: 	    return 'error: '.$!;
  350: 	}
  351: 	@oldenv=<$fh>;
  352: 	close($fh);
  353:     }
  354:     for (my $i=0; $i<=$#oldenv; $i++) {
  355:         chomp($oldenv[$i]);
  356:         if ($oldenv[$i] ne '') {
  357: 	    my ($name,$value)=split(/=/,$oldenv[$i],2);
  358: 	    $name=&unescape($name);
  359: 	    $value=&unescape($value);
  360: 	    unless (defined($newenv{$name})) {
  361: 		$newenv{$name}=$value;
  362: 	    }
  363:         }
  364:     }
  365:     {
  366: 	my $fh;
  367: 	unless (open($fh,">$env{'user.environment'}")) {
  368: 	    return 'error';
  369: 	}
  370: 	my $newname;
  371: 	foreach $newname (keys %newenv) {
  372: 	    print $fh &escape($newname).'='.&escape($newenv{$newname})."\n";
  373: 	}
  374: 	close($fh);
  375:     }
  376: 	
  377:     close($lockfh);
  378:     return 'ok';
  379: }
  380: # ----------------------------------------------------- Delete from Environment
  381: 
  382: sub delenv {
  383:     my $delthis=shift;
  384:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  385:         &logthis("<font color=\"blue\">WARNING: ".
  386:                 "Attempt to delete from environment ".$delthis);
  387:         return 'error';
  388:     }
  389:     my @oldenv;
  390:     {
  391: 	my $fh;
  392: 	unless (open($fh,"$env{'user.environment'}")) {
  393: 	    return 'error';
  394: 	}
  395: 	unless (flock($fh,LOCK_SH)) {
  396: 	    &logthis("<font color=\"blue\">WARNING: ".
  397: 		     'Could not obtain shared lock in delenv: '.$!);
  398: 	    close($fh);
  399: 	    return 'error: '.$!;
  400: 	}
  401: 	@oldenv=<$fh>;
  402: 	close($fh);
  403:     }
  404:     {
  405: 	my $fh;
  406: 	unless (open($fh,">$env{'user.environment'}")) {
  407: 	    return 'error';
  408: 	}
  409: 	unless (flock($fh,LOCK_EX)) {
  410: 	    &logthis("<font color=\"blue\">WARNING: ".
  411: 		     'Could not obtain exclusive lock in delenv: '.$!);
  412: 	    close($fh);
  413: 	    return 'error: '.$!;
  414: 	}
  415: 	foreach my $cur_key (@oldenv) {
  416: 	    my $unescaped_cur_key = &unescape($cur_key);
  417: 	    if ($unescaped_cur_key=~/^$delthis/) { 
  418:                 my ($key) = split('=',$cur_key,2);
  419: 		$key = &unescape($key);
  420:                 delete($env{$key});
  421:             } else {
  422:                 print $fh $cur_key; 
  423:             }
  424: 	}
  425: 	close($fh);
  426:     }
  427:     return 'ok';
  428: }
  429: 
  430: # ------------------------------------------ Find out current server userload
  431: # there is a copy in lond
  432: sub userload {
  433:     my $numusers=0;
  434:     {
  435: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  436: 	my $filename;
  437: 	my $curtime=time;
  438: 	while ($filename=readdir(LONIDS)) {
  439: 	    if ($filename eq '.' || $filename eq '..') {next;}
  440: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  441: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  442: 	}
  443: 	closedir(LONIDS);
  444:     }
  445:     my $userloadpercent=0;
  446:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  447:     if ($maxuserload) {
  448: 	$userloadpercent=100*$numusers/$maxuserload;
  449:     }
  450:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  451:     return $userloadpercent;
  452: }
  453: 
  454: # ------------------------------------------ Fight off request when overloaded
  455: 
  456: sub overloaderror {
  457:     my ($r,$checkserver)=@_;
  458:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  459:     my $loadavg;
  460:     if ($checkserver eq $perlvar{'lonHostID'}) {
  461:        open(my $loadfile,'/proc/loadavg');
  462:        $loadavg=<$loadfile>;
  463:        $loadavg =~ s/\s.*//g;
  464:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  465:        close($loadfile);
  466:     } else {
  467:        $loadavg=&reply('load',$checkserver);
  468:     }
  469:     my $overload=$loadavg-100;
  470:     if ($overload>0) {
  471: 	$r->err_headers_out->{'Retry-After'}=$overload;
  472:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  473:         return 413;
  474:     }    
  475:     return '';
  476: }
  477: 
  478: # ------------------------------ Find server with least workload from spare.tab
  479: 
  480: sub spareserver {
  481:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  482:     my $tryserver;
  483:     my $spareserver='';
  484:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  485:     my $lowestserver=$loadpercent > $userloadpercent?
  486: 	             $loadpercent :  $userloadpercent;
  487:     foreach $tryserver (keys(%spareid)) {
  488: 	my $loadans=&reply('load',$tryserver);
  489: 	my $userloadans=&reply('userload',$tryserver);
  490: 	if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  491: 	    next; #didn't get a number from the server
  492: 	}
  493: 	my $answer;
  494: 	if ($loadans =~ /\d/) {
  495: 	    if ($userloadans =~ /\d/) {
  496: 		#both are numbers, pick the bigger one
  497: 		$answer=$loadans > $userloadans?
  498: 		    $loadans :  $userloadans;
  499: 	    } else {
  500: 		$answer = $loadans;
  501: 	    }
  502: 	} else {
  503: 	    $answer = $userloadans;
  504: 	}
  505: 	if (($answer =~ /\d/) && ($answer<$lowestserver)) {
  506: 	    if ($want_server_name) {
  507: 		$spareserver=$tryserver;
  508: 	    } else {
  509: 		$spareserver="http://$hostname{$tryserver}";
  510: 	    }
  511: 	    $lowestserver=$answer;
  512: 	}
  513:     }
  514:     return $spareserver;
  515: }
  516: 
  517: # --------------------------------------------- Try to change a user's password
  518: 
  519: sub changepass {
  520:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
  521:     $currentpass = &escape($currentpass);
  522:     $newpass     = &escape($newpass);
  523:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
  524: 		       $server);
  525:     if (! $answer) {
  526: 	&logthis("No reply on password change request to $server ".
  527: 		 "by $uname in domain $udom.");
  528:     } elsif ($answer =~ "^ok") {
  529:         &logthis("$uname in $udom successfully changed their password ".
  530: 		 "on $server.");
  531:     } elsif ($answer =~ "^pwchange_failure") {
  532: 	&logthis("$uname in $udom was unable to change their password ".
  533: 		 "on $server.  The action was blocked by either lcpasswd ".
  534: 		 "or pwchange");
  535:     } elsif ($answer =~ "^non_authorized") {
  536:         &logthis("$uname in $udom did not get their password correct when ".
  537: 		 "attempting to change it on $server.");
  538:     } elsif ($answer =~ "^auth_mode_error") {
  539:         &logthis("$uname in $udom attempted to change their password despite ".
  540: 		 "not being locally or internally authenticated on $server.");
  541:     } elsif ($answer =~ "^unknown_user") {
  542:         &logthis("$uname in $udom attempted to change their password ".
  543: 		 "on $server but were unable to because $server is not ".
  544: 		 "their home server.");
  545:     } elsif ($answer =~ "^refused") {
  546: 	&logthis("$server refused to change $uname in $udom password because ".
  547: 		 "it was sent an unencrypted request to change the password.");
  548:     }
  549:     return $answer;
  550: }
  551: 
  552: # ----------------------- Try to determine user's current authentication scheme
  553: 
  554: sub queryauthenticate {
  555:     my ($uname,$udom)=@_;
  556:     my $uhome=&homeserver($uname,$udom);
  557:     if (!$uhome) {
  558: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  559: 	return 'no_host';
  560:     }
  561:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  562:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  563: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  564:     }
  565:     return $answer;
  566: }
  567: 
  568: # --------- Try to authenticate user from domain's lib servers (first this one)
  569: 
  570: sub authenticate {
  571:     my ($uname,$upass,$udom)=@_;
  572:     $upass=escape($upass);
  573:     $uname=~s/\W//g;
  574:     my $uhome=&homeserver($uname,$udom);
  575:     if (!$uhome) {
  576: 	&logthis("User $uname at $udom is unknown in authenticate");
  577: 	return 'no_host';
  578:     }
  579:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
  580:     if ($answer eq 'authorized') {
  581: 	&logthis("User $uname at $udom authorized by $uhome"); 
  582: 	return $uhome; 
  583:     }
  584:     if ($answer eq 'non_authorized') {
  585: 	&logthis("User $uname at $udom rejected by $uhome");
  586: 	return 'no_host'; 
  587:     }
  588:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  589:     return 'no_host';
  590: }
  591: 
  592: # ---------------------- Find the homebase for a user from domain's lib servers
  593: 
  594: my %homecache;
  595: sub homeserver {
  596:     my ($uname,$udom,$ignoreBadCache)=@_;
  597:     my $index="$uname:$udom";
  598: 
  599:     if (exists($homecache{$index})) { return $homecache{$index}; }
  600:     my $tryserver;
  601:     foreach $tryserver (keys %libserv) {
  602:         next if ($ignoreBadCache ne 'true' && 
  603: 		 exists($badServerCache{$tryserver}));
  604: 	if ($hostdom{$tryserver} eq $udom) {
  605:            my $answer=reply("home:$udom:$uname",$tryserver);
  606:            if ($answer eq 'found') { 
  607: 	       return $homecache{$index}=$tryserver;
  608:            } elsif ($answer eq 'no_host') {
  609: 	       $badServerCache{$tryserver}=1;
  610:            }
  611:        }
  612:     }    
  613:     return 'no_host';
  614: }
  615: 
  616: # ------------------------------------- Find the usernames behind a list of IDs
  617: 
  618: sub idget {
  619:     my ($udom,@ids)=@_;
  620:     my %returnhash=();
  621:     
  622:     my $tryserver;
  623:     foreach $tryserver (keys %libserv) {
  624:        if ($hostdom{$tryserver} eq $udom) {
  625: 	  my $idlist=join('&',@ids);
  626:           $idlist=~tr/A-Z/a-z/; 
  627: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  628:           my @answer=();
  629:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  630: 	      @answer=split(/\&/,$reply);
  631:           }                    ;
  632:           my $i;
  633:           for ($i=0;$i<=$#ids;$i++) {
  634:               if ($answer[$i]) {
  635: 		  $returnhash{$ids[$i]}=$answer[$i];
  636:               } 
  637:           }
  638:        }
  639:     }    
  640:     return %returnhash;
  641: }
  642: 
  643: # ------------------------------------- Find the IDs behind a list of usernames
  644: 
  645: sub idrget {
  646:     my ($udom,@unames)=@_;
  647:     my %returnhash=();
  648:     foreach (@unames) {
  649:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
  650:     }
  651:     return %returnhash;
  652: }
  653: 
  654: # ------------------------------- Store away a list of names and associated IDs
  655: 
  656: sub idput {
  657:     my ($udom,%ids)=@_;
  658:     my %servers=();
  659:     foreach (keys %ids) {
  660: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
  661:         my $uhom=&homeserver($_,$udom);
  662:         if ($uhom ne 'no_host') {
  663:             my $id=&escape($ids{$_});
  664:             $id=~tr/A-Z/a-z/;
  665:             my $unam=&escape($_);
  666: 	    if ($servers{$uhom}) {
  667: 		$servers{$uhom}.='&'.$id.'='.$unam;
  668:             } else {
  669:                 $servers{$uhom}=$id.'='.$unam;
  670:             }
  671:         }
  672:     }
  673:     foreach (keys %servers) {
  674:         &critical('idput:'.$udom.':'.$servers{$_},$_);
  675:     }
  676: }
  677: 
  678: # --------------------------------------------------- Assign a key to a student
  679: 
  680: sub assign_access_key {
  681: #
  682: # a valid key looks like uname:udom#comments
  683: # comments are being appended
  684: #
  685:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
  686:     $kdom=
  687:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
  688:     $knum=
  689:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
  690:     $cdom=
  691:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  692:     $cnum=
  693:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  694:     $udom=$env{'user.name'} unless (defined($udom));
  695:     $uname=$env{'user.domain'} unless (defined($uname));
  696:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
  697:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
  698:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
  699:                                                   # assigned to this person
  700:                                                   # - this should not happen,
  701:                                                   # unless something went wrong
  702:                                                   # the first time around
  703: # ready to assign
  704:         $logentry=$1.'; '.$logentry;
  705:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
  706:                                                  $kdom,$knum) eq 'ok') {
  707: # key now belongs to user
  708: 	    my $envkey='key.'.$cdom.'_'.$cnum;
  709:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
  710:                 &appenv('environment.'.$envkey => $ckey);
  711:                 return 'ok';
  712:             } else {
  713:                 return 
  714:   'error: Count not permanently assign key, will need to be re-entered later.';
  715: 	    }
  716:         } else {
  717:             return 'error: Could not assign key, try again later.';
  718:         }
  719:     } elsif (!$existing{$ckey}) {
  720: # the key does not exist
  721: 	return 'error: The key does not exist';
  722:     } else {
  723: # the key is somebody else's
  724: 	return 'error: The key is already in use';
  725:     }
  726: }
  727: 
  728: # ------------------------------------------ put an additional comment on a key
  729: 
  730: sub comment_access_key {
  731: #
  732: # a valid key looks like uname:udom#comments
  733: # comments are being appended
  734: #
  735:     my ($ckey,$cdom,$cnum,$logentry)=@_;
  736:     $cdom=
  737:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  738:     $cnum=
  739:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  740:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  741:     if ($existing{$ckey}) {
  742:         $existing{$ckey}.='; '.$logentry;
  743: # ready to assign
  744:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
  745:                                                  $cdom,$cnum) eq 'ok') {
  746: 	    return 'ok';
  747:         } else {
  748: 	    return 'error: Count not store comment.';
  749:         }
  750:     } else {
  751: # the key does not exist
  752: 	return 'error: The key does not exist';
  753:     }
  754: }
  755: 
  756: # ------------------------------------------------------ Generate a set of keys
  757: 
  758: sub generate_access_keys {
  759:     my ($number,$cdom,$cnum,$logentry)=@_;
  760:     $cdom=
  761:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  762:     $cnum=
  763:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  764:     unless (&allowed('mky',$cdom)) { return 0; }
  765:     unless (($cdom) && ($cnum)) { return 0; }
  766:     if ($number>10000) { return 0; }
  767:     sleep(2); # make sure don't get same seed twice
  768:     srand(time()^($$+($$<<15))); # from "Programming Perl"
  769:     my $total=0;
  770:     for (my $i=1;$i<=$number;$i++) {
  771:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
  772:                   sprintf("%lx",int(100000*rand)).'-'.
  773:                   sprintf("%lx",int(100000*rand));
  774:        $newkey=~s/1/g/g; # folks mix up 1 and l
  775:        $newkey=~s/0/h/g; # and also 0 and O
  776:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
  777:        if ($existing{$newkey}) {
  778:            $i--;
  779:        } else {
  780: 	  if (&put('accesskeys',
  781:               { $newkey => '# generated '.localtime().
  782:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
  783:                            '; '.$logentry },
  784: 		   $cdom,$cnum) eq 'ok') {
  785:               $total++;
  786: 	  }
  787:        }
  788:     }
  789:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
  790:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
  791:     return $total;
  792: }
  793: 
  794: # ------------------------------------------------------- Validate an accesskey
  795: 
  796: sub validate_access_key {
  797:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
  798:     $cdom=
  799:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  800:     $cnum=
  801:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  802:     $udom=$env{'user.domain'} unless (defined($udom));
  803:     $uname=$env{'user.name'} unless (defined($uname));
  804:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  805:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
  806: }
  807: 
  808: # ------------------------------------- Find the section of student in a course
  809: sub devalidate_getsection_cache {
  810:     my ($udom,$unam,$courseid)=@_;
  811:     $courseid=~s/\_/\//g;
  812:     $courseid=~s/^(\w)/\/$1/;
  813:     my $hashid="$udom:$unam:$courseid";
  814:     &devalidate_cache_new('getsection',$hashid);
  815: }
  816: 
  817: sub getsection {
  818:     my ($udom,$unam,$courseid)=@_;
  819:     my $cachetime=1800;
  820:     $courseid=~s/\_/\//g;
  821:     $courseid=~s/^(\w)/\/$1/;
  822: 
  823:     my $hashid="$udom:$unam:$courseid";
  824:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
  825:     if (defined($cached)) { return $result; }
  826: 
  827:     my %Pending; 
  828:     my %Expired;
  829:     #
  830:     # Each role can either have not started yet (pending), be active, 
  831:     #    or have expired.
  832:     #
  833:     # If there is an active role, we are done.
  834:     #
  835:     # If there is more than one role which has not started yet, 
  836:     #     choose the one which will start sooner
  837:     # If there is one role which has not started yet, return it.
  838:     #
  839:     # If there is more than one expired role, choose the one which ended last.
  840:     # If there is a role which has expired, return it.
  841:     #
  842:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
  843:                         &homeserver($unam,$udom)))) {
  844:         my ($key,$value)=split(/\=/,$_);
  845:         $key=&unescape($key);
  846:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
  847:         my $section=$1;
  848:         if ($key eq $courseid.'_st') { $section=''; }
  849:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
  850:         my $now=time;
  851:         if (defined($end) && $end && ($now > $end)) {
  852:             $Expired{$end}=$section;
  853:             next;
  854:         }
  855:         if (defined($start) && $start && ($now < $start)) {
  856:             $Pending{$start}=$section;
  857:             next;
  858:         }
  859:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
  860:     }
  861:     #
  862:     # Presumedly there will be few matching roles from the above
  863:     # loop and the sorting time will be negligible.
  864:     if (scalar(keys(%Pending))) {
  865:         my ($time) = sort {$a <=> $b} keys(%Pending);
  866:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
  867:     } 
  868:     if (scalar(keys(%Expired))) {
  869:         my @sorted = sort {$a <=> $b} keys(%Expired);
  870:         my $time = pop(@sorted);
  871:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
  872:     }
  873:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
  874: }
  875: 
  876: sub save_cache {
  877:     &purge_remembered();
  878:     #&Apache::loncommon::validate_page();
  879:     undef(%env);
  880: }
  881: 
  882: my $to_remember=-1;
  883: my %remembered;
  884: my %accessed;
  885: my $kicks=0;
  886: my $hits=0;
  887: sub devalidate_cache_new {
  888:     my ($name,$id,$debug) = @_;
  889:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
  890:     $id=&escape($name.':'.$id);
  891:     $memcache->delete($id);
  892:     delete($remembered{$id});
  893:     delete($accessed{$id});
  894: }
  895: 
  896: sub is_cached_new {
  897:     my ($name,$id,$debug) = @_;
  898:     $id=&escape($name.':'.$id);
  899:     if (exists($remembered{$id})) {
  900: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
  901: 	$accessed{$id}=[&gettimeofday()];
  902: 	$hits++;
  903: 	return ($remembered{$id},1);
  904:     }
  905:     my $value = $memcache->get($id);
  906:     if (!(defined($value))) {
  907: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
  908: 	return (undef,undef);
  909:     }
  910:     if ($value eq '__undef__') {
  911: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
  912: 	$value=undef;
  913:     }
  914:     &make_room($id,$value,$debug);
  915:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
  916:     return ($value,1);
  917: }
  918: 
  919: sub do_cache_new {
  920:     my ($name,$id,$value,$time,$debug) = @_;
  921:     $id=&escape($name.':'.$id);
  922:     my $setvalue=$value;
  923:     if (!defined($setvalue)) {
  924: 	$setvalue='__undef__';
  925:     }
  926:     if (!defined($time) ) {
  927: 	$time=600;
  928:     }
  929:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
  930:     $memcache->set($id,$setvalue,$time);
  931:     # need to make a copy of $value
  932:     #&make_room($id,$value,$debug);
  933:     return $value;
  934: }
  935: 
  936: sub make_room {
  937:     my ($id,$value,$debug)=@_;
  938:     $remembered{$id}=$value;
  939:     if ($to_remember<0) { return; }
  940:     $accessed{$id}=[&gettimeofday()];
  941:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
  942:     my $to_kick;
  943:     my $max_time=0;
  944:     foreach my $other (keys(%accessed)) {
  945: 	if (&tv_interval($accessed{$other}) > $max_time) {
  946: 	    $to_kick=$other;
  947: 	    $max_time=&tv_interval($accessed{$other});
  948: 	}
  949:     }
  950:     delete($remembered{$to_kick});
  951:     delete($accessed{$to_kick});
  952:     $kicks++;
  953:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
  954:     return;
  955: }
  956: 
  957: sub purge_remembered {
  958:     #&logthis("Tossing ".scalar(keys(%remembered)));
  959:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
  960:     undef(%remembered);
  961:     undef(%accessed);
  962: }
  963: # ------------------------------------- Read an entry from a user's environment
  964: 
  965: sub userenvironment {
  966:     my ($udom,$unam,@what)=@_;
  967:     my %returnhash=();
  968:     my @answer=split(/\&/,
  969:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
  970:                       &homeserver($unam,$udom)));
  971:     my $i;
  972:     for ($i=0;$i<=$#what;$i++) {
  973: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
  974:     }
  975:     return %returnhash;
  976: }
  977: 
  978: # ---------------------------------------------------------- Get a studentphoto
  979: sub studentphoto {
  980:     my ($udom,$unam,$ext) = @_;
  981:     my $home=&Apache::lonnet::homeserver($unam,$udom);
  982:     if (defined($env{'request.course.id'})) {
  983:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
  984:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
  985:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
  986:             } else {
  987:                 my ($result,$perm_reqd)=
  988: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
  989:                 if ($result eq 'ok') {
  990:                     if (!($perm_reqd eq 'yes')) {
  991:                         return(&retrievestudentphoto($udom,$unam,$ext));
  992:                     }
  993:                 }
  994:             }
  995:         }
  996:     } else {
  997:         my ($result,$perm_reqd) = 
  998: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
  999:         if ($result eq 'ok') {
 1000:             if (!($perm_reqd eq 'yes')) {
 1001:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1002:             }
 1003:         }
 1004:     }
 1005:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1006: }
 1007: 
 1008: sub retrievestudentphoto {
 1009:     my ($udom,$unam,$ext,$type) = @_;
 1010:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1011:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1012:     if ($ret eq 'ok') {
 1013:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1014:         if ($type eq 'thumbnail') {
 1015:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1016:         }
 1017:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1018:         return $tokenurl;
 1019:     } else {
 1020:         if ($type eq 'thumbnail') {
 1021:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1022:         } else { 
 1023:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1024:         }
 1025:     }
 1026: }
 1027: 
 1028: # -------------------------------------------------------------------- New chat
 1029: 
 1030: sub chatsend {
 1031:     my ($newentry,$anon,$group)=@_;
 1032:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1033:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1034:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1035:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1036: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1037: 		   &escape($newentry)).':'.$group,$chome);
 1038: }
 1039: 
 1040: # ------------------------------------------ Find current version of a resource
 1041: 
 1042: sub getversion {
 1043:     my $fname=&clutter(shift);
 1044:     unless ($fname=~/^\/res\//) { return -1; }
 1045:     return &currentversion(&filelocation('',$fname));
 1046: }
 1047: 
 1048: sub currentversion {
 1049:     my $fname=shift;
 1050:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1051:     if (defined($cached)) { return $result; }
 1052:     my $author=$fname;
 1053:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1054:     my ($udom,$uname)=split(/\//,$author);
 1055:     my $home=homeserver($uname,$udom);
 1056:     if ($home eq 'no_host') { 
 1057:         return -1; 
 1058:     }
 1059:     my $answer=reply("currentversion:$fname",$home);
 1060:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1061: 	return -1;
 1062:     }
 1063:     return &do_cache_new('resversion',$fname,$answer,600);
 1064: }
 1065: 
 1066: # ----------------------------- Subscribe to a resource, return URL if possible
 1067: 
 1068: sub subscribe {
 1069:     my $fname=shift;
 1070:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1071:     $fname=~s/[\n\r]//g;
 1072:     my $author=$fname;
 1073:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1074:     my ($udom,$uname)=split(/\//,$author);
 1075:     my $home=homeserver($uname,$udom);
 1076:     if ($home eq 'no_host') {
 1077:         return 'not_found';
 1078:     }
 1079:     my $answer=reply("sub:$fname",$home);
 1080:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1081: 	$answer.=' by '.$home;
 1082:     }
 1083:     return $answer;
 1084: }
 1085:     
 1086: # -------------------------------------------------------------- Replicate file
 1087: 
 1088: sub repcopy {
 1089:     my $filename=shift;
 1090:     $filename=~s/\/+/\//g;
 1091:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1092:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1093:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1094: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1095: 	return &repcopy_userfile($filename);
 1096:     }
 1097:     $filename=~s/[\n\r]//g;
 1098:     my $transname="$filename.in.transfer";
 1099:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1100:     my $remoteurl=subscribe($filename);
 1101:     if ($remoteurl =~ /^con_lost by/) {
 1102: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1103:            return 'unavailable';
 1104:     } elsif ($remoteurl eq 'not_found') {
 1105: 	   #&logthis("Subscribe returned not_found: $filename");
 1106: 	   return 'not_found';
 1107:     } elsif ($remoteurl =~ /^rejected by/) {
 1108: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1109:            return 'forbidden';
 1110:     } elsif ($remoteurl eq 'directory') {
 1111:            return 'ok';
 1112:     } else {
 1113:         my $author=$filename;
 1114:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1115:         my ($udom,$uname)=split(/\//,$author);
 1116:         my $home=homeserver($uname,$udom);
 1117:         unless ($home eq $perlvar{'lonHostID'}) {
 1118:            my @parts=split(/\//,$filename);
 1119:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1120:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1121:                &logthis("Malconfiguration for replication: $filename");
 1122: 	       return 'bad_request';
 1123:            }
 1124:            my $count;
 1125:            for ($count=5;$count<$#parts;$count++) {
 1126:                $path.="/$parts[$count]";
 1127:                if ((-e $path)!=1) {
 1128: 		   mkdir($path,0777);
 1129:                }
 1130:            }
 1131:            my $ua=new LWP::UserAgent;
 1132:            my $request=new HTTP::Request('GET',"$remoteurl");
 1133:            my $response=$ua->request($request,$transname);
 1134:            if ($response->is_error()) {
 1135: 	       unlink($transname);
 1136:                my $message=$response->status_line;
 1137:                &logthis("<font color=\"blue\">WARNING:"
 1138:                        ." LWP get: $message: $filename</font>");
 1139:                return 'unavailable';
 1140:            } else {
 1141: 	       if ($remoteurl!~/\.meta$/) {
 1142:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1143:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1144:                   if ($mresponse->is_error()) {
 1145: 		      unlink($filename.'.meta');
 1146:                       &logthis(
 1147:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1148:                   }
 1149: 	       }
 1150:                rename($transname,$filename);
 1151:                return 'ok';
 1152:            }
 1153:        }
 1154:     }
 1155: }
 1156: 
 1157: # ------------------------------------------------ Get server side include body
 1158: sub ssi_body {
 1159:     my ($filelink,%form)=@_;
 1160:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1161:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1162:     }
 1163:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
 1164:                                      &ssi($filelink,%form));
 1165:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+// END LON-CAPA Internal\s*(-->)?\s||gs;
 1166:     $output=~s/^.*?\<body[^\>]*\>//si;
 1167:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
 1168:     return $output;
 1169: }
 1170: 
 1171: # --------------------------------------------------------- Server Side Include
 1172: 
 1173: sub ssi {
 1174: 
 1175:     my ($fn,%form)=@_;
 1176: 
 1177:     my $ua=new LWP::UserAgent;
 1178:     
 1179:     my $request;
 1180: 
 1181:     $form{'no_update_last_known'}=1;
 1182: 
 1183:     if (%form) {
 1184:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
 1185:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1186:     } else {
 1187:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
 1188:     }
 1189: 
 1190:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1191:     my $response=$ua->request($request);
 1192: 
 1193:     return $response->content;
 1194: }
 1195: 
 1196: sub externalssi {
 1197:     my ($url)=@_;
 1198:     my $ua=new LWP::UserAgent;
 1199:     my $request=new HTTP::Request('GET',$url);
 1200:     my $response=$ua->request($request);
 1201:     return $response->content;
 1202: }
 1203: 
 1204: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1205: 
 1206: sub allowuploaded {
 1207:     my ($srcurl,$url)=@_;
 1208:     $url=&clutter(&declutter($url));
 1209:     my $dir=$url;
 1210:     $dir=~s/\/[^\/]+$//;
 1211:     my %httpref=();
 1212:     my $httpurl=&hreflocation('',$url);
 1213:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1214:     &Apache::lonnet::appenv(%httpref);
 1215: }
 1216: 
 1217: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1218: # input: action, courseID, current domain, intended
 1219: #        path to file, source of file, instruction to parse file for objects,
 1220: #        ref to hash for embedded objects,
 1221: #        ref to hash for codebase of java objects.
 1222: #
 1223: # output: url to file (if action was uploaddoc), 
 1224: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1225: #
 1226: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1227: # course.
 1228: #
 1229: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1230: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1231: #          course's home server.
 1232: #
 1233: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1234: #          be copied from $source (current location) to 
 1235: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1236: #         and will then be copied to
 1237: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1238: #         course's home server.
 1239: #
 1240: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1241: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1242: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1243: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1244: #         in course's home server.
 1245: #
 1246: 
 1247: sub process_coursefile {
 1248:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1249:     my $fetchresult;
 1250:     my $home=&homeserver($docuname,$docudom);
 1251:     if ($action eq 'propagate') {
 1252:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1253: 			     $home);
 1254:     } else {
 1255:         my $fpath = '';
 1256:         my $fname = $file;
 1257:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1258:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1259:         my $filepath = &build_filepath($fpath);
 1260:         if ($action eq 'copy') {
 1261:             if ($source eq '') {
 1262:                 $fetchresult = 'no source file';
 1263:                 return $fetchresult;
 1264:             } else {
 1265:                 my $destination = $filepath.'/'.$fname;
 1266:                 rename($source,$destination);
 1267:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1268:                                  $home);
 1269:             }
 1270:         } elsif ($action eq 'uploaddoc') {
 1271:             open(my $fh,'>'.$filepath.'/'.$fname);
 1272:             print $fh $env{'form.'.$source};
 1273:             close($fh);
 1274:             if ($parser eq 'parse') {
 1275:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
 1276:                 unless ($parse_result eq 'ok') {
 1277:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1278:                 }
 1279:             }
 1280:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1281:                                  $home);
 1282:             if ($fetchresult eq 'ok') {
 1283:                 return '/uploaded/'.$fpath.'/'.$fname;
 1284:             } else {
 1285:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1286:                         ' to host '.$home.': '.$fetchresult);
 1287:                 return '/adm/notfound.html';
 1288:             }
 1289:         }
 1290:     }
 1291:     unless ( $fetchresult eq 'ok') {
 1292:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1293:              ' to host '.$home.': '.$fetchresult);
 1294:     }
 1295:     return $fetchresult;
 1296: }
 1297: 
 1298: sub build_filepath {
 1299:     my ($fpath) = @_;
 1300:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1301:     unless ($fpath eq '') {
 1302:         my @parts=split('/',$fpath);
 1303:         foreach my $part (@parts) {
 1304:             $filepath.= '/'.$part;
 1305:             if ((-e $filepath)!=1) {
 1306:                 mkdir($filepath,0777);
 1307:             }
 1308:         }
 1309:     }
 1310:     return $filepath;
 1311: }
 1312: 
 1313: sub store_edited_file {
 1314:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1315:     my $file = $primary_url;
 1316:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1317:     my $fpath = '';
 1318:     my $fname = $file;
 1319:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1320:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1321:     my $filepath = &build_filepath($fpath);
 1322:     open(my $fh,'>'.$filepath.'/'.$fname);
 1323:     print $fh $content;
 1324:     close($fh);
 1325:     my $home=&homeserver($docuname,$docudom);
 1326:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1327: 			  $home);
 1328:     if ($$fetchresult eq 'ok') {
 1329:         return '/uploaded/'.$fpath.'/'.$fname;
 1330:     } else {
 1331:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1332: 		 ' to host '.$home.': '.$$fetchresult);
 1333:         return '/adm/notfound.html';
 1334:     }
 1335: }
 1336: 
 1337: sub clean_filename {
 1338:     my ($fname)=@_;
 1339: # Replace Windows backslashes by forward slashes
 1340:     $fname=~s/\\/\//g;
 1341: # Get rid of everything but the actual filename
 1342:     $fname=~s/^.*\/([^\/]+)$/$1/;
 1343: # Replace spaces by underscores
 1344:     $fname=~s/\s+/\_/g;
 1345: # Replace all other weird characters by nothing
 1346:     $fname=~s/[^\w\.\-]//g;
 1347: # Replace all .\d. sequences with _\d. so they no longer look like version
 1348: # numbers
 1349:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1350:     return $fname;
 1351: }
 1352: 
 1353: # --------------- Take an uploaded file and put it into the userfiles directory
 1354: # input: $formname - the contents of the file are in $env{"form.$formname"}
 1355: #                    the desired filenam is in $env{"form.$formname.filename"}
 1356: #        $coursedoc - if true up to the current course
 1357: #                     if false
 1358: #        $subdir - directory in userfile to store the file into
 1359: #        $parser, $allfiles, $codebase - unknown
 1360: #
 1361: # output: url of file in userspace, or error: <message> 
 1362: #             or /adm/notfound.html if failure to upload occurse
 1363: 
 1364: 
 1365: sub userfileupload {
 1366:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
 1367:     if (!defined($subdir)) { $subdir='unknown'; }
 1368:     my $fname=$env{'form.'.$formname.'.filename'};
 1369:     $fname=&clean_filename($fname);
 1370: # See if there is anything left
 1371:     unless ($fname) { return 'error: no uploaded file'; }
 1372:     chop($env{'form.'.$formname});
 1373:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1374:         my $now = time;
 1375:         my $filepath = 'tmp/helprequests/'.$now;
 1376:         my @parts=split(/\//,$filepath);
 1377:         my $fullpath = $perlvar{'lonDaemons'};
 1378:         for (my $i=0;$i<@parts;$i++) {
 1379:             $fullpath .= '/'.$parts[$i];
 1380:             if ((-e $fullpath)!=1) {
 1381:                 mkdir($fullpath,0777);
 1382:             }
 1383:         }
 1384:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1385:         print $fh $env{'form.'.$formname};
 1386:         close($fh);
 1387:         return $fullpath.'/'.$fname; 
 1388:     }
 1389:     
 1390: # Create the directory if not present
 1391:     $fname="$subdir/$fname";
 1392:     if ($coursedoc) {
 1393: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1394: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1395:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 1396:             return &finishuserfileupload($docuname,$docudom,
 1397: 					 $formname,$fname,$parser,$allfiles,
 1398: 					 $codebase);
 1399:         } else {
 1400:             $fname=$env{'form.folder'}.'/'.$fname;
 1401:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 1402: 				       $fname,$formname,$parser,
 1403: 				       $allfiles,$codebase);
 1404:         }
 1405:     } elsif (defined($destuname)) {
 1406:         my $docuname=$destuname;
 1407:         my $docudom=$destudom;
 1408: 	return &finishuserfileupload($docuname,$docudom,$formname,
 1409: 				     $fname,$parser,$allfiles,$codebase);
 1410:         
 1411:     } else {
 1412:         my $docuname=$env{'user.name'};
 1413:         my $docudom=$env{'user.domain'};
 1414:         if (exists($env{'form.group'})) {
 1415:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1416:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1417:         }
 1418: 	return &finishuserfileupload($docuname,$docudom,$formname,
 1419: 				     $fname,$parser,$allfiles,$codebase);
 1420:     }
 1421: }
 1422: 
 1423: sub finishuserfileupload {
 1424:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
 1425:     my $path=$docudom.'/'.$docuname.'/';
 1426:     my $filepath=$perlvar{'lonDocRoot'};
 1427:     my ($fnamepath,$file);
 1428:     $file=$fname;
 1429:     if ($fname=~m|/|) {
 1430:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 1431: 	$path.=$fnamepath.'/';
 1432:     }
 1433:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 1434:     my $count;
 1435:     for ($count=4;$count<=$#parts;$count++) {
 1436:         $filepath.="/$parts[$count]";
 1437:         if ((-e $filepath)!=1) {
 1438: 	    mkdir($filepath,0777);
 1439:         }
 1440:     }
 1441: # Save the file
 1442:     {
 1443: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 1444: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 1445: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 1446: 	    return '/adm/notfound.html';
 1447: 	}
 1448: 	if (!print FH ($env{'form.'.$formname})) {
 1449: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 1450: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 1451: 	    return '/adm/notfound.html';
 1452: 	}
 1453: 	close(FH);
 1454:     }
 1455:     if ($parser eq 'parse') {
 1456:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
 1457: 						   $codebase);
 1458:         unless ($parse_result eq 'ok') {
 1459:             &logthis('Failed to parse '.$filepath.$file.
 1460: 		     ' for embedded media: '.$parse_result); 
 1461:         }
 1462:     }
 1463: # Notify homeserver to grep it
 1464: #
 1465:     my $docuhome=&homeserver($docuname,$docudom);
 1466:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 1467:     if ($fetchresult eq 'ok') {
 1468: #
 1469: # Return the URL to it
 1470:         return '/uploaded/'.$path.$file;
 1471:     } else {
 1472:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 1473: 		 ': '.$fetchresult);
 1474:         return '/adm/notfound.html';
 1475:     }    
 1476: }
 1477: 
 1478: sub extract_embedded_items {
 1479:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
 1480:     my @state = ();
 1481:     my %javafiles = (
 1482:                       codebase => '',
 1483:                       code => '',
 1484:                       archive => ''
 1485:                     );
 1486:     my %mediafiles = (
 1487:                       src => '',
 1488:                       movie => '',
 1489:                      );
 1490:     my $p;
 1491:     if ($content) {
 1492:         $p = HTML::LCParser->new($content);
 1493:     } else {
 1494:         $p = HTML::LCParser->new($filepath.'/'.$file);
 1495:     }
 1496:     while (my $t=$p->get_token()) {
 1497: 	if ($t->[0] eq 'S') {
 1498: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 1499: 	    push (@state, $tagname);
 1500:             if (lc($tagname) eq 'allow') {
 1501:                 &add_filetype($allfiles,$attr->{'src'},'src');
 1502:             }
 1503: 	    if (lc($tagname) eq 'img') {
 1504: 		&add_filetype($allfiles,$attr->{'src'},'src');
 1505: 	    }
 1506:             if (lc($tagname) eq 'script') {
 1507:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 1508:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 1509:                 } else {
 1510:                     &add_filetype($allfiles,$attr->{'src'},'src');
 1511:                 }
 1512:             }
 1513:             if (lc($tagname) eq 'link') {
 1514:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 1515:                     &add_filetype($allfiles,$attr->{'href'},'href');
 1516:                 }
 1517:             }
 1518: 	    if (lc($tagname) eq 'object' ||
 1519: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 1520: 		foreach my $item (keys(%javafiles)) {
 1521: 		    $javafiles{$item} = '';
 1522: 		}
 1523: 	    }
 1524: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 1525: 		my $name = lc($attr->{'name'});
 1526: 		foreach my $item (keys(%javafiles)) {
 1527: 		    if ($name eq $item) {
 1528: 			$javafiles{$item} = $attr->{'value'};
 1529: 			last;
 1530: 		    }
 1531: 		}
 1532: 		foreach my $item (keys(%mediafiles)) {
 1533: 		    if ($name eq $item) {
 1534: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 1535: 			last;
 1536: 		    }
 1537: 		}
 1538: 	    }
 1539: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 1540: 		foreach my $item (keys(%javafiles)) {
 1541: 		    if ($attr->{$item}) {
 1542: 			$javafiles{$item} = $attr->{$item};
 1543: 			last;
 1544: 		    }
 1545: 		}
 1546: 		foreach my $item (keys(%mediafiles)) {
 1547: 		    if ($attr->{$item}) {
 1548: 			&add_filetype($allfiles,$attr->{$item},$item);
 1549: 			last;
 1550: 		    }
 1551: 		}
 1552: 	    }
 1553: 	} elsif ($t->[0] eq 'E') {
 1554: 	    my ($tagname) = ($t->[1]);
 1555: 	    if ($javafiles{'codebase'} ne '') {
 1556: 		$javafiles{'codebase'} .= '/';
 1557: 	    }  
 1558: 	    if (lc($tagname) eq 'applet' ||
 1559: 		lc($tagname) eq 'object' ||
 1560: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 1561: 		) {
 1562: 		foreach my $item (keys(%javafiles)) {
 1563: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 1564: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 1565: 			&add_filetype($allfiles,$file,$item);
 1566: 		    }
 1567: 		}
 1568: 	    } 
 1569: 	    pop @state;
 1570: 	}
 1571:     }
 1572:     return 'ok';
 1573: }
 1574: 
 1575: sub add_filetype {
 1576:     my ($allfiles,$file,$type)=@_;
 1577:     if (exists($allfiles->{$file})) {
 1578: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 1579: 	    push(@{$allfiles->{$file}}, &escape($type));
 1580: 	}
 1581:     } else {
 1582: 	@{$allfiles->{$file}} = (&escape($type));
 1583:     }
 1584: }
 1585: 
 1586: sub removeuploadedurl {
 1587:     my ($url)=@_;
 1588:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 1589:     return &removeuserfile($uname,$udom,$fname);
 1590: }
 1591: 
 1592: sub removeuserfile {
 1593:     my ($docuname,$docudom,$fname)=@_;
 1594:     my $home=&homeserver($docuname,$docudom);
 1595:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 1596: }
 1597: 
 1598: sub mkdiruserfile {
 1599:     my ($docuname,$docudom,$dir)=@_;
 1600:     my $home=&homeserver($docuname,$docudom);
 1601:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 1602: }
 1603: 
 1604: sub renameuserfile {
 1605:     my ($docuname,$docudom,$old,$new)=@_;
 1606:     my $home=&homeserver($docuname,$docudom);
 1607:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
 1608: 		  &escape("$new"),$home);
 1609: }
 1610: 
 1611: # ------------------------------------------------------------------------- Log
 1612: 
 1613: sub log {
 1614:     my ($dom,$nam,$hom,$what)=@_;
 1615:     return critical("log:$dom:$nam:$what",$hom);
 1616: }
 1617: 
 1618: # ------------------------------------------------------------------ Course Log
 1619: #
 1620: # This routine flushes several buffers of non-mission-critical nature
 1621: #
 1622: 
 1623: sub flushcourselogs {
 1624:     &logthis('Flushing log buffers');
 1625: #
 1626: # course logs
 1627: # This is a log of all transactions in a course, which can be used
 1628: # for data mining purposes
 1629: #
 1630: # It also collects the courseid database, which lists last transaction
 1631: # times and course titles for all courseids
 1632: #
 1633:     my %courseidbuffer=();
 1634:     foreach (keys %courselogs) {
 1635:         my $crsid=$_;
 1636:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 1637: 		          &escape($courselogs{$crsid}),
 1638: 		          $coursehombuf{$crsid}) eq 'ok') {
 1639: 	    delete $courselogs{$crsid};
 1640:         } else {
 1641:             &logthis('Failed to flush log buffer for '.$crsid);
 1642:             if (length($courselogs{$crsid})>40000) {
 1643:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 1644:                         " exceeded maximum size, deleting.</font>");
 1645:                delete $courselogs{$crsid};
 1646:             }
 1647:         }
 1648:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
 1649:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
 1650: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1651:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid});
 1652:         } else {
 1653:            $courseidbuffer{$coursehombuf{$crsid}}=
 1654: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1655:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid});
 1656:         }
 1657:     }
 1658: #
 1659: # Write course id database (reverse lookup) to homeserver of courses 
 1660: # Is used in pickcourse
 1661: #
 1662:     foreach (keys %courseidbuffer) {
 1663:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
 1664:     }
 1665: #
 1666: # File accesses
 1667: # Writes to the dynamic metadata of resources to get hit counts, etc.
 1668: #
 1669:     foreach my $entry (keys(%accesshash)) {
 1670:         if ($entry =~ /___count$/) {
 1671:             my ($dom,$name);
 1672:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
 1673:             if (! defined($dom) || $dom eq '' || 
 1674:                 ! defined($name) || $name eq '') {
 1675:                 my $cid = $env{'request.course.id'};
 1676:                 $dom  = $env{'request.'.$cid.'.domain'};
 1677:                 $name = $env{'request.'.$cid.'.num'};
 1678:             }
 1679:             my $value = $accesshash{$entry};
 1680:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 1681:             my %temphash=($url => $value);
 1682:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 1683:             if ($result eq 'ok') {
 1684:                 delete $accesshash{$entry};
 1685:             } elsif ($result eq 'unknown_cmd') {
 1686:                 # Target server has old code running on it.
 1687:                 my %temphash=($entry => $value);
 1688:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1689:                     delete $accesshash{$entry};
 1690:                 }
 1691:             }
 1692:         } else {
 1693:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
 1694:             my %temphash=($entry => $accesshash{$entry});
 1695:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1696:                 delete $accesshash{$entry};
 1697:             }
 1698:         }
 1699:     }
 1700: #
 1701: # Roles
 1702: # Reverse lookup of user roles for course faculty/staff and co-authorship
 1703: #
 1704:     foreach (keys %userrolehash) {
 1705:         my $entry=$_;
 1706:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 1707: 	    split(/\:/,$entry);
 1708:         if (&Apache::lonnet::put('nohist_userroles',
 1709:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 1710:                 $rudom,$runame) eq 'ok') {
 1711: 	    delete $userrolehash{$entry};
 1712:         }
 1713:     }
 1714: #
 1715: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 1716: #
 1717:     my %domrolebuffer = ();
 1718:     foreach my $entry (keys %domainrolehash) {
 1719:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
 1720:         if ($domrolebuffer{$rudom}) {
 1721:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 1722:                       '='.&escape($domainrolehash{$entry});
 1723:         } else {
 1724:             $domrolebuffer{$rudom}.=&escape($entry).
 1725:                       '='.&escape($domainrolehash{$entry});
 1726:         }
 1727:         delete $domainrolehash{$entry};
 1728:     }
 1729:     foreach my $dom (keys(%domrolebuffer)) {
 1730:         foreach my $tryserver (keys %libserv) {
 1731:             if ($hostdom{$tryserver} eq $dom) {
 1732:                 unless (&reply('domroleput:'.$dom.':'.
 1733:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 1734:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 1735:                 }
 1736:             }
 1737:         }
 1738:     }
 1739:     $dumpcount++;
 1740: }
 1741: 
 1742: sub courselog {
 1743:     my $what=shift;
 1744:     $what=time.':'.$what;
 1745:     unless ($env{'request.course.id'}) { return ''; }
 1746:     $coursedombuf{$env{'request.course.id'}}=
 1747:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 1748:     $coursenumbuf{$env{'request.course.id'}}=
 1749:        $env{'course.'.$env{'request.course.id'}.'.num'};
 1750:     $coursehombuf{$env{'request.course.id'}}=
 1751:        $env{'course.'.$env{'request.course.id'}.'.home'};
 1752:     $coursedescrbuf{$env{'request.course.id'}}=
 1753:        $env{'course.'.$env{'request.course.id'}.'.description'};
 1754:     $courseinstcodebuf{$env{'request.course.id'}}=
 1755:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 1756:     $courseownerbuf{$env{'request.course.id'}}=
 1757:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 1758:     if (defined $courselogs{$env{'request.course.id'}}) {
 1759: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 1760:     } else {
 1761: 	$courselogs{$env{'request.course.id'}}.=$what;
 1762:     }
 1763:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 1764: 	&flushcourselogs();
 1765:     }
 1766: }
 1767: 
 1768: sub courseacclog {
 1769:     my $fnsymb=shift;
 1770:     unless ($env{'request.course.id'}) { return ''; }
 1771:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 1772:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 1773:         $what.=':POST';
 1774:         # FIXME: Probably ought to escape things....
 1775: 	foreach (keys %env) {
 1776:             if ($_=~/^form\.(.*)/) {
 1777: 		$what.=':'.$1.'='.$env{$_};
 1778:             }
 1779:         }
 1780:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 1781:         # FIXME: We should not be depending on a form parameter that someone
 1782:         # editing lonsearchcat.pm might change in the future.
 1783:         if ($env{'form.phase'} eq 'course_search') {
 1784:             $what.= ':POST';
 1785:             # FIXME: Probably ought to escape things....
 1786:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 1787:                                  'crsdiscuss') {
 1788:                 $what.=':'.$element.'='.$env{'form.'.$element};
 1789:             }
 1790:         }
 1791:     }
 1792:     &courselog($what);
 1793: }
 1794: 
 1795: sub countacc {
 1796:     my $url=&declutter(shift);
 1797:     return if (! defined($url) || $url eq '');
 1798:     unless ($env{'request.course.id'}) { return ''; }
 1799:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 1800:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 1801:     $accesshash{$key}++;
 1802: }
 1803: 
 1804: sub linklog {
 1805:     my ($from,$to)=@_;
 1806:     $from=&declutter($from);
 1807:     $to=&declutter($to);
 1808:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 1809:     $accesshash{$to.'___'.$from.'___goto'}=1;
 1810: }
 1811:   
 1812: sub userrolelog {
 1813:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 1814:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 1815:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 1816:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 1817:         ($trole=~/^ta/)) {
 1818:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 1819:        $userrolehash
 1820:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 1821:                     =$tend.':'.$tstart;
 1822:     }
 1823:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 1824:         ($trole=~/^li/) || ($trole=~/^li/) ||
 1825:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 1826:         ($trole=~/^sc/)) {
 1827:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 1828:        $domainrolehash
 1829:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 1830:                     = $tend.':'.$tstart;
 1831:     }
 1832: }
 1833: 
 1834: sub get_course_adv_roles {
 1835:     my $cid=shift;
 1836:     $cid=$env{'request.course.id'} unless (defined($cid));
 1837:     my %coursehash=&coursedescription($cid);
 1838:     my %nothide=();
 1839:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 1840: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
 1841:     }
 1842:     my %returnhash=();
 1843:     my %dumphash=
 1844:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 1845:     my $now=time;
 1846:     foreach (keys %dumphash) {
 1847: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
 1848:         if (($tstart) && ($tstart<0)) { next; }
 1849:         if (($tend) && ($tend<$now)) { next; }
 1850:         if (($tstart) && ($now<$tstart)) { next; }
 1851:         my ($role,$username,$domain,$section)=split(/\:/,$_);
 1852: 	if ($username eq '' || $domain eq '') { next; }
 1853: 	if ((&privileged($username,$domain)) && 
 1854: 	    (!$nothide{$username.':'.$domain})) { next; }
 1855: 	if ($role eq 'cr') { next; }
 1856:         my $key=&plaintext($role);
 1857: 	if ($role =~ /^cr/) {
 1858: 	    $key=(split('/',$role))[3];
 1859: 	}
 1860:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 1861:         if ($returnhash{$key}) {
 1862: 	    $returnhash{$key}.=','.$username.':'.$domain;
 1863:         } else {
 1864:             $returnhash{$key}=$username.':'.$domain;
 1865:         }
 1866:      }
 1867:     return %returnhash;
 1868: }
 1869: 
 1870: sub get_my_roles {
 1871:     my ($uname,$udom)=@_;
 1872:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 1873:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 1874:     my %dumphash=
 1875:             &dump('nohist_userroles',$udom,$uname);
 1876:     my %returnhash=();
 1877:     my $now=time;
 1878:     foreach (keys %dumphash) {
 1879: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
 1880:         if (($tstart) && ($tstart<0)) { next; }
 1881:         if (($tend) && ($tend<$now)) { next; }
 1882:         if (($tstart) && ($now<$tstart)) { next; }
 1883:         my ($role,$username,$domain,$section)=split(/\:/,$_);
 1884: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 1885:      }
 1886:     return %returnhash;
 1887: }
 1888: 
 1889: # ----------------------------------------------------- Frontpage Announcements
 1890: #
 1891: #
 1892: 
 1893: sub postannounce {
 1894:     my ($server,$text)=@_;
 1895:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
 1896:     unless ($text=~/\w/) { $text=''; }
 1897:     return &reply('setannounce:'.&escape($text),$server);
 1898: }
 1899: 
 1900: sub getannounce {
 1901: 
 1902:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 1903: 	my $announcement='';
 1904: 	while (<$fh>) { $announcement .=$_; }
 1905: 	close($fh);
 1906: 	if ($announcement=~/\w/) { 
 1907: 	    return 
 1908:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 1909:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 1910: 	} else {
 1911: 	    return '';
 1912: 	}
 1913:     } else {
 1914: 	return '';
 1915:     }
 1916: }
 1917: 
 1918: # ---------------------------------------------------------- Course ID routines
 1919: # Deal with domain's nohist_courseid.db files
 1920: #
 1921: 
 1922: sub courseidput {
 1923:     my ($domain,$what,$coursehome)=@_;
 1924:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 1925: }
 1926: 
 1927: sub courseiddump {
 1928:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref)=@_;
 1929:     my %returnhash=();
 1930:     unless ($domfilter) { $domfilter=''; }
 1931:     foreach my $tryserver (keys %libserv) {
 1932:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
 1933: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
 1934: 	        foreach (
 1935:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
 1936: 			       $sincefilter.':'.&escape($descfilter).':'.
 1937:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter),
 1938:                                $tryserver))) {
 1939: 		    my ($key,$value)=split(/\=/,$_);
 1940:                     if (($key) && ($value)) {
 1941: 		        $returnhash{&unescape($key)}=$value;
 1942:                     }
 1943:                 }
 1944:             }
 1945:         }
 1946:     }
 1947:     return %returnhash;
 1948: }
 1949: 
 1950: # ---------------------------------------------------------- DC e-mail
 1951: 
 1952: sub dcmailput {
 1953:     my ($domain,$msgid,$message,$server)=@_;
 1954:     my $status = &Apache::lonnet::critical(
 1955:        'dcmailput:'.$domain.':'.&Apache::lonnet::escape($msgid).'='.
 1956:        &Apache::lonnet::escape($message),$server);
 1957:     return $status;
 1958: }
 1959: 
 1960: sub dcmaildump {
 1961:     my ($dom,$startdate,$enddate,$senders) = @_;
 1962:     my %returnhash=();
 1963:     if (exists($domain_primary{$dom})) {
 1964:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 1965:                                                          &escape($enddate).':';
 1966: 	my @esc_senders=map { &escape($_)} @$senders;
 1967: 	$cmd.=&escape(join('&',@esc_senders));
 1968: 	foreach (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
 1969:             my ($key,$value) = split(/\=/,$_);
 1970:             if (($key) && ($value)) {
 1971:                 $returnhash{&unescape($key)} = &unescape($value);
 1972:             }
 1973:         }
 1974:     }
 1975:     return %returnhash;
 1976: }
 1977: # ---------------------------------------------------------- Domain roles
 1978: 
 1979: sub get_domain_roles {
 1980:     my ($dom,$roles,$startdate,$enddate)=@_;
 1981:     if (undef($startdate) || $startdate eq '') {
 1982:         $startdate = '.';
 1983:     }
 1984:     if (undef($enddate) || $enddate eq '') {
 1985:         $enddate = '.';
 1986:     }
 1987:     my $rolelist = join(':',@{$roles});
 1988:     my %personnel = ();
 1989:     foreach my $tryserver (keys(%libserv)) {
 1990:         if ($hostdom{$tryserver} eq $dom) {
 1991:             %{$personnel{$tryserver}}=();
 1992:             foreach (
 1993:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
 1994:                    &escape($startdate).':'.&escape($enddate).':'.
 1995:                    &escape($rolelist), $tryserver))) {
 1996:                 my($key,$value) = split(/\=/,$_);
 1997:                 if (($key) && ($value)) {
 1998:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
 1999:                 }
 2000:             }
 2001:         }
 2002:     }
 2003:     return %personnel;
 2004: }
 2005: 
 2006: # ----------------------------------------------------------- Check out an item
 2007: 
 2008: sub get_first_access {
 2009:     my ($type,$argsymb)=@_;
 2010:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
 2011:     if ($argsymb) { $symb=$argsymb; }
 2012:     my ($map,$id,$res)=&decode_symb($symb);
 2013:     if ($type eq 'map') {
 2014: 	$res=&symbread($map);
 2015:     } else {
 2016: 	$res=$symb;
 2017:     }
 2018:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2019:     return $times{"$courseid\0$res"};
 2020: }
 2021: 
 2022: sub set_first_access {
 2023:     my ($type)=@_;
 2024:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
 2025:     my ($map,$id,$res)=&decode_symb($symb);
 2026:     if ($type eq 'map') {
 2027: 	$res=&symbread($map);
 2028:     } else {
 2029: 	$res=$symb;
 2030:     }
 2031:     my $firstaccess=&get_first_access($type,$symb);
 2032:     if (!$firstaccess) {
 2033: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2034:     }
 2035:     return 'already_set';
 2036: }
 2037: 
 2038: sub checkout {
 2039:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2040:     my $now=time;
 2041:     my $lonhost=$perlvar{'lonHostID'};
 2042:     my $infostr=&escape(
 2043:                  'CHECKOUTTOKEN&'.
 2044:                  $tuname.'&'.
 2045:                  $tudom.'&'.
 2046:                  $tcrsid.'&'.
 2047:                  $symb.'&'.
 2048: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2049:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2050:     if ($token=~/^error\:/) { 
 2051:         &logthis("<font color=\"blue\">WARNING: ".
 2052:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2053:                  "</font>");
 2054:         return ''; 
 2055:     }
 2056: 
 2057:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2058:     $token=~tr/a-z/A-Z/;
 2059: 
 2060:     my %infohash=('resource.0.outtoken' => $token,
 2061:                   'resource.0.checkouttime' => $now,
 2062:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2063: 
 2064:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2065:        return '';
 2066:     } else {
 2067:         &logthis("<font color=\"blue\">WARNING: ".
 2068:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2069:                  "</font>");
 2070:     }    
 2071: 
 2072:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2073:                          &escape('Checkout '.$infostr.' - '.
 2074:                                                  $token)) ne 'ok') {
 2075: 	return '';
 2076:     } else {
 2077:         &logthis("<font color=\"blue\">WARNING: ".
 2078:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2079:                  "</font>");
 2080:     }
 2081:     return $token;
 2082: }
 2083: 
 2084: # ------------------------------------------------------------ Check in an item
 2085: 
 2086: sub checkin {
 2087:     my $token=shift;
 2088:     my $now=time;
 2089:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 2090:     $lonhost=~tr/A-Z/a-z/;
 2091:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
 2092:     $dtoken=~s/\W/\_/g;
 2093:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 2094:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 2095: 
 2096:     unless (($tuname) && ($tudom)) {
 2097:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2098:         return '';
 2099:     }
 2100:     
 2101:     unless (&allowed('mgr',$tcrsid)) {
 2102:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2103:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2104:         return '';
 2105:     }
 2106: 
 2107:     my %infohash=('resource.0.intoken' => $token,
 2108:                   'resource.0.checkintime' => $now,
 2109:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2110: 
 2111:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2112:        return '';
 2113:     }    
 2114: 
 2115:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2116:                          &escape('Checkin - '.$token)) ne 'ok') {
 2117: 	return '';
 2118:     }
 2119: 
 2120:     return ($symb,$tuname,$tudom,$tcrsid);    
 2121: }
 2122: 
 2123: # --------------------------------------------- Set Expire Date for Spreadsheet
 2124: 
 2125: sub expirespread {
 2126:     my ($uname,$udom,$stype,$usymb)=@_;
 2127:     my $cid=$env{'request.course.id'}; 
 2128:     if ($cid) {
 2129:        my $now=time;
 2130:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2131:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2132:                             $env{'course.'.$cid.'.num'}.
 2133: 	        	    ':nohist_expirationdates:'.
 2134:                             &escape($key).'='.$now,
 2135:                             $env{'course.'.$cid.'.home'})
 2136:     }
 2137:     return 'ok';
 2138: }
 2139: 
 2140: # ----------------------------------------------------- Devalidate Spreadsheets
 2141: 
 2142: sub devalidate {
 2143:     my ($symb,$uname,$udom)=@_;
 2144:     my $cid=$env{'request.course.id'}; 
 2145:     if ($cid) {
 2146:         # delete the stored spreadsheets for
 2147:         # - the student level sheet of this user in course's homespace
 2148:         # - the assessment level sheet for this resource 
 2149:         #   for this user in user's homespace
 2150: 	# - current conditional state info
 2151: 	my $key=$uname.':'.$udom.':';
 2152:         my $status=
 2153: 	    &del('nohist_calculatedsheets',
 2154: 		 [$key.'studentcalc:'],
 2155: 		 $env{'course.'.$cid.'.domain'},
 2156: 		 $env{'course.'.$cid.'.num'})
 2157: 		.' '.
 2158: 	    &del('nohist_calculatedsheets_'.$cid,
 2159: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2160:         unless ($status eq 'ok ok') {
 2161:            &logthis('Could not devalidate spreadsheet '.
 2162:                     $uname.' at '.$udom.' for '.
 2163: 		    $symb.': '.$status);
 2164:         }
 2165: 	&delenv('user.state.'.$cid);
 2166:     }
 2167: }
 2168: 
 2169: sub get_scalar {
 2170:     my ($string,$end) = @_;
 2171:     my $value;
 2172:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2173: 	$value = $1;
 2174:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2175: 	$value = $1;
 2176:     }
 2177:     return &unescape($value);
 2178: }
 2179: 
 2180: sub array2str {
 2181:   my (@array) = @_;
 2182:   my $result=&arrayref2str(\@array);
 2183:   $result=~s/^__ARRAY_REF__//;
 2184:   $result=~s/__END_ARRAY_REF__$//;
 2185:   return $result;
 2186: }
 2187: 
 2188: sub arrayref2str {
 2189:   my ($arrayref) = @_;
 2190:   my $result='__ARRAY_REF__';
 2191:   foreach my $elem (@$arrayref) {
 2192:     if(ref($elem) eq 'ARRAY') {
 2193:       $result.=&arrayref2str($elem).'&';
 2194:     } elsif(ref($elem) eq 'HASH') {
 2195:       $result.=&hashref2str($elem).'&';
 2196:     } elsif(ref($elem)) {
 2197:       #print("Got a ref of ".(ref($elem))." skipping.");
 2198:     } else {
 2199:       $result.=&escape($elem).'&';
 2200:     }
 2201:   }
 2202:   $result=~s/\&$//;
 2203:   $result .= '__END_ARRAY_REF__';
 2204:   return $result;
 2205: }
 2206: 
 2207: sub hash2str {
 2208:   my (%hash) = @_;
 2209:   my $result=&hashref2str(\%hash);
 2210:   $result=~s/^__HASH_REF__//;
 2211:   $result=~s/__END_HASH_REF__$//;
 2212:   return $result;
 2213: }
 2214: 
 2215: sub hashref2str {
 2216:   my ($hashref)=@_;
 2217:   my $result='__HASH_REF__';
 2218:   foreach (sort(keys(%$hashref))) {
 2219:     if (ref($_) eq 'ARRAY') {
 2220:       $result.=&arrayref2str($_).'=';
 2221:     } elsif (ref($_) eq 'HASH') {
 2222:       $result.=&hashref2str($_).'=';
 2223:     } elsif (ref($_)) {
 2224:       $result.='=';
 2225:       #print("Got a ref of ".(ref($_))." skipping.");
 2226:     } else {
 2227: 	if ($_) {$result.=&escape($_).'=';} else { last; }
 2228:     }
 2229: 
 2230:     if(ref($hashref->{$_}) eq 'ARRAY') {
 2231:       $result.=&arrayref2str($hashref->{$_}).'&';
 2232:     } elsif(ref($hashref->{$_}) eq 'HASH') {
 2233:       $result.=&hashref2str($hashref->{$_}).'&';
 2234:     } elsif(ref($hashref->{$_})) {
 2235:        $result.='&';
 2236:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
 2237:     } else {
 2238:       $result.=&escape($hashref->{$_}).'&';
 2239:     }
 2240:   }
 2241:   $result=~s/\&$//;
 2242:   $result .= '__END_HASH_REF__';
 2243:   return $result;
 2244: }
 2245: 
 2246: sub str2hash {
 2247:     my ($string)=@_;
 2248:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 2249:     return %$hash;
 2250: }
 2251: 
 2252: sub str2hashref {
 2253:   my ($string) = @_;
 2254: 
 2255:   my %hash;
 2256: 
 2257:   if($string !~ /^__HASH_REF__/) {
 2258:       if (! ($string eq '' || !defined($string))) {
 2259: 	  $hash{'error'}='Not hash reference';
 2260:       }
 2261:       return (\%hash, $string);
 2262:   }
 2263: 
 2264:   $string =~ s/^__HASH_REF__//;
 2265: 
 2266:   while($string !~ /^__END_HASH_REF__/) {
 2267:       #key
 2268:       my $key='';
 2269:       if($string =~ /^__HASH_REF__/) {
 2270:           ($key, $string)=&str2hashref($string);
 2271:           if(defined($key->{'error'})) {
 2272:               $hash{'error'}='Bad data';
 2273:               return (\%hash, $string);
 2274:           }
 2275:       } elsif($string =~ /^__ARRAY_REF__/) {
 2276:           ($key, $string)=&str2arrayref($string);
 2277:           if($key->[0] eq 'Array reference error') {
 2278:               $hash{'error'}='Bad data';
 2279:               return (\%hash, $string);
 2280:           }
 2281:       } else {
 2282:           $string =~ s/^(.*?)=//;
 2283: 	  $key=&unescape($1);
 2284:       }
 2285:       $string =~ s/^=//;
 2286: 
 2287:       #value
 2288:       my $value='';
 2289:       if($string =~ /^__HASH_REF__/) {
 2290:           ($value, $string)=&str2hashref($string);
 2291:           if(defined($value->{'error'})) {
 2292:               $hash{'error'}='Bad data';
 2293:               return (\%hash, $string);
 2294:           }
 2295:       } elsif($string =~ /^__ARRAY_REF__/) {
 2296:           ($value, $string)=&str2arrayref($string);
 2297:           if($value->[0] eq 'Array reference error') {
 2298:               $hash{'error'}='Bad data';
 2299:               return (\%hash, $string);
 2300:           }
 2301:       } else {
 2302: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 2303:       }
 2304:       $string =~ s/^&//;
 2305: 
 2306:       $hash{$key}=$value;
 2307:   }
 2308: 
 2309:   $string =~ s/^__END_HASH_REF__//;
 2310: 
 2311:   return (\%hash, $string);
 2312: }
 2313: 
 2314: sub str2array {
 2315:     my ($string)=@_;
 2316:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 2317:     return @$array;
 2318: }
 2319: 
 2320: sub str2arrayref {
 2321:   my ($string) = @_;
 2322:   my @array;
 2323: 
 2324:   if($string !~ /^__ARRAY_REF__/) {
 2325:       if (! ($string eq '' || !defined($string))) {
 2326: 	  $array[0]='Array reference error';
 2327:       }
 2328:       return (\@array, $string);
 2329:   }
 2330: 
 2331:   $string =~ s/^__ARRAY_REF__//;
 2332: 
 2333:   while($string !~ /^__END_ARRAY_REF__/) {
 2334:       my $value='';
 2335:       if($string =~ /^__HASH_REF__/) {
 2336:           ($value, $string)=&str2hashref($string);
 2337:           if(defined($value->{'error'})) {
 2338:               $array[0] ='Array reference error';
 2339:               return (\@array, $string);
 2340:           }
 2341:       } elsif($string =~ /^__ARRAY_REF__/) {
 2342:           ($value, $string)=&str2arrayref($string);
 2343:           if($value->[0] eq 'Array reference error') {
 2344:               $array[0] ='Array reference error';
 2345:               return (\@array, $string);
 2346:           }
 2347:       } else {
 2348: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 2349:       }
 2350:       $string =~ s/^&//;
 2351: 
 2352:       push(@array, $value);
 2353:   }
 2354: 
 2355:   $string =~ s/^__END_ARRAY_REF__//;
 2356: 
 2357:   return (\@array, $string);
 2358: }
 2359: 
 2360: # -------------------------------------------------------------------Temp Store
 2361: 
 2362: sub tmpreset {
 2363:   my ($symb,$namespace,$domain,$stuname) = @_;
 2364:   if (!$symb) {
 2365:     $symb=&symbread();
 2366:     if (!$symb) { $symb= $env{'request.url'}; }
 2367:   }
 2368:   $symb=escape($symb);
 2369: 
 2370:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2371:   $namespace=~s/\//\_/g;
 2372:   $namespace=~s/\W//g;
 2373: 
 2374:   if (!$domain) { $domain=$env{'user.domain'}; }
 2375:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2376:   if ($domain eq 'public' && $stuname eq 'public') {
 2377:       $stuname=$ENV{'REMOTE_ADDR'};
 2378:   }
 2379:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2380:   my %hash;
 2381:   if (tie(%hash,'GDBM_File',
 2382: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2383: 	  &GDBM_WRCREAT(),0640)) {
 2384:     foreach my $key (keys %hash) {
 2385:       if ($key=~ /:$symb/) {
 2386: 	delete($hash{$key});
 2387:       }
 2388:     }
 2389:   }
 2390: }
 2391: 
 2392: sub tmpstore {
 2393:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2394: 
 2395:   if (!$symb) {
 2396:     $symb=&symbread();
 2397:     if (!$symb) { $symb= $env{'request.url'}; }
 2398:   }
 2399:   $symb=escape($symb);
 2400: 
 2401:   if (!$namespace) {
 2402:     # I don't think we would ever want to store this for a course.
 2403:     # it seems this will only be used if we don't have a course.
 2404:     #$namespace=$env{'request.course.id'};
 2405:     #if (!$namespace) {
 2406:       $namespace=$env{'request.state'};
 2407:     #}
 2408:   }
 2409:   $namespace=~s/\//\_/g;
 2410:   $namespace=~s/\W//g;
 2411:   if (!$domain) { $domain=$env{'user.domain'}; }
 2412:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2413:   if ($domain eq 'public' && $stuname eq 'public') {
 2414:       $stuname=$ENV{'REMOTE_ADDR'};
 2415:   }
 2416:   my $now=time;
 2417:   my %hash;
 2418:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2419:   if (tie(%hash,'GDBM_File',
 2420: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2421: 	  &GDBM_WRCREAT(),0640)) {
 2422:     $hash{"version:$symb"}++;
 2423:     my $version=$hash{"version:$symb"};
 2424:     my $allkeys=''; 
 2425:     foreach my $key (keys(%$storehash)) {
 2426:       $allkeys.=$key.':';
 2427:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 2428:     }
 2429:     $hash{"$version:$symb:timestamp"}=$now;
 2430:     $allkeys.='timestamp';
 2431:     $hash{"$version:keys:$symb"}=$allkeys;
 2432:     if (untie(%hash)) {
 2433:       return 'ok';
 2434:     } else {
 2435:       return "error:$!";
 2436:     }
 2437:   } else {
 2438:     return "error:$!";
 2439:   }
 2440: }
 2441: 
 2442: # -----------------------------------------------------------------Temp Restore
 2443: 
 2444: sub tmprestore {
 2445:   my ($symb,$namespace,$domain,$stuname) = @_;
 2446: 
 2447:   if (!$symb) {
 2448:     $symb=&symbread();
 2449:     if (!$symb) { $symb= $env{'request.url'}; }
 2450:   }
 2451:   $symb=escape($symb);
 2452: 
 2453:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2454: 
 2455:   if (!$domain) { $domain=$env{'user.domain'}; }
 2456:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2457:   if ($domain eq 'public' && $stuname eq 'public') {
 2458:       $stuname=$ENV{'REMOTE_ADDR'};
 2459:   }
 2460:   my %returnhash;
 2461:   $namespace=~s/\//\_/g;
 2462:   $namespace=~s/\W//g;
 2463:   my %hash;
 2464:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2465:   if (tie(%hash,'GDBM_File',
 2466: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2467: 	  &GDBM_READER(),0640)) {
 2468:     my $version=$hash{"version:$symb"};
 2469:     $returnhash{'version'}=$version;
 2470:     my $scope;
 2471:     for ($scope=1;$scope<=$version;$scope++) {
 2472:       my $vkeys=$hash{"$scope:keys:$symb"};
 2473:       my @keys=split(/:/,$vkeys);
 2474:       my $key;
 2475:       $returnhash{"$scope:keys"}=$vkeys;
 2476:       foreach $key (@keys) {
 2477: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2478: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2479:       }
 2480:     }
 2481:     if (!(untie(%hash))) {
 2482:       return "error:$!";
 2483:     }
 2484:   } else {
 2485:     return "error:$!";
 2486:   }
 2487:   return %returnhash;
 2488: }
 2489: 
 2490: # ----------------------------------------------------------------------- Store
 2491: 
 2492: sub store {
 2493:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2494:     my $home='';
 2495: 
 2496:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2497: 
 2498:     $symb=&symbclean($symb);
 2499:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2500: 
 2501:     if (!$domain) { $domain=$env{'user.domain'}; }
 2502:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2503: 
 2504:     &devalidate($symb,$stuname,$domain);
 2505: 
 2506:     $symb=escape($symb);
 2507:     if (!$namespace) { 
 2508:        unless ($namespace=$env{'request.course.id'}) { 
 2509:           return ''; 
 2510:        } 
 2511:     }
 2512:     if (!$home) { $home=$env{'user.home'}; }
 2513: 
 2514:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2515:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2516: 
 2517:     my $namevalue='';
 2518:     foreach (keys %$storehash) {
 2519:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 2520:     }
 2521:     $namevalue=~s/\&$//;
 2522:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 2523:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2524: }
 2525: 
 2526: # -------------------------------------------------------------- Critical Store
 2527: 
 2528: sub cstore {
 2529:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2530:     my $home='';
 2531: 
 2532:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2533: 
 2534:     $symb=&symbclean($symb);
 2535:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2536: 
 2537:     if (!$domain) { $domain=$env{'user.domain'}; }
 2538:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2539: 
 2540:     &devalidate($symb,$stuname,$domain);
 2541: 
 2542:     $symb=escape($symb);
 2543:     if (!$namespace) { 
 2544:        unless ($namespace=$env{'request.course.id'}) { 
 2545:           return ''; 
 2546:        } 
 2547:     }
 2548:     if (!$home) { $home=$env{'user.home'}; }
 2549: 
 2550:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2551:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2552: 
 2553:     my $namevalue='';
 2554:     foreach (keys %$storehash) {
 2555:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 2556:     }
 2557:     $namevalue=~s/\&$//;
 2558:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 2559:     return critical
 2560:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2561: }
 2562: 
 2563: # --------------------------------------------------------------------- Restore
 2564: 
 2565: sub restore {
 2566:     my ($symb,$namespace,$domain,$stuname) = @_;
 2567:     my $home='';
 2568: 
 2569:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2570: 
 2571:     if (!$symb) {
 2572:       unless ($symb=escape(&symbread())) { return ''; }
 2573:     } else {
 2574:       $symb=&escape(&symbclean($symb));
 2575:     }
 2576:     if (!$namespace) { 
 2577:        unless ($namespace=$env{'request.course.id'}) { 
 2578:           return ''; 
 2579:        } 
 2580:     }
 2581:     if (!$domain) { $domain=$env{'user.domain'}; }
 2582:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2583:     if (!$home) { $home=$env{'user.home'}; }
 2584:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 2585: 
 2586:     my %returnhash=();
 2587:     foreach (split(/\&/,$answer)) {
 2588: 	my ($name,$value)=split(/\=/,$_);
 2589:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 2590:     }
 2591:     my $version;
 2592:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 2593:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
 2594:           $returnhash{$_}=$returnhash{$version.':'.$_};
 2595:        }
 2596:     }
 2597:     return %returnhash;
 2598: }
 2599: 
 2600: # ---------------------------------------------------------- Course Description
 2601: 
 2602: sub coursedescription {
 2603:     my ($courseid,$args)=@_;
 2604:     $courseid=~s/^\///;
 2605:     $courseid=~s/\_/\//g;
 2606:     my ($cdomain,$cnum)=split(/\//,$courseid);
 2607:     my $chome=&homeserver($cnum,$cdomain);
 2608:     my $normalid=$cdomain.'_'.$cnum;
 2609:     # need to always cache even if we get errors otherwise we keep 
 2610:     # trying and trying and trying to get the course description.
 2611:     my %envhash=();
 2612:     my %returnhash=();
 2613:     
 2614:     my $expiretime=600;
 2615:     if ($env{'request.course.id'} eq $normalid) {
 2616: 	$expiretime=120;
 2617:     }
 2618: 
 2619:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 2620:     if (!$args->{'freshen_cache'}
 2621: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 2622: 	foreach my $key (keys(%env)) {
 2623: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 2624: 	    my ($setting) = $1;
 2625: 	    $returnhash{$setting} = $env{$key};
 2626: 	}
 2627: 	return %returnhash;
 2628:     }
 2629: 
 2630:     # get the data agin
 2631:     if (!$args->{'one_time'}) {
 2632: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 2633:     }
 2634:     if ($chome ne 'no_host') {
 2635:        %returnhash=&dump('environment',$cdomain,$cnum);
 2636:        if (!exists($returnhash{'con_lost'})) {
 2637:            $returnhash{'home'}= $chome;
 2638: 	   $returnhash{'domain'} = $cdomain;
 2639: 	   $returnhash{'num'} = $cnum;
 2640:            while (my ($name,$value) = each %returnhash) {
 2641:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 2642:            }
 2643:            $returnhash{'url'}=&clutter($returnhash{'url'});
 2644:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 2645: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 2646:            $envhash{'course.'.$normalid.'.home'}=$chome;
 2647:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 2648:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 2649:        }
 2650:     }
 2651:     if (!$args->{'one_time'}) {
 2652: 	&appenv(%envhash);
 2653:     }
 2654:     return %returnhash;
 2655: }
 2656: 
 2657: # -------------------------------------------------See if a user is privileged
 2658: 
 2659: sub privileged {
 2660:     my ($username,$domain)=@_;
 2661:     my $rolesdump=&reply("dump:$domain:$username:roles",
 2662: 			&homeserver($username,$domain));
 2663:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 2664:     my $now=time;
 2665:     if ($rolesdump ne '') {
 2666:         foreach (split(/&/,$rolesdump)) {
 2667: 	    if ($_!~/^rolesdef_/) {
 2668: 		my ($area,$role)=split(/=/,$_);
 2669: 		$area=~s/\_\w\w$//;
 2670: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 2671: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 2672: 		    my $active=1;
 2673: 		    if ($tend) {
 2674: 			if ($tend<$now) { $active=0; }
 2675: 		    }
 2676: 		    if ($tstart) {
 2677: 			if ($tstart>$now) { $active=0; }
 2678: 		    }
 2679: 		    if ($active) { return 1; }
 2680: 		}
 2681: 	    }
 2682: 	}
 2683:     }
 2684:     return 0;
 2685: }
 2686: 
 2687: # -------------------------------------------------------- Get user privileges
 2688: 
 2689: sub rolesinit {
 2690:     my ($domain,$username,$authhost)=@_;
 2691:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 2692:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 2693:     my %allroles=();
 2694:     my %allgroups=();   
 2695:     my $now=time;
 2696:     my $userroles="user.login.time=$now\n";
 2697:     my $group_privs;
 2698: 
 2699:     if ($rolesdump ne '') {
 2700:         foreach (split(/&/,$rolesdump)) {
 2701: 	  if ($_!~/^rolesdef_/) {
 2702:             my ($area,$role)=split(/=/,$_);
 2703: 	    $area=~s/\_\w\w$//;
 2704:             my ($trole,$tend,$tstart,$group_privs);
 2705: 	    if ($role=~/^cr/) { 
 2706: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
 2707: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
 2708: 		    ($tend,$tstart)=split('_',$trest);
 2709: 		} else {
 2710: 		    $trole=$role;
 2711: 		}
 2712:             } elsif ($role =~ m|^gr/|) {
 2713:                 ($trole,$tend,$tstart) = split(/_/,$role);
 2714:                 ($trole,$group_privs) = split(/\//,$trole);
 2715:                 $group_privs = &unescape($group_privs);
 2716: 	    } else {
 2717: 		($trole,$tend,$tstart)=split(/_/,$role);
 2718: 	    }
 2719:             $userroles.=&set_arearole($trole,$area,$tstart,$tend,$domain,$username);
 2720:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 2721:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 2722:             if (($area ne '') && ($trole ne '')) {
 2723: 		my $spec=$trole.'.'.$area;
 2724: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 2725: 		if ($trole =~ /^cr\//) {
 2726:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 2727:                 } elsif ($trole eq 'gr') {
 2728:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 2729: 		} else {
 2730:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 2731: 		}
 2732:             }
 2733:           }
 2734:         }
 2735:         my ($author,$adv) = &set_userprivs(\$userroles,\%allroles,\%allgroups);
 2736:         $userroles.='user.adv='.$adv."\n".
 2737: 	            'user.author='.$author."\n";
 2738:         $env{'user.adv'}=$adv;
 2739:     }
 2740:     return $userroles;  
 2741: }
 2742: 
 2743: sub set_arearole {
 2744:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 2745: # log the associated role with the area
 2746:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 2747:     return 'user.role.'.$trole.'.'.$area.'='.$tstart.'.'.$tend."\n";
 2748: }
 2749: 
 2750: sub custom_roleprivs {
 2751:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 2752:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 2753:     my $homsvr=homeserver($rauthor,$rdomain);
 2754:     if ($hostname{$homsvr} ne '') {
 2755:         my ($rdummy,$roledef)=
 2756:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 2757:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 2758:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 2759:             if (defined($syspriv)) {
 2760:                 $$allroles{'cm./'}.=':'.$syspriv;
 2761:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 2762:             }
 2763:             if ($tdomain ne '') {
 2764:                 if (defined($dompriv)) {
 2765:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 2766:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 2767:                 }
 2768:                 if (($trest ne '') && (defined($coursepriv))) {
 2769:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 2770:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 2771:                 }
 2772:             }
 2773:         }
 2774:     }
 2775: }
 2776: 
 2777: sub group_roleprivs {
 2778:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 2779:     my $access = 1;
 2780:     my $now = time;
 2781:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 2782:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 2783:     if ($access) {
 2784:         my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
 2785:         $$allgroups{$course}{$group} .=':'.$group_privs;
 2786:     }
 2787: }
 2788: 
 2789: sub standard_roleprivs {
 2790:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 2791:     if (defined($pr{$trole.':s'})) {
 2792:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 2793:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 2794:     }
 2795:     if ($tdomain ne '') {
 2796:         if (defined($pr{$trole.':d'})) {
 2797:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 2798:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 2799:         }
 2800:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 2801:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 2802:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 2803:         }
 2804:     }
 2805: }
 2806: 
 2807: sub set_userprivs {
 2808:     my ($userroles,$allroles,$allgroups) = @_; 
 2809:     my $author=0;
 2810:     my $adv=0;
 2811:     my %grouproles = ();
 2812:     if (keys(%{$allgroups}) > 0) {
 2813:         foreach my $role (keys %{$allroles}) {
 2814:             my ($trole,$area,$sec,$extendedarea);
 2815:             if ($role =~ m|^(\w+)\.(/\w+/\w+)(/?\w*)|) {
 2816:                 $trole = $1;
 2817:                 $area = $2;
 2818:                 $sec = $3;
 2819:                 $extendedarea = $area.$sec;
 2820:                 if (exists($$allgroups{$area})) {
 2821:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 2822:                         my $spec = $trole.'.'.$extendedarea;
 2823:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 2824:                                                 $$allgroups{$area}{$group};
 2825:                     }
 2826:                 }
 2827:             }
 2828:         }
 2829:     }
 2830:     foreach (keys(%grouproles)) {
 2831:         $$allroles{$_} = $grouproles{$_};
 2832:     }
 2833:     foreach (keys %{$allroles}) {
 2834:         my %thesepriv=();
 2835:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
 2836:         foreach (split(/:/,$$allroles{$_})) {
 2837:             if ($_ ne '') {
 2838:                 my ($privilege,$restrictions)=split(/&/,$_);
 2839:                 if ($restrictions eq '') {
 2840:                     $thesepriv{$privilege}='F';
 2841:                 } elsif ($thesepriv{$privilege} ne 'F') {
 2842:                     $thesepriv{$privilege}.=$restrictions;
 2843:                 }
 2844:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 2845:             }
 2846:         }
 2847:         my $thesestr='';
 2848:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
 2849:         $$userroles.='user.priv.'.$_.'='.$thesestr."\n";
 2850:     }
 2851:     return ($author,$adv);
 2852: }
 2853: 
 2854: # --------------------------------------------------------------- get interface
 2855: 
 2856: sub get {
 2857:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2858:    my $items='';
 2859:    foreach (@$storearr) {
 2860:        $items.=escape($_).'&';
 2861:    }
 2862:    $items=~s/\&$//;
 2863:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2864:    if (!$uname) { $uname=$env{'user.name'}; }
 2865:    my $uhome=&homeserver($uname,$udomain);
 2866: 
 2867:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 2868:    my @pairs=split(/\&/,$rep);
 2869:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2870:      return @pairs;
 2871:    }
 2872:    my %returnhash=();
 2873:    my $i=0;
 2874:    foreach (@$storearr) {
 2875:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
 2876:       $i++;
 2877:    }
 2878:    return %returnhash;
 2879: }
 2880: 
 2881: # --------------------------------------------------------------- del interface
 2882: 
 2883: sub del {
 2884:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2885:    my $items='';
 2886:    foreach (@$storearr) {
 2887:        $items.=escape($_).'&';
 2888:    }
 2889:    $items=~s/\&$//;
 2890:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2891:    if (!$uname) { $uname=$env{'user.name'}; }
 2892:    my $uhome=&homeserver($uname,$udomain);
 2893: 
 2894:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 2895: }
 2896: 
 2897: # -------------------------------------------------------------- dump interface
 2898: 
 2899: sub dump {
 2900:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 2901:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2902:    if (!$uname) { $uname=$env{'user.name'}; }
 2903:    my $uhome=&homeserver($uname,$udomain);
 2904:    if ($regexp) {
 2905:        $regexp=&escape($regexp);
 2906:    } else {
 2907:        $regexp='.';
 2908:    }
 2909:    my $rep=reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 2910:    my @pairs=split(/\&/,$rep);
 2911:    my %returnhash=();
 2912:    foreach (@pairs) {
 2913:       my ($key,$value)=split(/=/,$_,2);
 2914:       $returnhash{unescape($key)}=&thaw_unescape($value);
 2915:    }
 2916:    return %returnhash;
 2917: }
 2918: 
 2919: # --------------------------------------------------------- dumpstore interface
 2920: 
 2921: sub dumpstore {
 2922:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 2923:    return &dump($namespace,$udomain,$uname,$regexp,$range);
 2924: }
 2925: 
 2926: # -------------------------------------------------------------- keys interface
 2927: 
 2928: sub getkeys {
 2929:    my ($namespace,$udomain,$uname)=@_;
 2930:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2931:    if (!$uname) { $uname=$env{'user.name'}; }
 2932:    my $uhome=&homeserver($uname,$udomain);
 2933:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 2934:    my @keyarray=();
 2935:    foreach (split(/\&/,$rep)) {
 2936:       push (@keyarray,&unescape($_));
 2937:    }
 2938:    return @keyarray;
 2939: }
 2940: 
 2941: # --------------------------------------------------------------- currentdump
 2942: sub currentdump {
 2943:    my ($courseid,$sdom,$sname)=@_;
 2944:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 2945:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 2946:    $sname    = $env{'user.name'}         if (! defined($sname));
 2947:    my $uhome = &homeserver($sname,$sdom);
 2948:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 2949:    return if ($rep =~ /^(error:|no_such_host)/);
 2950:    #
 2951:    my %returnhash=();
 2952:    #
 2953:    if ($rep eq "unknown_cmd") { 
 2954:        # an old lond will not know currentdump
 2955:        # Do a dump and make it look like a currentdump
 2956:        my @tmp = &dump($courseid,$sdom,$sname,'.');
 2957:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 2958:        my %hash = @tmp;
 2959:        @tmp=();
 2960:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 2961:    } else {
 2962:        my @pairs=split(/\&/,$rep);
 2963:        foreach (@pairs) {
 2964:            my ($key,$value)=split(/=/,$_);
 2965:            my ($symb,$param) = split(/:/,$key);
 2966:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 2967:                                                         &thaw_unescape($value);
 2968:        }
 2969:    }
 2970:    return %returnhash;
 2971: }
 2972: 
 2973: sub convert_dump_to_currentdump{
 2974:     my %hash = %{shift()};
 2975:     my %returnhash;
 2976:     # Code ripped from lond, essentially.  The only difference
 2977:     # here is the unescaping done by lonnet::dump().  Conceivably
 2978:     # we might run in to problems with parameter names =~ /^v\./
 2979:     while (my ($key,$value) = each(%hash)) {
 2980:         my ($v,$symb,$param) = split(/:/,$key);
 2981:         next if ($v eq 'version' || $symb eq 'keys');
 2982:         next if (exists($returnhash{$symb}) &&
 2983:                  exists($returnhash{$symb}->{$param}) &&
 2984:                  $returnhash{$symb}->{'v.'.$param} > $v);
 2985:         $returnhash{$symb}->{$param}=$value;
 2986:         $returnhash{$symb}->{'v.'.$param}=$v;
 2987:     }
 2988:     #
 2989:     # Remove all of the keys in the hashes which keep track of
 2990:     # the version of the parameter.
 2991:     while (my ($symb,$param_hash) = each(%returnhash)) {
 2992:         # use a foreach because we are going to delete from the hash.
 2993:         foreach my $key (keys(%$param_hash)) {
 2994:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 2995:         }
 2996:     }
 2997:     return \%returnhash;
 2998: }
 2999: 
 3000: # ------------------------------------------------------ critical inc interface
 3001: 
 3002: sub cinc {
 3003:     return &inc(@_,'critical');
 3004: }
 3005: 
 3006: # --------------------------------------------------------------- inc interface
 3007: 
 3008: sub inc {
 3009:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3010:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3011:     if (!$uname) { $uname=$env{'user.name'}; }
 3012:     my $uhome=&homeserver($uname,$udomain);
 3013:     my $items='';
 3014:     if (! ref($store)) {
 3015:         # got a single value, so use that instead
 3016:         $items = &escape($store).'=&';
 3017:     } elsif (ref($store) eq 'SCALAR') {
 3018:         $items = &escape($$store).'=&';        
 3019:     } elsif (ref($store) eq 'ARRAY') {
 3020:         $items = join('=&',map {&escape($_);} @{$store});
 3021:     } elsif (ref($store) eq 'HASH') {
 3022:         while (my($key,$value) = each(%{$store})) {
 3023:             $items.= &escape($key).'='.&escape($value).'&';
 3024:         }
 3025:     }
 3026:     $items=~s/\&$//;
 3027:     if ($critical) {
 3028: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3029:     } else {
 3030: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3031:     }
 3032: }
 3033: 
 3034: # --------------------------------------------------------------- put interface
 3035: 
 3036: sub put {
 3037:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3038:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3039:    if (!$uname) { $uname=$env{'user.name'}; }
 3040:    my $uhome=&homeserver($uname,$udomain);
 3041:    my $items='';
 3042:    foreach (keys %$storehash) {
 3043:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 3044:    }
 3045:    $items=~s/\&$//;
 3046:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3047: }
 3048: 
 3049: # ------------------------------------------------------------ newput interface
 3050: 
 3051: sub newput {
 3052:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3053:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3054:    if (!$uname) { $uname=$env{'user.name'}; }
 3055:    my $uhome=&homeserver($uname,$udomain);
 3056:    my $items='';
 3057:    foreach my $key (keys(%$storehash)) {
 3058:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3059:    }
 3060:    $items=~s/\&$//;
 3061:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 3062: }
 3063: 
 3064: # ---------------------------------------------------------  putstore interface
 3065: 
 3066: sub putstore {
 3067:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3068:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3069:    if (!$uname) { $uname=$env{'user.name'}; }
 3070:    my $uhome=&homeserver($uname,$udomain);
 3071:    my $items='';
 3072:    foreach my $key (keys(%$storehash)) {
 3073:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 3074:    }
 3075:    $items=~s/\&$//;
 3076:    my $esc_symb=&escape($symb);
 3077:    my $esc_v=&escape($version);
 3078:    my $reply =
 3079:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 3080: 	      $uhome);
 3081:    if ($reply eq 'unknown_cmd') {
 3082:        # gfall back to way things use to be done
 3083:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 3084: 			    $uname);
 3085:    }
 3086:    return $reply;
 3087: }
 3088: 
 3089: sub old_putstore {
 3090:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3091:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3092:     if (!$uname) { $uname=$env{'user.name'}; }
 3093:     my $uhome=&homeserver($uname,$udomain);
 3094:     my %newstorehash;
 3095:     foreach (keys %$storehash) {
 3096: 	my $key = $version.':'.&escape($symb).':'.$_;
 3097: 	$newstorehash{$key} = $storehash->{$_};
 3098:     }
 3099:     my $items='';
 3100:     my %allitems = ();
 3101:     foreach (keys %newstorehash) {
 3102: 	if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 3103: 	    my $key = $1.':keys:'.$2;
 3104: 	    $allitems{$key} .= $3.':';
 3105: 	}
 3106: 	$items.=$_.'='.&freeze_escape($newstorehash{$_}).'&';
 3107:     }
 3108:     foreach (keys %allitems) {
 3109: 	$allitems{$_} =~ s/\:$//;
 3110: 	$items.= $_.'='.$allitems{$_}.'&';
 3111:     }
 3112:     $items=~s/\&$//;
 3113:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3114: }
 3115: 
 3116: # ------------------------------------------------------ critical put interface
 3117: 
 3118: sub cput {
 3119:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3120:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3121:    if (!$uname) { $uname=$env{'user.name'}; }
 3122:    my $uhome=&homeserver($uname,$udomain);
 3123:    my $items='';
 3124:    foreach (keys %$storehash) {
 3125:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 3126:    }
 3127:    $items=~s/\&$//;
 3128:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 3129: }
 3130: 
 3131: # -------------------------------------------------------------- eget interface
 3132: 
 3133: sub eget {
 3134:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3135:    my $items='';
 3136:    foreach (@$storearr) {
 3137:        $items.=escape($_).'&';
 3138:    }
 3139:    $items=~s/\&$//;
 3140:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3141:    if (!$uname) { $uname=$env{'user.name'}; }
 3142:    my $uhome=&homeserver($uname,$udomain);
 3143:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 3144:    my @pairs=split(/\&/,$rep);
 3145:    my %returnhash=();
 3146:    my $i=0;
 3147:    foreach (@$storearr) {
 3148:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
 3149:       $i++;
 3150:    }
 3151:    return %returnhash;
 3152: }
 3153: 
 3154: # ------------------------------------------------------------ tmpput interface
 3155: sub tmpput {
 3156:     my ($storehash,$server)=@_;
 3157:     my $items='';
 3158:     foreach (keys(%$storehash)) {
 3159: 	$items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 3160:     }
 3161:     $items=~s/\&$//;
 3162:     return &reply("tmpput:$items",$server);
 3163: }
 3164: 
 3165: # ------------------------------------------------------------ tmpget interface
 3166: sub tmpget {
 3167:     my ($token,$server)=@_;
 3168:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3169:     my $rep=&reply("tmpget:$token",$server);
 3170:     my %returnhash;
 3171:     foreach my $item (split(/\&/,$rep)) {
 3172: 	my ($key,$value)=split(/=/,$item);
 3173: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 3174:     }
 3175:     return %returnhash;
 3176: }
 3177: 
 3178: # ------------------------------------------------------------ tmpget interface
 3179: sub tmpdel {
 3180:     my ($token,$server)=@_;
 3181:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3182:     return &reply("tmpdel:$token",$server);
 3183: }
 3184: 
 3185: # ---------------------------------------------- Custom access rule evaluation
 3186: 
 3187: sub customaccess {
 3188:     my ($priv,$uri)=@_;
 3189:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
 3190:     $urealm=~s/^\W//;
 3191:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
 3192:     my $access=0;
 3193:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 3194: 	my ($effect,$realm,$role)=split(/\:/,$_);
 3195:         if ($role) {
 3196: 	   if ($role ne $urole) { next; }
 3197:         }
 3198:         foreach (split(/\s*\,\s*/,$realm)) {
 3199:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
 3200:             if ($tdom) {
 3201: 		if ($tdom ne $udom) { next; }
 3202:             }
 3203:             if ($tcrs) {
 3204: 		if ($tcrs ne $ucrs) { next; }
 3205:             }
 3206:             if ($tsec) {
 3207: 		if ($tsec ne $usec) { next; }
 3208:             }
 3209:             $access=($effect eq 'allow');
 3210:             last;
 3211:         }
 3212: 	if ($realm eq '' && $role eq '') {
 3213:             $access=($effect eq 'allow');
 3214: 	}
 3215:     }
 3216:     return $access;
 3217: }
 3218: 
 3219: # ------------------------------------------------- Check for a user privilege
 3220: 
 3221: sub allowed {
 3222:     my ($priv,$uri,$symb)=@_;
 3223:     my $ver_orguri=$uri;
 3224:     $uri=&deversion($uri);
 3225:     my $orguri=$uri;
 3226:     $uri=&declutter($uri);
 3227:     
 3228:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 3229: # Free bre access to adm and meta resources
 3230:     if (((($uri=~/^adm\//) && ($uri !~ m|/bulletinboard$|)) 
 3231: 	 || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
 3232: 	return 'F';
 3233:     }
 3234: 
 3235: # Free bre access to user's own portfolio contents
 3236:     my ($space,$domain,$name,@dir)=split('/',$uri);
 3237:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 3238: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 3239:         return 'F';
 3240:     }
 3241: 
 3242: # bre access to group if user has rgf priv for this group and course.
 3243:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 3244:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 3245:         if (exists($env{'request.course.id'})) {
 3246:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3247:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3248:             if (($domain eq $cdom) && ($name eq $cnum)) {
 3249:                 my $courseprivid=$env{'request.course.id'};
 3250:                 $courseprivid=~s/\_/\//;
 3251:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 3252:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 3253:                     return $1; 
 3254:                 }
 3255:             }
 3256:         }
 3257:     }
 3258: 
 3259: # Free bre to public access
 3260: 
 3261:     if ($priv eq 'bre') {
 3262:         my $copyright=&metadata($uri,'copyright');
 3263: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 3264:            return 'F'; 
 3265:         }
 3266:         if ($copyright eq 'priv') {
 3267:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3268: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 3269: 		return '';
 3270:             }
 3271:         }
 3272:         if ($copyright eq 'domain') {
 3273:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3274: 	    unless (($env{'user.domain'} eq $1) ||
 3275:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 3276: 		return '';
 3277:             }
 3278:         }
 3279:         if ($env{'request.role'}=~ /li\.\//) {
 3280:             # Library role, so allow browsing of resources in this domain.
 3281:             return 'F';
 3282:         }
 3283:         if ($copyright eq 'custom') {
 3284: 	    unless (&customaccess($priv,$uri)) { return ''; }
 3285:         }
 3286:     }
 3287:     # Domain coordinator is trying to create a course
 3288:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 3289:         # uri is the requested domain in this case.
 3290:         # comparison to 'request.role.domain' shows if the user has selected
 3291:         # a role of dc for the domain in question.
 3292:         return 'F' if ($uri eq $env{'request.role.domain'});
 3293:     }
 3294: 
 3295:     my $thisallowed='';
 3296:     my $statecond=0;
 3297:     my $courseprivid='';
 3298: 
 3299: # Course
 3300: 
 3301:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 3302:        $thisallowed.=$1;
 3303:     }
 3304: 
 3305: # Domain
 3306: 
 3307:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 3308:        =~/\Q$priv\E\&([^\:]*)/) {
 3309:        $thisallowed.=$1;
 3310:     }
 3311: 
 3312: # Course: uri itself is a course
 3313:     my $courseuri=$uri;
 3314:     $courseuri=~s/\_(\d)/\/$1/;
 3315:     $courseuri=~s/^([^\/])/\/$1/;
 3316: 
 3317:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 3318:        =~/\Q$priv\E\&([^\:]*)/) {
 3319:        $thisallowed.=$1;
 3320:     }
 3321: 
 3322: # Group: uri itself is a group
 3323:     my $groupuri=$uri;
 3324:     $groupuri=~s/^([^\/])/\/$1/;
 3325:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$groupuri}
 3326:        =~/\Q$priv\E\&([^\:]*)/) {
 3327:        $thisallowed.=$1;
 3328:     }
 3329: 
 3330: # URI is an uploaded document for this course, default permissions don't matter
 3331: # not allowing 'edit' access (editupload) to uploaded course docs
 3332:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 3333: 	$thisallowed='';
 3334:         my ($match)=&is_on_map($uri);
 3335:         if ($match) {
 3336:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 3337:                   =~/\Q$priv\E\&([^\:]*)/) {
 3338:                 $thisallowed.=$1;
 3339:             }
 3340:         } else {
 3341:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 3342:             if ($refuri) {
 3343:                 if ($refuri =~ m|^/adm/|) {
 3344:                     $thisallowed='F';
 3345:                 } else {
 3346:                     $refuri=&declutter($refuri);
 3347:                     my ($match) = &is_on_map($refuri);
 3348:                     if ($match) {
 3349:                         $thisallowed='F';
 3350:                     }
 3351:                 }
 3352:             }
 3353:         }
 3354:     }
 3355: 
 3356: # Full access at system, domain or course-wide level? Exit.
 3357: 
 3358:     if ($thisallowed=~/F/) {
 3359: 	return 'F';
 3360:     }
 3361: 
 3362: # If this is generating or modifying users, exit with special codes
 3363: 
 3364:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 3365: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 3366: 	    my ($audom,$auname)=split('/',$uri);
 3367: # no author name given, so this just checks on the general right to make a co-author in this domain
 3368: 	    unless ($auname) { return $thisallowed; }
 3369: # an author name is given, so we are about to actually make a co-author for a certain account
 3370: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 3371: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 3372: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 3373: 	}
 3374: 	return $thisallowed;
 3375:     }
 3376: #
 3377: # Gathered so far: system, domain and course wide privileges
 3378: #
 3379: # Course: See if uri or referer is an individual resource that is part of 
 3380: # the course
 3381: 
 3382:     if ($env{'request.course.id'}) {
 3383: 
 3384:        $courseprivid=$env{'request.course.id'};
 3385:        if ($env{'request.course.sec'}) {
 3386:           $courseprivid.='/'.$env{'request.course.sec'};
 3387:        }
 3388:        $courseprivid=~s/\_/\//;
 3389:        my $checkreferer=1;
 3390:        my ($match,$cond)=&is_on_map($uri);
 3391:        if ($match) {
 3392:            $statecond=$cond;
 3393:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3394:                =~/\Q$priv\E\&([^\:]*)/) {
 3395:                $thisallowed.=$1;
 3396:                $checkreferer=0;
 3397:            }
 3398:        }
 3399:        
 3400:        if ($checkreferer) {
 3401: 	  my $refuri=$env{'httpref.'.$orguri};
 3402:             unless ($refuri) {
 3403:                 foreach (keys %env) {
 3404: 		    if ($_=~/^httpref\..*\*/) {
 3405: 			my $pattern=$_;
 3406:                         $pattern=~s/^httpref\.\/res\///;
 3407:                         $pattern=~s/\*/\[\^\/\]\+/g;
 3408:                         $pattern=~s/\//\\\//g;
 3409:                         if ($orguri=~/$pattern/) {
 3410: 			    $refuri=$env{$_};
 3411:                         }
 3412:                     }
 3413:                 }
 3414:             }
 3415: 
 3416:          if ($refuri) { 
 3417: 	  $refuri=&declutter($refuri);
 3418:           my ($match,$cond)=&is_on_map($refuri);
 3419:             if ($match) {
 3420:               my $refstatecond=$cond;
 3421:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3422:                   =~/\Q$priv\E\&([^\:]*)/) {
 3423:                   $thisallowed.=$1;
 3424:                   $uri=$refuri;
 3425:                   $statecond=$refstatecond;
 3426:               }
 3427:           }
 3428:         }
 3429:        }
 3430:    }
 3431: 
 3432: #
 3433: # Gathered now: all privileges that could apply, and condition number
 3434: # 
 3435: #
 3436: # Full or no access?
 3437: #
 3438: 
 3439:     if ($thisallowed=~/F/) {
 3440: 	return 'F';
 3441:     }
 3442: 
 3443:     unless ($thisallowed) {
 3444:         return '';
 3445:     }
 3446: 
 3447: # Restrictions exist, deal with them
 3448: #
 3449: #   C:according to course preferences
 3450: #   R:according to resource settings
 3451: #   L:unless locked
 3452: #   X:according to user session state
 3453: #
 3454: 
 3455: # Possibly locked functionality, check all courses
 3456: # Locks might take effect only after 10 minutes cache expiration for other
 3457: # courses, and 2 minutes for current course
 3458: 
 3459:     my $envkey;
 3460:     if ($thisallowed=~/L/) {
 3461:         foreach $envkey (keys %env) {
 3462:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 3463:                my $courseid=$2;
 3464:                my $roleid=$1.'.'.$2;
 3465:                $courseid=~s/^\///;
 3466:                my $expiretime=600;
 3467:                if ($env{'request.role'} eq $roleid) {
 3468: 		  $expiretime=120;
 3469:                }
 3470: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 3471:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 3472:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 3473: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 3474:                }
 3475:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3476:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 3477: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 3478:                        &log($env{'user.domain'},$env{'user.name'},
 3479:                             $env{'user.home'},
 3480:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 3481:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3482:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 3483: 		       return '';
 3484:                    }
 3485:                }
 3486:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3487:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 3488: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 3489:                        &log($env{'user.domain'},$env{'user.name'},
 3490:                             $env{'user.home'},
 3491:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 3492:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3493:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 3494: 		       return '';
 3495:                    }
 3496:                }
 3497: 	   }
 3498:        }
 3499:     }
 3500:    
 3501: #
 3502: # Rest of the restrictions depend on selected course
 3503: #
 3504: 
 3505:     unless ($env{'request.course.id'}) {
 3506:        return '1';
 3507:     }
 3508: 
 3509: #
 3510: # Now user is definitely in a course
 3511: #
 3512: 
 3513: 
 3514: # Course preferences
 3515: 
 3516:    if ($thisallowed=~/C/) {
 3517:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 3518:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 3519:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 3520: 	   =~/\Q$rolecode\E/) {
 3521: 	   if ($priv ne 'pch') { 
 3522: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 3523: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 3524: 			$env{'request.course.id'});
 3525: 	   }
 3526:            return '';
 3527:        }
 3528: 
 3529:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 3530: 	   =~/\Q$unamedom\E/) {
 3531: 	   if ($priv ne 'pch') { 
 3532: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 3533: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 3534: 			$env{'request.course.id'});
 3535: 	   }
 3536:            return '';
 3537:        }
 3538:    }
 3539: 
 3540: # Resource preferences
 3541: 
 3542:    if ($thisallowed=~/R/) {
 3543:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 3544:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 3545: 	   if ($priv ne 'pch') { 
 3546: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 3547: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 3548: 	   }
 3549: 	   return '';
 3550:        }
 3551:    }
 3552: 
 3553: # Restricted by state or randomout?
 3554: 
 3555:    if ($thisallowed=~/X/) {
 3556:       if ($env{'acc.randomout'}) {
 3557: 	 if (!$symb) { $symb=&symbread($uri,1); }
 3558:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 3559:             return ''; 
 3560:          }
 3561:       }
 3562:       if (&condval($statecond)) {
 3563: 	 return '2';
 3564:       } else {
 3565:          return '';
 3566:       }
 3567:    }
 3568: 
 3569:    return 'F';
 3570: }
 3571: 
 3572: sub split_uri_for_cond {
 3573:     my $uri=&deversion(&declutter(shift));
 3574:     my @uriparts=split(/\//,$uri);
 3575:     my $filename=pop(@uriparts);
 3576:     my $pathname=join('/',@uriparts);
 3577:     return ($pathname,$filename);
 3578: }
 3579: # --------------------------------------------------- Is a resource on the map?
 3580: 
 3581: sub is_on_map {
 3582:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 3583:     #Trying to find the conditional for the file
 3584:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 3585: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 3586:     if ($match) {
 3587: 	return (1,$1);
 3588:     } else {
 3589: 	return (0,0);
 3590:     }
 3591: }
 3592: 
 3593: # --------------------------------------------------------- Get symb from alias
 3594: 
 3595: sub get_symb_from_alias {
 3596:     my $symb=shift;
 3597:     my ($map,$resid,$url)=&decode_symb($symb);
 3598: # Already is a symb
 3599:     if ($url) { return $symb; }
 3600: # Must be an alias
 3601:     my $aliassymb='';
 3602:     my %bighash;
 3603:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 3604:                             &GDBM_READER(),0640)) {
 3605:         my $rid=$bighash{'mapalias_'.$symb};
 3606: 	if ($rid) {
 3607: 	    my ($mapid,$resid)=split(/\./,$rid);
 3608: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 3609: 				    $resid,$bighash{'src_'.$rid});
 3610: 	}
 3611:         untie %bighash;
 3612:     }
 3613:     return $aliassymb;
 3614: }
 3615: 
 3616: # ----------------------------------------------------------------- Define Role
 3617: 
 3618: sub definerole {
 3619:   if (allowed('mcr','/')) {
 3620:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 3621:     foreach (split(':',$sysrole)) {
 3622: 	my ($crole,$cqual)=split(/\&/,$_);
 3623:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 3624:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 3625: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 3626:                return "refused:s:$crole&$cqual"; 
 3627:             }
 3628:         }
 3629:     }
 3630:     foreach (split(':',$domrole)) {
 3631: 	my ($crole,$cqual)=split(/\&/,$_);
 3632:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 3633:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 3634: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 3635:                return "refused:d:$crole&$cqual"; 
 3636:             }
 3637:         }
 3638:     }
 3639:     foreach (split(':',$courole)) {
 3640: 	my ($crole,$cqual)=split(/\&/,$_);
 3641:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 3642:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 3643: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 3644:                return "refused:c:$crole&$cqual"; 
 3645:             }
 3646:         }
 3647:     }
 3648:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 3649:                 "$env{'user.domain'}:$env{'user.name'}:".
 3650: 	        "rolesdef_$rolename=".
 3651:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 3652:     return reply($command,$env{'user.home'});
 3653:   } else {
 3654:     return 'refused';
 3655:   }
 3656: }
 3657: 
 3658: # ---------------- Make a metadata query against the network of library servers
 3659: 
 3660: sub metadata_query {
 3661:     my ($query,$custom,$customshow,$server_array)=@_;
 3662:     my %rhash;
 3663:     my @server_list = (defined($server_array) ? @$server_array
 3664:                                               : keys(%libserv) );
 3665:     for my $server (@server_list) {
 3666: 	unless ($custom or $customshow) {
 3667: 	    my $reply=&reply("querysend:".&escape($query),$server);
 3668: 	    $rhash{$server}=$reply;
 3669: 	}
 3670: 	else {
 3671: 	    my $reply=&reply("querysend:".&escape($query).':'.
 3672: 			     &escape($custom).':'.&escape($customshow),
 3673: 			     $server);
 3674: 	    $rhash{$server}=$reply;
 3675: 	}
 3676:     }
 3677:     return \%rhash;
 3678: }
 3679: 
 3680: # ----------------------------------------- Send log queries and wait for reply
 3681: 
 3682: sub log_query {
 3683:     my ($uname,$udom,$query,%filters)=@_;
 3684:     my $uhome=&homeserver($uname,$udom);
 3685:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 3686:     my $uhost=$hostname{$uhome};
 3687:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
 3688:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 3689:                        $uhome);
 3690:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 3691:     return get_query_reply($queryid);
 3692: }
 3693: 
 3694: # ------- Request retrieval of institutional classlists for course(s)
 3695: 
 3696: sub fetch_enrollment_query {
 3697:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 3698:     my $homeserver;
 3699:     my $maxtries = 1;
 3700:     if ($context eq 'automated') {
 3701:         $homeserver = $perlvar{'lonHostID'};
 3702:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 3703:     } else {
 3704:         $homeserver = &homeserver($cnum,$dom);
 3705:     }
 3706:     my $host=$hostname{$homeserver};
 3707:     my $cmd = '';
 3708:     foreach (keys %{$affiliatesref}) {
 3709:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
 3710:     }
 3711:     $cmd =~ s/%%$//;
 3712:     $cmd = &escape($cmd);
 3713:     my $query = 'fetchenrollment';
 3714:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 3715:     unless ($queryid=~/^\Q$host\E\_/) { 
 3716:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 3717:         return 'error: '.$queryid;
 3718:     }
 3719:     my $reply = &get_query_reply($queryid);
 3720:     my $tries = 1;
 3721:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 3722:         $reply = &get_query_reply($queryid);
 3723:         $tries ++;
 3724:     }
 3725:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 3726:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 3727:     } else {
 3728:         my @responses = split/:/,$reply;
 3729:         if ($homeserver eq $perlvar{'lonHostID'}) {
 3730:             foreach (@responses) {
 3731:                 my ($key,$value) = split/=/,$_;
 3732:                 $$replyref{$key} = $value;
 3733:             }
 3734:         } else {
 3735:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 3736:             foreach (@responses) {
 3737:                 my ($key,$value) = split/=/,$_;
 3738:                 $$replyref{$key} = $value;
 3739:                 if ($value > 0) {
 3740:                     foreach (@{$$affiliatesref{$key}}) {
 3741:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
 3742:                         my $destname = $pathname.'/'.$filename;
 3743:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 3744:                         if ($xml_classlist =~ /^error/) {
 3745:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 3746:                         } else {
 3747:                             if ( open(FILE,">$destname") ) {
 3748:                                 print FILE &unescape($xml_classlist);
 3749:                                 close(FILE);
 3750:                             } else {
 3751:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 3752:                             }
 3753:                         }
 3754:                     }
 3755:                 }
 3756:             }
 3757:         }
 3758:         return 'ok';
 3759:     }
 3760:     return 'error';
 3761: }
 3762: 
 3763: sub get_query_reply {
 3764:     my $queryid=shift;
 3765:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 3766:     my $reply='';
 3767:     for (1..100) {
 3768: 	sleep 2;
 3769:         if (-e $replyfile.'.end') {
 3770: 	    if (open(my $fh,$replyfile)) {
 3771:                $reply.=<$fh>;
 3772:                close($fh);
 3773: 	   } else { return 'error: reply_file_error'; }
 3774:            return &unescape($reply);
 3775: 	}
 3776:     }
 3777:     return 'timeout:'.$queryid;
 3778: }
 3779: 
 3780: sub courselog_query {
 3781: #
 3782: # possible filters:
 3783: # url: url or symb
 3784: # username
 3785: # domain
 3786: # action: view, submit, grade
 3787: # start: timestamp
 3788: # end: timestamp
 3789: #
 3790:     my (%filters)=@_;
 3791:     unless ($env{'request.course.id'}) { return 'no_course'; }
 3792:     if ($filters{'url'}) {
 3793: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 3794:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 3795:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 3796:     }
 3797:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3798:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3799:     return &log_query($cname,$cdom,'courselog',%filters);
 3800: }
 3801: 
 3802: sub userlog_query {
 3803:     my ($uname,$udom,%filters)=@_;
 3804:     return &log_query($uname,$udom,'userlog',%filters);
 3805: }
 3806: 
 3807: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 3808: 
 3809: sub auto_run {
 3810:     my ($cnum,$cdom) = @_;
 3811:     my $homeserver = &homeserver($cnum,$cdom);
 3812:     my $response = &reply('autorun:'.$cdom,$homeserver);
 3813:     return $response;
 3814: }
 3815:                                                                                    
 3816: sub auto_get_sections {
 3817:     my ($cnum,$cdom,$inst_coursecode) = @_;
 3818:     my $homeserver = &homeserver($cnum,$cdom);
 3819:     my @secs = ();
 3820:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 3821:     unless ($response eq 'refused') {
 3822:         @secs = split/:/,$response;
 3823:     }
 3824:     return @secs;
 3825: }
 3826:                                                                                    
 3827: sub auto_new_course {
 3828:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 3829:     my $homeserver = &homeserver($cnum,$cdom);
 3830:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 3831:     return $response;
 3832: }
 3833:                                                                                    
 3834: sub auto_validate_courseID {
 3835:     my ($cnum,$cdom,$inst_course_id) = @_;
 3836:     my $homeserver = &homeserver($cnum,$cdom);
 3837:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 3838:     return $response;
 3839: }
 3840:                                                                                    
 3841: sub auto_create_password {
 3842:     my ($cnum,$cdom,$authparam) = @_;
 3843:     my $homeserver = &homeserver($cnum,$cdom); 
 3844:     my $create_passwd = 0;
 3845:     my $authchk = '';
 3846:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 3847:     if ($response eq 'refused') {
 3848:         $authchk = 'refused';
 3849:     } else {
 3850:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
 3851:     }
 3852:     return ($authparam,$create_passwd,$authchk);
 3853: }
 3854: 
 3855: sub auto_photo_permission {
 3856:     my ($cnum,$cdom,$students) = @_;
 3857:     my $homeserver = &homeserver($cnum,$cdom);
 3858:     my ($outcome,$perm_reqd,$conditions) = 
 3859: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 3860:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 3861: 	return (undef,undef);
 3862:     }
 3863:     return ($outcome,$perm_reqd,$conditions);
 3864: }
 3865: 
 3866: sub auto_checkphotos {
 3867:     my ($uname,$udom,$pid) = @_;
 3868:     my $homeserver = &homeserver($uname,$udom);
 3869:     my ($result,$resulttype);
 3870:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 3871: 				   &escape($uname).':'.&escape($pid),
 3872: 				   $homeserver));
 3873:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 3874: 	return (undef,undef);
 3875:     }
 3876:     if ($outcome) {
 3877:         ($result,$resulttype) = split(/:/,$outcome);
 3878:     } 
 3879:     return ($result,$resulttype);
 3880: }
 3881: 
 3882: sub auto_photochoice {
 3883:     my ($cnum,$cdom) = @_;
 3884:     my $homeserver = &homeserver($cnum,$cdom);
 3885:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 3886: 						       &escape($cdom),
 3887: 						       $homeserver)));
 3888:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 3889: 	return (undef,undef);
 3890:     }
 3891:     return ($update,$comment);
 3892: }
 3893: 
 3894: sub auto_photoupdate {
 3895:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 3896:     my $homeserver = &homeserver($cnum,$dom);
 3897:     my $host=$hostname{$homeserver};
 3898:     my $cmd = '';
 3899:     my $maxtries = 1;
 3900:     foreach (keys %{$affiliatesref}) {
 3901:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
 3902:     }
 3903:     $cmd =~ s/%%$//;
 3904:     $cmd = &escape($cmd);
 3905:     my $query = 'institutionalphotos';
 3906:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 3907:     unless ($queryid=~/^\Q$host\E\_/) {
 3908:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 3909:         return 'error: '.$queryid;
 3910:     }
 3911:     my $reply = &get_query_reply($queryid);
 3912:     my $tries = 1;
 3913:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 3914:         $reply = &get_query_reply($queryid);
 3915:         $tries ++;
 3916:     }
 3917:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 3918:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 3919:     } else {
 3920:         my @responses = split(/:/,$reply);
 3921:         my $outcome = shift(@responses); 
 3922:         foreach my $item (@responses) {
 3923:             my ($key,$value) = split(/=/,$item);
 3924:             $$photo{$key} = $value;
 3925:         }
 3926:         return $outcome;
 3927:     }
 3928:     return 'error';
 3929: }
 3930: 
 3931: sub auto_instcode_format {
 3932:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
 3933:     my $courses = '';
 3934:     my $homeserver;
 3935:     if ($caller eq 'global') {
 3936:         foreach my $tryserver (keys %libserv) {
 3937:             if ($hostdom{$tryserver} eq $codedom) {
 3938:                 $homeserver = $tryserver;
 3939:                 last;
 3940:             }
 3941:         }
 3942:         if (($env{'user.name'}) && ($env{'user.domain'} eq $codedom)) {
 3943:             $homeserver = &homeserver($env{'user.name'},$codedom);
 3944:         }
 3945:     } else {
 3946:         $homeserver = &homeserver($caller,$codedom);
 3947:     }
 3948:     foreach (keys %{$instcodes}) {
 3949:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
 3950:     }
 3951:     chop($courses);
 3952:     my $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$homeserver);
 3953:     unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 3954:         my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = split/:/,$response;
 3955:         %{$codes} = &str2hash($codes_str);
 3956:         @{$codetitles} = &str2array($codetitles_str);
 3957:         %{$cat_titles} = &str2hash($cat_titles_str);
 3958:         %{$cat_order} = &str2hash($cat_order_str);
 3959:         return 'ok';
 3960:     }
 3961:     return $response;
 3962: }
 3963: 
 3964: # ------------------------------------------------------- Course Group routines
 3965: 
 3966: sub get_coursegroups {
 3967:     my ($cdom,$cnum,$group) = @_;
 3968:     return(&dump('coursegroups',$cdom,$cnum,$group));
 3969: }
 3970: 
 3971: sub modify_coursegroup {
 3972:     my ($cdom,$cnum,$groupsettings) = @_;
 3973:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 3974: }
 3975: 
 3976: sub modify_group_roles {
 3977:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
 3978:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 3979:     my $role = 'gr/'.&escape($userprivs);
 3980:     my ($uname,$udom) = split(/:/,$user);
 3981:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
 3982:     if ($result eq 'ok') {
 3983:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 3984:     }
 3985: 
 3986:     return $result;
 3987: }
 3988: 
 3989: sub modify_coursegroup_membership {
 3990:     my ($cdom,$cnum,$membership) = @_;
 3991:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 3992:     return $result;
 3993: }
 3994: 
 3995: sub get_active_groups {
 3996:     my ($udom,$uname,$cdom,$cnum) = @_;
 3997:     my $now = time;
 3998:     my %groups = ();
 3999:     foreach my $key (keys(%env)) {
 4000:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
 4001:             my ($start,$end) = split(/\./,$env{$key});
 4002:             if (($end!=0) && ($end<$now)) { next; }
 4003:             if (($start!=0) && ($start>$now)) { next; }
 4004:             if ($1 eq $cdom && $2 eq $cnum) {
 4005:                 $groups{$3} = $env{$key} ;
 4006:             }
 4007:         }
 4008:     }
 4009:     return %groups;
 4010: }
 4011: 
 4012: sub get_group_membership {
 4013:     my ($cdom,$cnum,$group) = @_;
 4014:     return(&dump('groupmembership',$cdom,$cnum,$group));
 4015: }
 4016: 
 4017: sub get_users_groups {
 4018:     my ($udom,$uname,$courseid) = @_;
 4019:     my @usersgroups;
 4020:     my $cachetime=1800;
 4021:     $courseid=~s/\_/\//g;
 4022:     $courseid=~s/^(\w)/\/$1/;
 4023: 
 4024:     my $hashid="$udom:$uname:$courseid";
 4025:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 4026:     if (defined($cached)) {
 4027:         @usersgroups = split/:/,$grouplist;
 4028:     } else {  
 4029:         $grouplist = '';
 4030:         my %roleshash = &dump('roles',$udom,$uname,$courseid);
 4031:         my ($tmp) = keys(%roleshash);
 4032:         if ($tmp=~/^error:/) {
 4033:             &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
 4034:         } else {
 4035:             my $access_end = $env{'course.'.$courseid.
 4036:                                   '.default_enrollment_end_date'};
 4037:             my $now = time;
 4038:             foreach my $key (keys %roleshash) {
 4039:                 if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
 4040:                     my $group = $1;
 4041:                     if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 4042:                         my $start = $2;
 4043:                         my $end = $1;
 4044:                         if ($start == -1) { next; } # deleted from group
 4045:                         if (($start!=0) && ($start>$now)) { next; }
 4046:                         if (($end!=0) && ($end<$now)) {
 4047:                             if ($access_end && $access_end < $now) {
 4048:                                 if ($access_end - $end < 86400) {
 4049:                                     push(@usersgroups,$group);
 4050:                                 }
 4051:                             }
 4052:                             next;
 4053:                         }
 4054:                         push(@usersgroups,$group);
 4055:                     }
 4056:                 }
 4057:             }
 4058:             @usersgroups = &sort_course_groups($courseid,@usersgroups);
 4059:             $grouplist = join(':',@usersgroups);
 4060:             &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 4061:         }
 4062:     }
 4063:     return @usersgroups;
 4064: }
 4065: 
 4066: sub devalidate_getgroups_cache {
 4067:     my ($udom,$uname,$cdom,$cnum)=@_;
 4068:     my $courseid = $cdom.'_'.$cnum;
 4069:     $courseid=~s/\_/\//g;
 4070:     $courseid=~s/^(\w)/\/$1/;
 4071:     my $hashid="$udom:$uname:$courseid";
 4072:     &devalidate_cache_new('getgroups',$hashid);
 4073: }
 4074: 
 4075: # ------------------------------------------------------------------ Plain Text
 4076: 
 4077: sub plaintext {
 4078:     my $short=shift;
 4079:     return &Apache::lonlocal::mt($prp{$short});
 4080: }
 4081: 
 4082: # ----------------------------------------------------------------- Assign Role
 4083: 
 4084: sub assignrole {
 4085:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 4086:     my $mrole;
 4087:     if ($role =~ /^cr\//) {
 4088:         my $cwosec=$url;
 4089:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 4090: 	unless (&allowed('ccr',$cwosec)) {
 4091:            &logthis('Refused custom assignrole: '.
 4092:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4093: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4094:            return 'refused'; 
 4095:         }
 4096:         $mrole='cr';
 4097:     } elsif ($role =~ /^gr\//) {
 4098:         my $cwogrp=$url;
 4099:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 4100:         unless (&allowed('mdg',$cwogrp)) {
 4101:             &logthis('Refused group assignrole: '.
 4102:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4103:                     $env{'user.name'}.' at '.$env{'user.domain'});
 4104:             return 'refused';
 4105:         }
 4106:         $mrole='gr';
 4107:     } else {
 4108:         my $cwosec=$url;
 4109:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 4110:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
 4111:            &logthis('Refused assignrole: '.
 4112:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4113: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4114:            return 'refused'; 
 4115:         }
 4116:         $mrole=$role;
 4117:     }
 4118:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4119:                 "$udom:$uname:$url".'_'."$mrole=$role";
 4120:     if ($end) { $command.='_'.$end; }
 4121:     if ($start) {
 4122: 	if ($end) { 
 4123:            $command.='_'.$start; 
 4124:         } else {
 4125:            $command.='_0_'.$start;
 4126:         }
 4127:     }
 4128: # actually delete
 4129:     if ($deleteflag) {
 4130: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 4131: # modify command to delete the role
 4132:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 4133:                 "$udom:$uname:$url".'_'."$mrole";
 4134: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 4135: # set start and finish to negative values for userrolelog
 4136:            $start=-1;
 4137:            $end=-1;
 4138:         }
 4139:     }
 4140: # send command
 4141:     my $answer=&reply($command,&homeserver($uname,$udom));
 4142: # log new user role if status is ok
 4143:     if ($answer eq 'ok') {
 4144: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 4145:     }
 4146:     return $answer;
 4147: }
 4148: 
 4149: # -------------------------------------------------- Modify user authentication
 4150: # Overrides without validation
 4151: 
 4152: sub modifyuserauth {
 4153:     my ($udom,$uname,$umode,$upass)=@_;
 4154:     my $uhome=&homeserver($uname,$udom);
 4155:     unless (&allowed('mau',$udom)) { return 'refused'; }
 4156:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 4157:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4158:              ' in domain '.$env{'request.role.domain'});  
 4159:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 4160: 		     &escape($upass),$uhome);
 4161:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 4162:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 4163:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4164:     &log($udom,,$uname,$uhome,
 4165:         'Authentication changed by '.$env{'user.domain'}.', '.
 4166:                                      $env{'user.name'}.', '.$umode.
 4167:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4168:     unless ($reply eq 'ok') {
 4169:         &logthis('Authentication mode error: '.$reply);
 4170: 	return 'error: '.$reply;
 4171:     }   
 4172:     return 'ok';
 4173: }
 4174: 
 4175: # --------------------------------------------------------------- Modify a user
 4176: 
 4177: sub modifyuser {
 4178:     my ($udom,    $uname, $uid,
 4179:         $umode,   $upass, $first,
 4180:         $middle,  $last,  $gene,
 4181:         $forceid, $desiredhome, $email)=@_;
 4182:     $udom=~s/\W//g;
 4183:     $uname=~s/\W//g;
 4184:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 4185:              $umode.', '.$first.', '.$middle.', '.
 4186: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 4187:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 4188:                                      ' desiredhome not specified'). 
 4189:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4190:              ' in domain '.$env{'request.role.domain'});
 4191:     my $uhome=&homeserver($uname,$udom,'true');
 4192: # ----------------------------------------------------------------- Create User
 4193:     if (($uhome eq 'no_host') && 
 4194: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 4195:         my $unhome='';
 4196:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
 4197:             $unhome = $desiredhome;
 4198: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 4199: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 4200:         } else { # load balancing routine for determining $unhome
 4201:             my $tryserver;
 4202:             my $loadm=10000000;
 4203:             foreach $tryserver (keys %libserv) {
 4204: 	       if ($hostdom{$tryserver} eq $udom) {
 4205:                   my $answer=reply('load',$tryserver);
 4206:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
 4207: 		      $loadm=$answer;
 4208:                       $unhome=$tryserver;
 4209:                   }
 4210: 	       }
 4211: 	    }
 4212:         }
 4213:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 4214: 	    return 'error: unable to find a home server for '.$uname.
 4215:                    ' in domain '.$udom;
 4216:         }
 4217:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 4218:                          &escape($upass),$unhome);
 4219: 	unless ($reply eq 'ok') {
 4220:             return 'error: '.$reply;
 4221:         }   
 4222:         $uhome=&homeserver($uname,$udom,'true');
 4223:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 4224: 	    return 'error: unable verify users home machine.';
 4225:         }
 4226:     }   # End of creation of new user
 4227: # ---------------------------------------------------------------------- Add ID
 4228:     if ($uid) {
 4229:        $uid=~tr/A-Z/a-z/;
 4230:        my %uidhash=&idrget($udom,$uname);
 4231:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 4232:          && (!$forceid)) {
 4233: 	  unless ($uid eq $uidhash{$uname}) {
 4234: 	      return 'error: user id "'.$uid.'" does not match '.
 4235:                   'current user id "'.$uidhash{$uname}.'".';
 4236:           }
 4237:        } else {
 4238: 	  &idput($udom,($uname => $uid));
 4239:        }
 4240:     }
 4241: # -------------------------------------------------------------- Add names, etc
 4242:     my @tmp=&get('environment',
 4243: 		   ['firstname','middlename','lastname','generation'],
 4244: 		   $udom,$uname);
 4245:     my %names;
 4246:     if ($tmp[0] =~ m/^error:.*/) { 
 4247:         %names=(); 
 4248:     } else {
 4249:         %names = @tmp;
 4250:     }
 4251: #
 4252: # Make sure to not trash student environment if instructor does not bother
 4253: # to supply name and email information
 4254: #
 4255:     if ($first)  { $names{'firstname'}  = $first; }
 4256:     if (defined($middle)) { $names{'middlename'} = $middle; }
 4257:     if ($last)   { $names{'lastname'}   = $last; }
 4258:     if (defined($gene))   { $names{'generation'} = $gene; }
 4259:     if ($email) {
 4260:        $email=~s/[^\w\@\.\-\,]//gs;
 4261:        if ($email=~/\@/) { $names{'notification'} = $email;
 4262: 			   $names{'critnotification'} = $email;
 4263: 			   $names{'permanentemail'} = $email; }
 4264:     }
 4265:     my $reply = &put('environment', \%names, $udom,$uname);
 4266:     if ($reply ne 'ok') { return 'error: '.$reply; }
 4267:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 4268:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 4269:              $umode.', '.$first.', '.$middle.', '.
 4270: 	     $last.', '.$gene.' by '.
 4271:              $env{'user.name'}.' at '.$env{'user.domain'});
 4272:     return 'ok';
 4273: }
 4274: 
 4275: # -------------------------------------------------------------- Modify student
 4276: 
 4277: sub modifystudent {
 4278:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 4279:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 4280:     if (!$cid) {
 4281: 	unless ($cid=$env{'request.course.id'}) {
 4282: 	    return 'not_in_class';
 4283: 	}
 4284:     }
 4285: # --------------------------------------------------------------- Make the user
 4286:     my $reply=&modifyuser
 4287: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 4288:          $desiredhome,$email);
 4289:     unless ($reply eq 'ok') { return $reply; }
 4290:     # This will cause &modify_student_enrollment to get the uid from the
 4291:     # students environment
 4292:     $uid = undef if (!$forceid);
 4293:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 4294: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 4295:     return $reply;
 4296: }
 4297: 
 4298: sub modify_student_enrollment {
 4299:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
 4300:     my ($cdom,$cnum,$chome);
 4301:     if (!$cid) {
 4302: 	unless ($cid=$env{'request.course.id'}) {
 4303: 	    return 'not_in_class';
 4304: 	}
 4305: 	$cdom=$env{'course.'.$cid.'.domain'};
 4306: 	$cnum=$env{'course.'.$cid.'.num'};
 4307:     } else {
 4308: 	($cdom,$cnum)=split(/_/,$cid);
 4309:     }
 4310:     $chome=$env{'course.'.$cid.'.home'};
 4311:     if (!$chome) {
 4312: 	$chome=&homeserver($cnum,$cdom);
 4313:     }
 4314:     if (!$chome) { return 'unknown_course'; }
 4315:     # Make sure the user exists
 4316:     my $uhome=&homeserver($uname,$udom);
 4317:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 4318: 	return 'error: no such user';
 4319:     }
 4320:     # Get student data if we were not given enough information
 4321:     if (!defined($first)  || $first  eq '' || 
 4322:         !defined($last)   || $last   eq '' || 
 4323:         !defined($uid)    || $uid    eq '' || 
 4324:         !defined($middle) || $middle eq '' || 
 4325:         !defined($gene)   || $gene   eq '') {
 4326:         # They did not supply us with enough data to enroll the student, so
 4327:         # we need to pick up more information.
 4328:         my %tmp = &get('environment',
 4329:                        ['firstname','middlename','lastname', 'generation','id']
 4330:                        ,$udom,$uname);
 4331: 
 4332:         #foreach (keys(%tmp)) {
 4333:         #    &logthis("key $_ = ".$tmp{$_});
 4334:         #}
 4335:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 4336:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 4337:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 4338:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 4339:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 4340:     }
 4341:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 4342:     my $reply=cput('classlist',
 4343: 		   {"$uname:$udom" => 
 4344: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 4345: 		   $cdom,$cnum);
 4346:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 4347: 	return 'error: '.$reply;
 4348:     } else {
 4349: 	&devalidate_getsection_cache($udom,$uname,$cid);
 4350:     }
 4351:     # Add student role to user
 4352:     my $uurl='/'.$cid;
 4353:     $uurl=~s/\_/\//g;
 4354:     if ($usec) {
 4355: 	$uurl.='/'.$usec;
 4356:     }
 4357:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 4358: }
 4359: 
 4360: sub format_name {
 4361:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 4362:     my $name;
 4363:     if ($first ne 'lastname') {
 4364: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 4365:     } else {
 4366: 	if ($lastname=~/\S/) {
 4367: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 4368: 	    $name=~s/\s+,/,/;
 4369: 	} else {
 4370: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 4371: 	}
 4372:     }
 4373:     $name=~s/^\s+//;
 4374:     $name=~s/\s+$//;
 4375:     $name=~s/\s+/ /g;
 4376:     return $name;
 4377: }
 4378: 
 4379: # ------------------------------------------------- Write to course preferences
 4380: 
 4381: sub writecoursepref {
 4382:     my ($courseid,%prefs)=@_;
 4383:     $courseid=~s/^\///;
 4384:     $courseid=~s/\_/\//g;
 4385:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4386:     my $chome=homeserver($cnum,$cdomain);
 4387:     if (($chome eq '') || ($chome eq 'no_host')) { 
 4388: 	return 'error: no such course';
 4389:     }
 4390:     my $cstring='';
 4391:     foreach (keys %prefs) {
 4392: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
 4393:     }
 4394:     $cstring=~s/\&$//;
 4395:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 4396: }
 4397: 
 4398: # ---------------------------------------------------------- Make/modify course
 4399: 
 4400: sub createcourse {
 4401:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner)=@_;
 4402:     $url=&declutter($url);
 4403:     my $cid='';
 4404:     unless (&allowed('ccc',$udom)) {
 4405:         return 'refused';
 4406:     }
 4407: # ------------------------------------------------------------------- Create ID
 4408:    my $uname=int(1+rand(9)).
 4409:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 4410:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 4411:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 4412: # ----------------------------------------------- Make sure that does not exist
 4413:    my $uhome=&homeserver($uname,$udom,'true');
 4414:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 4415:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 4416:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 4417:        $uhome=&homeserver($uname,$udom,'true');       
 4418:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 4419:            return 'error: unable to generate unique course-ID';
 4420:        } 
 4421:    }
 4422: # ------------------------------------------------ Check supplied server name
 4423:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 4424:     if (! exists($libserv{$course_server})) {
 4425:         return 'error:bad server name '.$course_server;
 4426:     }
 4427: # ------------------------------------------------------------- Make the course
 4428:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 4429:                       $course_server);
 4430:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 4431:     $uhome=&homeserver($uname,$udom,'true');
 4432:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 4433: 	return 'error: no such course';
 4434:     }
 4435: # ----------------------------------------------------------------- Course made
 4436: # log existence
 4437:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
 4438:                  ':'.&escape($inst_code).':'.&escape($course_owner),$uhome);
 4439:     &flushcourselogs();
 4440: # set toplevel url
 4441:     my $topurl=$url;
 4442:     unless ($nonstandard) {
 4443: # ------------------------------------------ For standard courses, make top url
 4444:         my $mapurl=&clutter($url);
 4445:         if ($mapurl eq '/res/') { $mapurl=''; }
 4446:         $env{'form.initmap'}=(<<ENDINITMAP);
 4447: <map>
 4448: <resource id="1" type="start"></resource>
 4449: <resource id="2" src="$mapurl"></resource>
 4450: <resource id="3" type="finish"></resource>
 4451: <link index="1" from="1" to="2"></link>
 4452: <link index="2" from="2" to="3"></link>
 4453: </map>
 4454: ENDINITMAP
 4455:         $topurl=&declutter(
 4456:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 4457:                           );
 4458:     }
 4459: # ----------------------------------------------------------- Write preferences
 4460:     &writecoursepref($udom.'_'.$uname,
 4461:                      ('description' => $description,
 4462:                       'url'         => $topurl));
 4463:     return '/'.$udom.'/'.$uname;
 4464: }
 4465: 
 4466: # ---------------------------------------------------------- Assign Custom Role
 4467: 
 4468: sub assigncustomrole {
 4469:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 4470:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 4471:                        $end,$start,$deleteflag);
 4472: }
 4473: 
 4474: # ----------------------------------------------------------------- Revoke Role
 4475: 
 4476: sub revokerole {
 4477:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 4478:     my $now=time;
 4479:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 4480: }
 4481: 
 4482: # ---------------------------------------------------------- Revoke Custom Role
 4483: 
 4484: sub revokecustomrole {
 4485:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 4486:     my $now=time;
 4487:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 4488:            $deleteflag);
 4489: }
 4490: 
 4491: # ------------------------------------------------------------ Disk usage
 4492: sub diskusage {
 4493:     my ($udom,$uname,$directoryRoot)=@_;
 4494:     $directoryRoot =~ s/\/$//;
 4495:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 4496:     return $listing;
 4497: }
 4498: 
 4499: sub is_locked {
 4500:     my ($file_name, $domain, $user) = @_;
 4501:     my @check;
 4502:     my $is_locked;
 4503:     push @check, $file_name;
 4504:     my %locked = &get('file_permissions',\@check,
 4505: 		      $env{'user.domain'},$env{'user.name'});
 4506:     my ($tmp)=keys(%locked);
 4507:     if ($tmp=~/^error:/) { undef(%locked); }
 4508: 
 4509:     if (ref($locked{$file_name}) eq 'ARRAY') {
 4510:         $is_locked = 'true';
 4511:     } else {
 4512:         $is_locked = 'false';
 4513:     }
 4514: }
 4515: 
 4516: # ------------------------------------------------------------- Mark as Read Only
 4517: 
 4518: sub mark_as_readonly {
 4519:     my ($domain,$user,$files,$what) = @_;
 4520:     my %current_permissions = &dump('file_permissions',$domain,$user);
 4521:     my ($tmp)=keys(%current_permissions);
 4522:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 4523:     foreach my $file (@{$files}) {
 4524:         push(@{$current_permissions{$file}},$what);
 4525:     }
 4526:     &put('file_permissions',\%current_permissions,$domain,$user);
 4527:     return;
 4528: }
 4529: 
 4530: # ------------------------------------------------------------Save Selected Files
 4531: 
 4532: sub save_selected_files {
 4533:     my ($user, $path, @files) = @_;
 4534:     my $filename = $user."savedfiles";
 4535:     my @other_files = &files_not_in_path($user, $path);
 4536:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4537:     foreach my $file (@files) {
 4538:         print (OUT $env{'form.currentpath'}.$file."\n");
 4539:     }
 4540:     foreach my $file (@other_files) {
 4541:         print (OUT $file."\n");
 4542:     }
 4543:     close (OUT);
 4544:     return 'ok';
 4545: }
 4546: 
 4547: sub clear_selected_files {
 4548:     my ($user) = @_;
 4549:     my $filename = $user."savedfiles";
 4550:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4551:     print (OUT undef);
 4552:     close (OUT);
 4553:     return ("ok");    
 4554: }
 4555: 
 4556: sub files_in_path {
 4557:     my ($user, $path) = @_;
 4558:     my $filename = $user."savedfiles";
 4559:     my %return_files;
 4560:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4561:     while (my $line_in = <IN>) {
 4562:         chomp ($line_in);
 4563:         my @paths_and_file = split (m!/!, $line_in);
 4564:         my $file_part = pop (@paths_and_file);
 4565:         my $path_part = join ('/', @paths_and_file);
 4566:         $path_part.='/';
 4567:         my $path_and_file = $path_part.$file_part;
 4568:         if ($path_part eq $path) {
 4569:             $return_files{$file_part}= 'selected';
 4570:         }
 4571:     }
 4572:     close (IN);
 4573:     return (\%return_files);
 4574: }
 4575: 
 4576: # called in portfolio select mode, to show files selected NOT in current directory
 4577: sub files_not_in_path {
 4578:     my ($user, $path) = @_;
 4579:     my $filename = $user."savedfiles";
 4580:     my @return_files;
 4581:     my $path_part;
 4582:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4583:     while (<IN>) {
 4584:         #ok, I know it's clunky, but I want it to work
 4585:         my @paths_and_file = split m!/!, $_;
 4586:         my $file_part = pop (@paths_and_file);
 4587:         chomp ($file_part);
 4588:         my $path_part = join ('/', @paths_and_file);
 4589:         $path_part .= '/';
 4590:         my $path_and_file = $path_part.$file_part;
 4591:         if ($path_part ne $path) {
 4592:             push (@return_files, ($path_and_file));
 4593:         }
 4594:     }
 4595:     close (OUT);
 4596:     return (@return_files);
 4597: }
 4598: 
 4599: #--------------------------------------------------------------Get Marked as Read Only
 4600: 
 4601: 
 4602: sub get_marked_as_readonly {
 4603:     my ($domain,$user,$what) = @_;
 4604:     my %current_permissions = &dump('file_permissions',$domain,$user);
 4605:     my ($tmp)=keys(%current_permissions);
 4606:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 4607:     my @readonly_files;
 4608:     my $cmp1=$what;
 4609:     if (ref($what)) { $cmp1=join('',@{$what}) };
 4610:     while (my ($file_name,$value) = each(%current_permissions)) {
 4611:         if (ref($value) eq "ARRAY"){
 4612:             foreach my $stored_what (@{$value}) {
 4613:                 my $cmp2=$stored_what;
 4614:                 if (ref($stored_what)) { $cmp2=join('',@{$stored_what}) };
 4615:                 if ($cmp1 eq $cmp2) {
 4616:                     push(@readonly_files, $file_name);
 4617:                 } elsif (!defined($what)) {
 4618:                     push(@readonly_files, $file_name);
 4619:                 }
 4620:             }
 4621:         } 
 4622:     }
 4623:     return @readonly_files;
 4624: }
 4625: #-----------------------------------------------------------Get Marked as Read Only Hash
 4626: 
 4627: sub get_marked_as_readonly_hash {
 4628:     my ($domain,$user,$what) = @_;
 4629:     my %current_permissions = &dump('file_permissions',$domain,$user);
 4630:     my ($tmp)=keys(%current_permissions);
 4631:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 4632: 
 4633:     my %readonly_files;
 4634:     while (my ($file_name,$value) = each(%current_permissions)) {
 4635:         if (ref($value) eq "ARRAY"){
 4636:             foreach my $stored_what (@{$value}) {
 4637:                 if ($stored_what eq $what) {
 4638:                     $readonly_files{$file_name} = 'locked';
 4639:                 } elsif (!defined($what)) {
 4640:                     $readonly_files{$file_name} = 'locked';
 4641:                 }
 4642:             }
 4643:         } 
 4644:     }
 4645:     return %readonly_files;
 4646: }
 4647: # ------------------------------------------------------------ Unmark as Read Only
 4648: 
 4649: sub unmark_as_readonly {
 4650:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 4651:     # for portfolio submissions, $what contains [$symb,$crsid] 
 4652:     my ($domain,$user,$what,$file_name) = @_;
 4653:     my $symb_crs = $what;
 4654:     if (ref($what)) { $symb_crs=join('',@$what); }
 4655:     my %current_permissions = &dump('file_permissions',$domain,$user);
 4656:     my ($tmp)=keys(%current_permissions);
 4657:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 4658:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what);
 4659:     foreach my $file (@readonly_files) {
 4660: 	if (defined($file_name) && ($file_name ne $file)) { next; }
 4661: 	my $current_locks = $current_permissions{$file};
 4662:         my @new_locks;
 4663:         my @del_keys;
 4664:         if (ref($current_locks) eq "ARRAY"){
 4665:             foreach my $locker (@{$current_locks}) {
 4666:                 my $compare=$locker;
 4667:                 if (ref($locker)) { $compare=join('',@{$locker}) };
 4668:                 if ($compare ne $symb_crs) {
 4669:                     push(@new_locks, $locker);
 4670:                 }
 4671:             }
 4672:             if (scalar(@new_locks) > 0) {
 4673:                 $current_permissions{$file} = \@new_locks;
 4674:             } else {
 4675:                 push(@del_keys, $file);
 4676:                 &del('file_permissions',\@del_keys, $domain, $user);
 4677:                 delete($current_permissions{$file});
 4678:             }
 4679:         }
 4680:     }
 4681:     &put('file_permissions',\%current_permissions,$domain,$user);
 4682:     return;
 4683: }
 4684: 
 4685: # ------------------------------------------------------------ Directory lister
 4686: 
 4687: sub dirlist {
 4688:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 4689: 
 4690:     $uri=~s/^\///;
 4691:     $uri=~s/\/$//;
 4692:     my ($udom, $uname);
 4693:     (undef,$udom,$uname)=split(/\//,$uri);
 4694:     if(defined($userdomain)) {
 4695:         $udom = $userdomain;
 4696:     }
 4697:     if(defined($username)) {
 4698:         $uname = $username;
 4699:     }
 4700: 
 4701:     my $dirRoot = $perlvar{'lonDocRoot'};
 4702:     if(defined($alternateDirectoryRoot)) {
 4703:         $dirRoot = $alternateDirectoryRoot;
 4704:         $dirRoot =~ s/\/$//;
 4705:     }
 4706: 
 4707:     if($udom) {
 4708:         if($uname) {
 4709:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
 4710:                               homeserver($uname,$udom));
 4711:             my @listing_results;
 4712:             if ($listing eq 'unknown_cmd') {
 4713:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
 4714:                                homeserver($uname,$udom));
 4715:                 @listing_results = split(/:/,$listing);
 4716:             } else {
 4717:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 4718:             }
 4719:             return @listing_results;
 4720:         } elsif(!defined($alternateDirectoryRoot)) {
 4721:             my $tryserver;
 4722:             my %allusers=();
 4723:             foreach $tryserver (keys %libserv) {
 4724:                 if($hostdom{$tryserver} eq $udom) {
 4725:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 4726:                                       $udom, $tryserver);
 4727:                     my @listing_results;
 4728:                     if ($listing eq 'unknown_cmd') {
 4729:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 4730:                                        $udom, $tryserver);
 4731:                         @listing_results = split(/:/,$listing);
 4732:                     } else {
 4733:                         @listing_results =
 4734:                             map { &unescape($_); } split(/:/,$listing);
 4735:                     }
 4736:                     if ($listing_results[0] ne 'no_such_dir' && 
 4737:                         $listing_results[0] ne 'empty'       &&
 4738:                         $listing_results[0] ne 'con_lost') {
 4739:                         foreach (@listing_results) {
 4740:                             my ($entry,@stat)=split(/&/,$_);
 4741:                             $allusers{$entry}=1;
 4742:                         }
 4743:                     }
 4744:                 }
 4745:             }
 4746:             my $alluserstr='';
 4747:             foreach (sort keys %allusers) {
 4748:                 $alluserstr.=$_.'&user:';
 4749:             }
 4750:             $alluserstr=~s/:$//;
 4751:             return split(/:/,$alluserstr);
 4752:         } else {
 4753:             my @emptyResults = ();
 4754:             push(@emptyResults, 'missing user name');
 4755:             return split(':',@emptyResults);
 4756:         }
 4757:     } elsif(!defined($alternateDirectoryRoot)) {
 4758:         my $tryserver;
 4759:         my %alldom=();
 4760:         foreach $tryserver (keys %libserv) {
 4761:             $alldom{$hostdom{$tryserver}}=1;
 4762:         }
 4763:         my $alldomstr='';
 4764:         foreach (sort keys %alldom) {
 4765:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
 4766:         }
 4767:         $alldomstr=~s/:$//;
 4768:         return split(/:/,$alldomstr);       
 4769:     } else {
 4770:         my @emptyResults = ();
 4771:         push(@emptyResults, 'missing domain');
 4772:         return split(':',@emptyResults);
 4773:     }
 4774: }
 4775: 
 4776: # --------------------------------------------- GetFileTimestamp
 4777: # This function utilizes dirlist and returns the date stamp for
 4778: # when it was last modified.  It will also return an error of -1
 4779: # if an error occurs
 4780: 
 4781: ##
 4782: ## FIXME: This subroutine assumes its caller knows something about the
 4783: ## directory structure of the home server for the student ($root).
 4784: ## Not a good assumption to make.  Since this is for looking up files
 4785: ## in user directories, the full path should be constructed by lond, not
 4786: ## whatever machine we request data from.
 4787: ##
 4788: sub GetFileTimestamp {
 4789:     my ($studentDomain,$studentName,$filename,$root)=@_;
 4790:     $studentDomain=~s/\W//g;
 4791:     $studentName=~s/\W//g;
 4792:     my $subdir=$studentName.'__';
 4793:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 4794:     my $proname="$studentDomain/$subdir/$studentName";
 4795:     $proname .= '/'.$filename;
 4796:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 4797:                                               $studentName, $root);
 4798:     my @stats = split('&', $fileStat);
 4799:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 4800:         # @stats contains first the filename, then the stat output
 4801:         return $stats[10]; # so this is 10 instead of 9.
 4802:     } else {
 4803:         return -1;
 4804:     }
 4805: }
 4806: 
 4807: sub stat_file {
 4808:     my ($uri) = @_;
 4809:     $uri = &clutter($uri);
 4810: 
 4811:     # we want just the url part without the unneeded accessor url bits
 4812:     if ($uri =~ m-^/adm/-) {
 4813: 	$uri=~s-^/adm/wrapper/-/-;
 4814: 	$uri=~s-^/adm/coursedocs/showdoc/-/-;
 4815:     }
 4816:     my ($udom,$uname,$file,$dir);
 4817:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 4818: 	($udom,$uname,$file) =
 4819: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
 4820: 	$file = 'userfiles/'.$file;
 4821: 	$dir = &Apache::loncommon::propath($udom,$uname);
 4822:     }
 4823:     if ($uri =~ m-^/res/-) {
 4824: 	($udom,$uname) = 
 4825: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
 4826: 	$file = $uri;
 4827:     }
 4828: 
 4829:     if (!$udom || !$uname || !$file) {
 4830: 	# unable to handle the uri
 4831: 	return ();
 4832:     }
 4833: 
 4834:     my ($result) = &dirlist($file,$udom,$uname,$dir);
 4835:     my @stats = split('&', $result);
 4836:     
 4837:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 4838: 	shift(@stats); #filename is first
 4839: 	return @stats;
 4840:     }
 4841:     return ();
 4842: }
 4843: 
 4844: # -------------------------------------------------------- Value of a Condition
 4845: 
 4846: # gets the value of a specific preevaluated condition
 4847: #    stored in the string  $env{user.state.<cid>}
 4848: # or looks up a condition reference in the bighash and if if hasn't
 4849: # already been evaluated recurses into docondval to get the value of
 4850: # the condition, then memoizing it to 
 4851: #   $env{user.state.<cid>.<condition>}
 4852: sub directcondval {
 4853:     my $number=shift;
 4854:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 4855: 	&Apache::lonuserstate::evalstate();
 4856:     }
 4857:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 4858: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 4859:     } elsif ($number =~ /^_/) {
 4860: 	my $sub_condition;
 4861: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 4862: 		&GDBM_READER(),0640)) {
 4863: 	    $sub_condition=$bighash{'conditions'.$number};
 4864: 	    untie(%bighash);
 4865: 	}
 4866: 	my $value = &docondval($sub_condition);
 4867: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
 4868: 	return $value;
 4869:     }
 4870:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 4871:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 4872:     } else {
 4873:        return 2;
 4874:     }
 4875: }
 4876: 
 4877: # get the collection of conditions for this resource
 4878: sub condval {
 4879:     my $condidx=shift;
 4880:     my $allpathcond='';
 4881:     foreach my $cond (split(/\|/,$condidx)) {
 4882: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 4883: 	    $allpathcond.=
 4884: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 4885: 	}
 4886:     }
 4887:     $allpathcond=~s/\|$//;
 4888:     return &docondval($allpathcond);
 4889: }
 4890: 
 4891: #evaluates an expression of conditions
 4892: sub docondval {
 4893:     my ($allpathcond) = @_;
 4894:     my $result=0;
 4895:     if ($env{'request.course.id'}
 4896: 	&& defined($allpathcond)) {
 4897: 	my $operand='|';
 4898: 	my @stack;
 4899: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 4900: 	    if ($chunk eq '(') {
 4901: 		push @stack,($operand,$result);
 4902: 	    } elsif ($chunk eq ')') {
 4903: 		my $before=pop @stack;
 4904: 		if (pop @stack eq '&') {
 4905: 		    $result=$result>$before?$before:$result;
 4906: 		} else {
 4907: 		    $result=$result>$before?$result:$before;
 4908: 		}
 4909: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 4910: 		$operand=$chunk;
 4911: 	    } else {
 4912: 		my $new=directcondval($chunk);
 4913: 		if ($operand eq '&') {
 4914: 		    $result=$result>$new?$new:$result;
 4915: 		} else {
 4916: 		    $result=$result>$new?$result:$new;
 4917: 		}
 4918: 	    }
 4919: 	}
 4920:     }
 4921:     return $result;
 4922: }
 4923: 
 4924: # ---------------------------------------------------- Devalidate courseresdata
 4925: 
 4926: sub devalidatecourseresdata {
 4927:     my ($coursenum,$coursedomain)=@_;
 4928:     my $hashid=$coursenum.':'.$coursedomain;
 4929:     &devalidate_cache_new('courseres',$hashid);
 4930: }
 4931: 
 4932: # --------------------------------------------------- Course Resourcedata Query
 4933: 
 4934: sub get_courseresdata {
 4935:     my ($coursenum,$coursedomain)=@_;
 4936:     my $coursehom=&homeserver($coursenum,$coursedomain);
 4937:     my $hashid=$coursenum.':'.$coursedomain;
 4938:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 4939:     my %dumpreply;
 4940:     unless (defined($cached)) {
 4941: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 4942: 	$result=\%dumpreply;
 4943: 	my ($tmp) = keys(%dumpreply);
 4944: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 4945: 	    &do_cache_new('courseres',$hashid,$result,600);
 4946: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 4947: 	    return $tmp;
 4948: 	} elsif ($tmp =~ /^(error)/) {
 4949: 	    $result=undef;
 4950: 	    &do_cache_new('courseres',$hashid,$result,600);
 4951: 	}
 4952:     }
 4953:     return $result;
 4954: }
 4955: 
 4956: sub devalidateuserresdata {
 4957:     my ($uname,$udom)=@_;
 4958:     my $hashid="$udom:$uname";
 4959:     &devalidate_cache_new('userres',$hashid);
 4960: }
 4961: 
 4962: sub get_userresdata {
 4963:     my ($uname,$udom)=@_;
 4964:     #most student don\'t have any data set, check if there is some data
 4965:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 4966: 
 4967:     my $hashid="$udom:$uname";
 4968:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 4969:     if (!defined($cached)) {
 4970: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 4971: 	$result=\%resourcedata;
 4972: 	&do_cache_new('userres',$hashid,$result,600);
 4973:     }
 4974:     my ($tmp)=keys(%$result);
 4975:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 4976: 	return $result;
 4977:     }
 4978:     #error 2 occurs when the .db doesn't exist
 4979:     if ($tmp!~/error: 2 /) {
 4980: 	&logthis("<font color=\"blue\">WARNING:".
 4981: 		 " Trying to get resource data for ".
 4982: 		 $uname." at ".$udom.": ".
 4983: 		 $tmp."</font>");
 4984:     } elsif ($tmp=~/error: 2 /) {
 4985: 	#&EXT_cache_set($udom,$uname);
 4986: 	&do_cache_new('userres',$hashid,undef,600);
 4987: 	undef($tmp); # not really an error so don't send it back
 4988:     }
 4989:     return $tmp;
 4990: }
 4991: 
 4992: sub resdata {
 4993:     my ($name,$domain,$type,@which)=@_;
 4994:     my $result;
 4995:     if ($type eq 'course') {
 4996: 	$result=&get_courseresdata($name,$domain);
 4997:     } elsif ($type eq 'user') {
 4998: 	$result=&get_userresdata($name,$domain);
 4999:     }
 5000:     if (!ref($result)) { return $result; }    
 5001:     foreach my $item (@which) {
 5002: 	if (defined($result->{$item})) {
 5003: 	    return $result->{$item};
 5004: 	}
 5005:     }
 5006:     return undef;
 5007: }
 5008: 
 5009: #
 5010: # EXT resource caching routines
 5011: #
 5012: 
 5013: sub clear_EXT_cache_status {
 5014:     &delenv('cache.EXT.');
 5015: }
 5016: 
 5017: sub EXT_cache_status {
 5018:     my ($target_domain,$target_user) = @_;
 5019:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5020:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 5021:         # We know already the user has no data
 5022:         return 1;
 5023:     } else {
 5024:         return 0;
 5025:     }
 5026: }
 5027: 
 5028: sub EXT_cache_set {
 5029:     my ($target_domain,$target_user) = @_;
 5030:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5031:     #&appenv($cachename => time);
 5032: }
 5033: 
 5034: # --------------------------------------------------------- Value of a Variable
 5035: sub EXT {
 5036: 
 5037:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 5038:     unless ($varname) { return ''; }
 5039:     #get real user name/domain, courseid and symb
 5040:     my $courseid;
 5041:     my $publicuser;
 5042:     if ($symbparm) {
 5043: 	$symbparm=&get_symb_from_alias($symbparm);
 5044:     }
 5045:     if (!($uname && $udom)) {
 5046:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
 5047: 	  &Apache::lonxml::whichuser($symbparm);
 5048:       if (!$symbparm) {	$symbparm=$cursymb; }
 5049:     } else {
 5050: 	$courseid=$env{'request.course.id'};
 5051:     }
 5052:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 5053:     my $rest;
 5054:     if (defined($therest[0])) {
 5055:        $rest=join('.',@therest);
 5056:     } else {
 5057:        $rest='';
 5058:     }
 5059: 
 5060:     my $qualifierrest=$qualifier;
 5061:     if ($rest) { $qualifierrest.='.'.$rest; }
 5062:     my $spacequalifierrest=$space;
 5063:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 5064:     if ($realm eq 'user') {
 5065: # --------------------------------------------------------------- user.resource
 5066: 	if ($space eq 'resource') {
 5067: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 5068: 		  || defined($Apache::lonhomework::parsing_a_task))
 5069: 		 &&
 5070: 		 ($symbparm eq &symbread()) ) {
 5071: 		return $Apache::lonhomework::history{$qualifierrest};
 5072: 	    } else {
 5073: 		my %restored;
 5074: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 5075: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 5076: 		} else {
 5077: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 5078: 		}
 5079: 		return $restored{$qualifierrest};
 5080: 	    }
 5081: # ----------------------------------------------------------------- user.access
 5082:         } elsif ($space eq 'access') {
 5083: 	    # FIXME - not supporting calls for a specific user
 5084:             return &allowed($qualifier,$rest);
 5085: # ------------------------------------------ user.preferences, user.environment
 5086:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 5087: 	    if (($uname eq $env{'user.name'}) &&
 5088: 		($udom eq $env{'user.domain'})) {
 5089: 		return $env{join('.',('environment',$qualifierrest))};
 5090: 	    } else {
 5091: 		my %returnhash;
 5092: 		if (!$publicuser) {
 5093: 		    %returnhash=&userenvironment($udom,$uname,
 5094: 						 $qualifierrest);
 5095: 		}
 5096: 		return $returnhash{$qualifierrest};
 5097: 	    }
 5098: # ----------------------------------------------------------------- user.course
 5099:         } elsif ($space eq 'course') {
 5100: 	    # FIXME - not supporting calls for a specific user
 5101:             return $env{join('.',('request.course',$qualifier))};
 5102: # ------------------------------------------------------------------- user.role
 5103:         } elsif ($space eq 'role') {
 5104: 	    # FIXME - not supporting calls for a specific user
 5105:             my ($role,$where)=split(/\./,$env{'request.role'});
 5106:             if ($qualifier eq 'value') {
 5107: 		return $role;
 5108:             } elsif ($qualifier eq 'extent') {
 5109:                 return $where;
 5110:             }
 5111: # ----------------------------------------------------------------- user.domain
 5112:         } elsif ($space eq 'domain') {
 5113:             return $udom;
 5114: # ------------------------------------------------------------------- user.name
 5115:         } elsif ($space eq 'name') {
 5116:             return $uname;
 5117: # ---------------------------------------------------- Any other user namespace
 5118:         } else {
 5119: 	    my %reply;
 5120: 	    if (!$publicuser) {
 5121: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 5122: 	    }
 5123: 	    return $reply{$qualifierrest};
 5124:         }
 5125:     } elsif ($realm eq 'query') {
 5126: # ---------------------------------------------- pull stuff out of query string
 5127:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 5128: 						[$spacequalifierrest]);
 5129: 	return $env{'form.'.$spacequalifierrest}; 
 5130:    } elsif ($realm eq 'request') {
 5131: # ------------------------------------------------------------- request.browser
 5132:         if ($space eq 'browser') {
 5133: 	    if ($qualifier eq 'textremote') {
 5134: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 5135: 		    return 1;
 5136: 		} else {
 5137: 		    return 0;
 5138: 		}
 5139: 	    } else {
 5140: 		return $env{'browser.'.$qualifier};
 5141: 	    }
 5142: # ------------------------------------------------------------ request.filename
 5143:         } else {
 5144:             return $env{'request.'.$spacequalifierrest};
 5145:         }
 5146:     } elsif ($realm eq 'course') {
 5147: # ---------------------------------------------------------- course.description
 5148:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 5149:     } elsif ($realm eq 'resource') {
 5150: 
 5151: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 5152: 	    if (!$symbparm) { $symbparm=&symbread(); }
 5153: 	}
 5154: 
 5155: 	if ($space eq 'title') {
 5156: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 5157: 	    return &gettitle($symbparm);
 5158: 	}
 5159: 	
 5160: 	if ($space eq 'map') {
 5161: 	    my ($map) = &decode_symb($symbparm);
 5162: 	    return &symbread($map);
 5163: 	}
 5164: 
 5165: 	my ($section, $group, @groups);
 5166: 	my ($courselevelm,$courselevel);
 5167: 	if ($symbparm && defined($courseid) && 
 5168: 	    $courseid eq $env{'request.course.id'}) {
 5169: 
 5170: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 5171: 
 5172: # ----------------------------------------------------- Cascading lookup scheme
 5173: 	    my $symbp=$symbparm;
 5174: 	    my $mapp=(&decode_symb($symbp))[0];
 5175: 
 5176: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 5177: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 5178: 
 5179: 	    if (($env{'user.name'} eq $uname) &&
 5180: 		($env{'user.domain'} eq $udom)) {
 5181: 		$section=$env{'request.course.sec'};
 5182:                 @groups = split(/:/,$env{'request.course.groups'});  
 5183:                 @groups=&sort_course_groups($courseid,@groups); 
 5184: 	    } else {
 5185: 		if (! defined($usection)) {
 5186: 		    $section=&getsection($udom,$uname,$courseid);
 5187: 		} else {
 5188: 		    $section = $usection;
 5189: 		}
 5190:                 @groups = &get_users_groups($udom,$uname,$courseid);
 5191: 	    }
 5192: 
 5193: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 5194: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 5195: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 5196: 
 5197: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 5198: 	    my $courselevelr=$courseid.'.'.$symbparm;
 5199: 	    $courselevelm=$courseid.'.'.$mapparm;
 5200: 
 5201: # ----------------------------------------------------------- first, check user
 5202: 
 5203: 	    my $userreply=&resdata($uname,$udom,'user',
 5204: 				       ($courselevelr,$courselevelm,
 5205: 					$courselevel));
 5206: 	    if (defined($userreply)) { return $userreply; }
 5207: 
 5208: # ------------------------------------------------ second, check some of course
 5209:             my $coursereply;
 5210:             if (@groups > 0) {
 5211:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 5212:                                        $mapparm,$spacequalifierrest);
 5213:                 if (defined($coursereply)) { return $coursereply; }
 5214:             }
 5215: 
 5216: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 5217: 				     $env{'course.'.$courseid.'.domain'},
 5218: 				     'course',
 5219: 				     ($seclevelr,$seclevelm,$seclevel,
 5220: 				      $courselevelr));
 5221: 	    if (defined($coursereply)) { return $coursereply; }
 5222: 
 5223: # ------------------------------------------------------ third, check map parms
 5224: 	    my %parmhash=();
 5225: 	    my $thisparm='';
 5226: 	    if (tie(%parmhash,'GDBM_File',
 5227: 		    $env{'request.course.fn'}.'_parms.db',
 5228: 		    &GDBM_READER(),0640)) {
 5229: 		$thisparm=$parmhash{$symbparm};
 5230: 		untie(%parmhash);
 5231: 	    }
 5232: 	    if ($thisparm) { return $thisparm; }
 5233: 	}
 5234: # ------------------------------------------ fourth, look in resource metadata
 5235: 
 5236: 	$spacequalifierrest=~s/\./\_/;
 5237: 	my $filename;
 5238: 	if (!$symbparm) { $symbparm=&symbread(); }
 5239: 	if ($symbparm) {
 5240: 	    $filename=(&decode_symb($symbparm))[2];
 5241: 	} else {
 5242: 	    $filename=$env{'request.filename'};
 5243: 	}
 5244: 	my $metadata=&metadata($filename,$spacequalifierrest);
 5245: 	if (defined($metadata)) { return $metadata; }
 5246: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 5247: 	if (defined($metadata)) { return $metadata; }
 5248: 
 5249: # ---------------------------------------------- fourth, look in rest pf course
 5250: 	if ($symbparm && defined($courseid) && 
 5251: 	    $courseid eq $env{'request.course.id'}) {
 5252: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 5253: 				     $env{'course.'.$courseid.'.domain'},
 5254: 				     'course',
 5255: 				     ($courselevelm,$courselevel));
 5256: 	    if (defined($coursereply)) { return $coursereply; }
 5257: 	}
 5258: # ------------------------------------------------------------------ Cascade up
 5259: 	unless ($space eq '0') {
 5260: 	    my @parts=split(/_/,$space);
 5261: 	    my $id=pop(@parts);
 5262: 	    my $part=join('_',@parts);
 5263: 	    if ($part eq '') { $part='0'; }
 5264: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 5265: 				 $symbparm,$udom,$uname,$section,1);
 5266: 	    if (defined($partgeneral)) { return $partgeneral; }
 5267: 	}
 5268: 	if ($recurse) { return undef; }
 5269: 	my $pack_def=&packages_tab_default($filename,$varname);
 5270: 	if (defined($pack_def)) { return $pack_def; }
 5271: 
 5272: # ---------------------------------------------------- Any other user namespace
 5273:     } elsif ($realm eq 'environment') {
 5274: # ----------------------------------------------------------------- environment
 5275: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 5276: 	    return $env{'environment.'.$spacequalifierrest};
 5277: 	} else {
 5278: 	    my %returnhash=&userenvironment($udom,$uname,
 5279: 					    $spacequalifierrest);
 5280: 	    return $returnhash{$spacequalifierrest};
 5281: 	}
 5282:     } elsif ($realm eq 'system') {
 5283: # ----------------------------------------------------------------- system.time
 5284: 	if ($space eq 'time') {
 5285: 	    return time;
 5286:         }
 5287:     } elsif ($realm eq 'server') {
 5288: # ----------------------------------------------------------------- system.time
 5289: 	if ($space eq 'name') {
 5290: 	    return $ENV{'SERVER_NAME'};
 5291:         }
 5292:     }
 5293:     return '';
 5294: }
 5295: 
 5296: sub check_group_parms {
 5297:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 5298:     my @groupitems = ();
 5299:     my $resultitem;
 5300:     my @levels = ($symbparm,$mapparm,$what);
 5301:     foreach my $group (@{$groups}) {
 5302:         foreach my $level (@levels) {
 5303:              my $item = $courseid.'.['.$group.'].'.$level;
 5304:              push(@groupitems,$item);
 5305:         }
 5306:     }
 5307:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 5308:                             $env{'course.'.$courseid.'.domain'},
 5309:                                      'course',@groupitems);
 5310:     return $coursereply;
 5311: }
 5312: 
 5313: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 5314:     my ($courseid,@groups) = @_;
 5315:     @groups = sort(@groups);
 5316:     return @groups;
 5317: }
 5318: 
 5319: sub packages_tab_default {
 5320:     my ($uri,$varname)=@_;
 5321:     my (undef,$part,$name)=split(/\./,$varname);
 5322:     my $packages=&metadata($uri,'packages');
 5323:     foreach my $package (split(/,/,$packages)) {
 5324: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 5325: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 5326: 	    return $packagetab{"$pack_type&$name&default"};
 5327: 	}
 5328: 	if ($pack_type eq 'part') { $pack_part='0'; }
 5329: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 5330: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 5331: 	}
 5332:     }
 5333:     return undef;
 5334: }
 5335: 
 5336: sub add_prefix_and_part {
 5337:     my ($prefix,$part)=@_;
 5338:     my $keyroot;
 5339:     if (defined($prefix) && $prefix !~ /^__/) {
 5340: 	# prefix that has a part already
 5341: 	$keyroot=$prefix;
 5342:     } elsif (defined($prefix)) {
 5343: 	# prefix that is missing a part
 5344: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 5345:     } else {
 5346: 	# no prefix at all
 5347: 	if (defined($part)) { $keyroot='_'.$part; }
 5348:     }
 5349:     return $keyroot;
 5350: }
 5351: 
 5352: # ---------------------------------------------------------------- Get metadata
 5353: 
 5354: my %metaentry;
 5355: sub metadata {
 5356:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 5357:     $uri=&declutter($uri);
 5358:     # if it is a non metadata possible uri return quickly
 5359:     if (($uri eq '') || 
 5360: 	(($uri =~ m|^/*adm/|) && 
 5361: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 5362:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
 5363: 	($uri =~ m|home/[^/]+/public_html/|)) {
 5364: 	return undef;
 5365:     }
 5366:     my $filename=$uri;
 5367:     $uri=~s/\.meta$//;
 5368: #
 5369: # Is the metadata already cached?
 5370: # Look at timestamp of caching
 5371: # Everything is cached by the main uri, libraries are never directly cached
 5372: #
 5373:     if (!defined($liburi)) {
 5374: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 5375: 	if (defined($cached)) { return $result->{':'.$what}; }
 5376:     }
 5377:     {
 5378: #
 5379: # Is this a recursive call for a library?
 5380: #
 5381: #	if (! exists($metacache{$uri})) {
 5382: #	    $metacache{$uri}={};
 5383: #	}
 5384:         if ($liburi) {
 5385: 	    $liburi=&declutter($liburi);
 5386:             $filename=$liburi;
 5387:         } else {
 5388: 	    &devalidate_cache_new('meta',$uri);
 5389: 	    undef(%metaentry);
 5390: 	}
 5391:         my %metathesekeys=();
 5392:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 5393: 	my $metastring;
 5394: 	if ($uri !~ m -^(uploaded|editupload)/-) {
 5395: 	    my $file=&filelocation('',&clutter($filename));
 5396: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 5397: 	    $metastring=&getfile($file);
 5398: 	}
 5399:         my $parser=HTML::LCParser->new(\$metastring);
 5400:         my $token;
 5401:         undef %metathesekeys;
 5402:         while ($token=$parser->get_token) {
 5403: 	    if ($token->[0] eq 'S') {
 5404: 		if (defined($token->[2]->{'package'})) {
 5405: #
 5406: # This is a package - get package info
 5407: #
 5408: 		    my $package=$token->[2]->{'package'};
 5409: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 5410: 		    if (defined($token->[2]->{'id'})) { 
 5411: 			$keyroot.='_'.$token->[2]->{'id'}; 
 5412: 		    }
 5413: 		    if ($metaentry{':packages'}) {
 5414: 			$metaentry{':packages'}.=','.$package.$keyroot;
 5415: 		    } else {
 5416: 			$metaentry{':packages'}=$package.$keyroot;
 5417: 		    }
 5418: 		    foreach (sort keys %packagetab) {
 5419: 			my $part=$keyroot;
 5420: 			$part=~s/^\_//;
 5421: 			if ($_=~/^\Q$package\E\&/ || 
 5422: 			    $_=~/^\Q$package\E_0\&/) {
 5423: 			    my ($pack,$name,$subp)=split(/\&/,$_);
 5424: 			    # ignore package.tab specified default values
 5425:                             # here &package_tab_default() will fetch those
 5426: 			    if ($subp eq 'default') { next; }
 5427: 			    my $value=$packagetab{$_};
 5428: 			    my $unikey;
 5429: 			    if ($pack =~ /_0$/) {
 5430: 				$unikey='parameter_0_'.$name;
 5431: 				$part=0;
 5432: 			    } else {
 5433: 				$unikey='parameter'.$keyroot.'_'.$name;
 5434: 			    }
 5435: 			    if ($subp eq 'display') {
 5436: 				$value.=' [Part: '.$part.']';
 5437: 			    }
 5438: 			    $metaentry{':'.$unikey.'.part'}=$part;
 5439: 			    $metathesekeys{$unikey}=1;
 5440: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 5441: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 5442: 			    }
 5443: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 5444: 				$metaentry{':'.$unikey}=
 5445: 				    $metaentry{':'.$unikey.'.default'};
 5446: 			    }
 5447: 			}
 5448: 		    }
 5449: 		} else {
 5450: #
 5451: # This is not a package - some other kind of start tag
 5452: #
 5453: 		    my $entry=$token->[1];
 5454: 		    my $unikey;
 5455: 		    if ($entry eq 'import') {
 5456: 			$unikey='';
 5457: 		    } else {
 5458: 			$unikey=$entry;
 5459: 		    }
 5460: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 5461: 
 5462: 		    if (defined($token->[2]->{'id'})) { 
 5463: 			$unikey.='_'.$token->[2]->{'id'}; 
 5464: 		    }
 5465: 
 5466: 		    if ($entry eq 'import') {
 5467: #
 5468: # Importing a library here
 5469: #
 5470: 			if ($depthcount<20) {
 5471: 			    my $location=$parser->get_text('/import');
 5472: 			    my $dir=$filename;
 5473: 			    $dir=~s|[^/]*$||;
 5474: 			    $location=&filelocation($dir,$location);
 5475: 			    foreach (sort(split(/\,/,&metadata($uri,'keys',
 5476: 							       $location,$unikey,
 5477: 							       $depthcount+1)))) {
 5478: 				$metaentry{':'.$_}=$metaentry{':'.$_};
 5479: 				$metathesekeys{$_}=1;
 5480: 			    }
 5481: 			}
 5482: 		    } else { 
 5483: 			
 5484: 			if (defined($token->[2]->{'name'})) { 
 5485: 			    $unikey.='_'.$token->[2]->{'name'}; 
 5486: 			}
 5487: 			$metathesekeys{$unikey}=1;
 5488: 			foreach (@{$token->[3]}) {
 5489: 			    $metaentry{':'.$unikey.'.'.$_}=$token->[2]->{$_};
 5490: 			}
 5491: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 5492: 			my $default=$metaentry{':'.$unikey.'.default'};
 5493: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 5494: 		 # only ws inside the tag, and not in default, so use default
 5495: 		 # as value
 5496: 			    $metaentry{':'.$unikey}=$default;
 5497: 			} else {
 5498: 		  # either something interesting inside the tag or default
 5499:                   # uninteresting
 5500: 			    $metaentry{':'.$unikey}=$internaltext;
 5501: 			}
 5502: # end of not-a-package not-a-library import
 5503: 		    }
 5504: # end of not-a-package start tag
 5505: 		}
 5506: # the next is the end of "start tag"
 5507: 	    }
 5508: 	}
 5509: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 5510: 	foreach my $key (sort(keys(%packagetab))) {
 5511: 	    #no specific packages #how's our extension
 5512: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 5513: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 5514: 					 \%metathesekeys);
 5515: 	}
 5516: 	if (!exists($metaentry{':packages'})) {
 5517: 	    foreach my $key (sort(keys(%packagetab))) {
 5518: 		#no specific packages well let's get default then
 5519: 		if ($key!~/^default&/) { next; }
 5520: 		&metadata_create_package_def($uri,$key,'default',
 5521: 					     \%metathesekeys);
 5522: 	    }
 5523: 	}
 5524: # are there custom rights to evaluate
 5525: 	if ($metaentry{':copyright'} eq 'custom') {
 5526: 
 5527:     #
 5528:     # Importing a rights file here
 5529:     #
 5530: 	    unless ($depthcount) {
 5531: 		my $location=$metaentry{':customdistributionfile'};
 5532: 		my $dir=$filename;
 5533: 		$dir=~s|[^/]*$||;
 5534: 		$location=&filelocation($dir,$location);
 5535: 		foreach (sort(split(/\,/,&metadata($uri,'keys',
 5536: 						   $location,'_rights',
 5537: 						   $depthcount+1)))) {
 5538: 		    #$metaentry{':'.$_}=$metacache{$uri}->{':'.$_};
 5539: 		    $metathesekeys{$_}=1;
 5540: 		}
 5541: 	    }
 5542: 	}
 5543: 	$metaentry{':keys'}=join(',',keys %metathesekeys);
 5544: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 5545: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 5546: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
 5547: # this is the end of "was not already recently cached
 5548:     }
 5549:     return $metaentry{':'.$what};
 5550: }
 5551: 
 5552: sub metadata_create_package_def {
 5553:     my ($uri,$key,$package,$metathesekeys)=@_;
 5554:     my ($pack,$name,$subp)=split(/\&/,$key);
 5555:     if ($subp eq 'default') { next; }
 5556:     
 5557:     if (defined($metaentry{':packages'})) {
 5558: 	$metaentry{':packages'}.=','.$package;
 5559:     } else {
 5560: 	$metaentry{':packages'}=$package;
 5561:     }
 5562:     my $value=$packagetab{$key};
 5563:     my $unikey;
 5564:     $unikey='parameter_0_'.$name;
 5565:     $metaentry{':'.$unikey.'.part'}=0;
 5566:     $$metathesekeys{$unikey}=1;
 5567:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 5568: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 5569:     }
 5570:     if (defined($metaentry{':'.$unikey.'.default'})) {
 5571: 	$metaentry{':'.$unikey}=
 5572: 	    $metaentry{':'.$unikey.'.default'};
 5573:     }
 5574: }
 5575: 
 5576: sub metadata_generate_part0 {
 5577:     my ($metadata,$metacache,$uri) = @_;
 5578:     my %allnames;
 5579:     foreach my $metakey (sort keys %$metadata) {
 5580: 	if ($metakey=~/^parameter\_(.*)/) {
 5581: 	  my $part=$$metacache{':'.$metakey.'.part'};
 5582: 	  my $name=$$metacache{':'.$metakey.'.name'};
 5583: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 5584: 	    $allnames{$name}=$part;
 5585: 	  }
 5586: 	}
 5587:     }
 5588:     foreach my $name (keys(%allnames)) {
 5589:       $$metadata{"parameter_0_$name"}=1;
 5590:       my $key=":parameter_0_$name";
 5591:       $$metacache{"$key.part"}='0';
 5592:       $$metacache{"$key.name"}=$name;
 5593:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 5594: 					   $allnames{$name}.'_'.$name.
 5595: 					   '.type'};
 5596:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 5597: 			     '.display'};
 5598:       my $expr='[Part: '.$allnames{$name}.']';
 5599:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 5600:       $$metacache{"$key.display"}=$olddis;
 5601:     }
 5602: }
 5603: 
 5604: # ------------------------------------------------- Get the title of a resource
 5605: 
 5606: sub gettitle {
 5607:     my $urlsymb=shift;
 5608:     my $symb=&symbread($urlsymb);
 5609:     if ($symb) {
 5610: 	my $key=$env{'request.course.id'}."\0".$symb;
 5611: 	my ($result,$cached)=&is_cached_new('title',$key);
 5612: 	if (defined($cached)) { 
 5613: 	    return $result;
 5614: 	}
 5615: 	my ($map,$resid,$url)=&decode_symb($symb);
 5616: 	my $title='';
 5617: 	my %bighash;
 5618: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5619: 		&GDBM_READER(),0640)) {
 5620: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
 5621: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
 5622: 	    untie %bighash;
 5623: 	}
 5624: 	$title=~s/\&colon\;/\:/gs;
 5625: 	if ($title) {
 5626: 	    return &do_cache_new('title',$key,$title,600);
 5627: 	}
 5628: 	$urlsymb=$url;
 5629:     }
 5630:     my $title=&metadata($urlsymb,'title');
 5631:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 5632:     return $title;
 5633: }
 5634: 
 5635: sub get_slot {
 5636:     my ($which,$cnum,$cdom)=@_;
 5637:     if (!$cnum || !$cdom) {
 5638: 	(undef,my $courseid)=&Apache::lonxml::whichuser();
 5639: 	$cdom=$env{'course.'.$courseid.'.domain'};
 5640: 	$cnum=$env{'course.'.$courseid.'.num'};
 5641:     }
 5642:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 5643:     my %slotinfo;
 5644:     if (exists($remembered{$key})) {
 5645: 	$slotinfo{$which} = $remembered{$key};
 5646:     } else {
 5647: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 5648: 	&Apache::lonhomework::showhash(%slotinfo);
 5649: 	my ($tmp)=keys(%slotinfo);
 5650: 	if ($tmp=~/^error:/) { return (); }
 5651: 	$remembered{$key} = $slotinfo{$which};
 5652:     }
 5653:     if (ref($slotinfo{$which}) eq 'HASH') {
 5654: 	return %{$slotinfo{$which}};
 5655:     }
 5656:     return $slotinfo{$which};
 5657: }
 5658: # ------------------------------------------------- Update symbolic store links
 5659: 
 5660: sub symblist {
 5661:     my ($mapname,%newhash)=@_;
 5662:     $mapname=&deversion(&declutter($mapname));
 5663:     my %hash;
 5664:     if (($env{'request.course.fn'}) && (%newhash)) {
 5665:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 5666:                       &GDBM_WRCREAT(),0640)) {
 5667: 	    foreach my $url (keys %newhash) {
 5668: 		next if ($url eq 'last_known'
 5669: 			 && $env{'form.no_update_last_known'});
 5670: 		$hash{declutter($url)}=&encode_symb($mapname,
 5671: 						    $newhash{$url}->[1],
 5672: 						    $newhash{$url}->[0]);
 5673:             }
 5674:             if (untie(%hash)) {
 5675: 		return 'ok';
 5676:             }
 5677:         }
 5678:     }
 5679:     return 'error';
 5680: }
 5681: 
 5682: # --------------------------------------------------------------- Verify a symb
 5683: 
 5684: sub symbverify {
 5685:     my ($symb,$thisurl)=@_;
 5686:     my $thisfn=$thisurl;
 5687: # wrapper not part of symbs
 5688:     $thisfn=~s/^\/adm\/wrapper//;
 5689:     $thisfn=~s/^\/adm\/coursedocs\/showdoc\///;
 5690:     $thisfn=&declutter($thisfn);
 5691: # direct jump to resource in page or to a sequence - will construct own symbs
 5692:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 5693: # check URL part
 5694:     my ($map,$resid,$url)=&decode_symb($symb);
 5695: 
 5696:     unless ($url eq $thisfn) { return 0; }
 5697: 
 5698:     $symb=&symbclean($symb);
 5699:     $thisurl=&deversion($thisurl);
 5700:     $thisfn=&deversion($thisfn);
 5701: 
 5702:     my %bighash;
 5703:     my $okay=0;
 5704: 
 5705:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5706:                             &GDBM_READER(),0640)) {
 5707:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 5708:         unless ($ids) { 
 5709:            $ids=$bighash{'ids_/'.$thisurl};
 5710:         }
 5711:         if ($ids) {
 5712: # ------------------------------------------------------------------- Has ID(s)
 5713: 	    foreach (split(/\,/,$ids)) {
 5714: 	       my ($mapid,$resid)=split(/\./,$_);
 5715:                if (
 5716:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 5717:    eq $symb) { 
 5718: 		   if (($env{'request.role.adv'}) ||
 5719: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
 5720: 		       $okay=1; 
 5721: 		   }
 5722: 	       }
 5723: 	   }
 5724:         }
 5725: 	untie(%bighash);
 5726:     }
 5727:     return $okay;
 5728: }
 5729: 
 5730: # --------------------------------------------------------------- Clean-up symb
 5731: 
 5732: sub symbclean {
 5733:     my $symb=shift;
 5734:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 5735: # remove version from map
 5736:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 5737: 
 5738: # remove version from URL
 5739:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 5740: 
 5741: # remove wrapper
 5742: 
 5743:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 5744:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 5745:     return $symb;
 5746: }
 5747: 
 5748: # ---------------------------------------------- Split symb to find map and url
 5749: 
 5750: sub encode_symb {
 5751:     my ($map,$resid,$url)=@_;
 5752:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 5753: }
 5754: 
 5755: sub decode_symb {
 5756:     my $symb=shift;
 5757:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 5758:     my ($map,$resid,$url)=split(/___/,$symb);
 5759:     return (&fixversion($map),$resid,&fixversion($url));
 5760: }
 5761: 
 5762: sub fixversion {
 5763:     my $fn=shift;
 5764:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 5765:     my %bighash;
 5766:     my $uri=&clutter($fn);
 5767:     my $key=$env{'request.course.id'}.'_'.$uri;
 5768: # is this cached?
 5769:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 5770:     if (defined($cached)) { return $result; }
 5771: # unfortunately not cached, or expired
 5772:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5773: 	    &GDBM_READER(),0640)) {
 5774:  	if ($bighash{'version_'.$uri}) {
 5775:  	    my $version=$bighash{'version_'.$uri};
 5776:  	    unless (($version eq 'mostrecent') || 
 5777: 		    ($version==&getversion($uri))) {
 5778:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 5779:  	    }
 5780:  	}
 5781:  	untie %bighash;
 5782:     }
 5783:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 5784: }
 5785: 
 5786: sub deversion {
 5787:     my $url=shift;
 5788:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 5789:     return $url;
 5790: }
 5791: 
 5792: # ------------------------------------------------------ Return symb list entry
 5793: 
 5794: sub symbread {
 5795:     my ($thisfn,$donotrecurse)=@_;
 5796:     my $cache_str='request.symbread.cached.'.$thisfn;
 5797:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 5798: # no filename provided? try from environment
 5799:     unless ($thisfn) {
 5800:         if ($env{'request.symb'}) {
 5801: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 5802: 	}
 5803: 	$thisfn=$env{'request.filename'};
 5804:     }
 5805:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 5806: # is that filename actually a symb? Verify, clean, and return
 5807:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 5808: 	if (&symbverify($thisfn,$1)) {
 5809: 	    return $env{$cache_str}=&symbclean($thisfn);
 5810: 	}
 5811:     }
 5812:     $thisfn=declutter($thisfn);
 5813:     my %hash;
 5814:     my %bighash;
 5815:     my $syval='';
 5816:     if (($env{'request.course.fn'}) && ($thisfn)) {
 5817:         my $targetfn = $thisfn;
 5818:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 5819:             $targetfn = 'adm/wrapper/'.$thisfn;
 5820:         }
 5821: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 5822: 	    $targetfn=$1;
 5823: 	}
 5824:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 5825:                       &GDBM_READER(),0640)) {
 5826: 	    $syval=$hash{$targetfn};
 5827:             untie(%hash);
 5828:         }
 5829: # ---------------------------------------------------------- There was an entry
 5830:         if ($syval) {
 5831: 	    #unless ($syval=~/\_\d+$/) {
 5832: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 5833: 		    #&appenv('request.ambiguous' => $thisfn);
 5834: 		    #return $env{$cache_str}='';
 5835: 		#}    
 5836: 		#$syval.=$1;
 5837: 	    #}
 5838:         } else {
 5839: # ------------------------------------------------------- Was not in symb table
 5840:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5841:                             &GDBM_READER(),0640)) {
 5842: # ---------------------------------------------- Get ID(s) for current resource
 5843:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 5844:               unless ($ids) { 
 5845:                  $ids=$bighash{'ids_/'.$thisfn};
 5846:               }
 5847:               unless ($ids) {
 5848: # alias?
 5849: 		  $ids=$bighash{'mapalias_'.$thisfn};
 5850:               }
 5851:               if ($ids) {
 5852: # ------------------------------------------------------------------- Has ID(s)
 5853:                  my @possibilities=split(/\,/,$ids);
 5854:                  if ($#possibilities==0) {
 5855: # ----------------------------------------------- There is only one possibility
 5856: 		     my ($mapid,$resid)=split(/\./,$ids);
 5857: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 5858: 						    $resid,$thisfn);
 5859:                  } elsif (!$donotrecurse) {
 5860: # ------------------------------------------ There is more than one possibility
 5861:                      my $realpossible=0;
 5862:                      foreach (@possibilities) {
 5863: 			 my $file=$bighash{'src_'.$_};
 5864:                          if (&allowed('bre',$file)) {
 5865:          		    my ($mapid,$resid)=split(/\./,$_);
 5866:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 5867: 				$realpossible++;
 5868:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 5869: 						    $resid,$thisfn);
 5870:                             }
 5871: 			 }
 5872:                      }
 5873: 		     if ($realpossible!=1) { $syval=''; }
 5874:                  } else {
 5875:                      $syval='';
 5876:                  }
 5877: 	      }
 5878:               untie(%bighash)
 5879:            }
 5880:         }
 5881:         if ($syval) {
 5882: 	    return $env{$cache_str}=$syval;
 5883:         }
 5884:     }
 5885:     &appenv('request.ambiguous' => $thisfn);
 5886:     return $env{$cache_str}='';
 5887: }
 5888: 
 5889: # ---------------------------------------------------------- Return random seed
 5890: 
 5891: sub numval {
 5892:     my $txt=shift;
 5893:     $txt=~tr/A-J/0-9/;
 5894:     $txt=~tr/a-j/0-9/;
 5895:     $txt=~tr/K-T/0-9/;
 5896:     $txt=~tr/k-t/0-9/;
 5897:     $txt=~tr/U-Z/0-5/;
 5898:     $txt=~tr/u-z/0-5/;
 5899:     $txt=~s/\D//g;
 5900:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 5901:     return int($txt);
 5902: }
 5903: 
 5904: sub numval2 {
 5905:     my $txt=shift;
 5906:     $txt=~tr/A-J/0-9/;
 5907:     $txt=~tr/a-j/0-9/;
 5908:     $txt=~tr/K-T/0-9/;
 5909:     $txt=~tr/k-t/0-9/;
 5910:     $txt=~tr/U-Z/0-5/;
 5911:     $txt=~tr/u-z/0-5/;
 5912:     $txt=~s/\D//g;
 5913:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 5914:     my $total;
 5915:     foreach my $val (@txts) { $total+=$val; }
 5916:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 5917:     return int($total);
 5918: }
 5919: 
 5920: sub numval3 {
 5921:     use integer;
 5922:     my $txt=shift;
 5923:     $txt=~tr/A-J/0-9/;
 5924:     $txt=~tr/a-j/0-9/;
 5925:     $txt=~tr/K-T/0-9/;
 5926:     $txt=~tr/k-t/0-9/;
 5927:     $txt=~tr/U-Z/0-5/;
 5928:     $txt=~tr/u-z/0-5/;
 5929:     $txt=~s/\D//g;
 5930:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 5931:     my $total;
 5932:     foreach my $val (@txts) { $total+=$val; }
 5933:     if ($_64bit) { $total=(($total<<32)>>32); }
 5934:     return $total;
 5935: }
 5936: 
 5937: sub digest {
 5938:     my ($data)=@_;
 5939:     my $digest=&Digest::MD5::md5($data);
 5940:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 5941:     my ($e,$f);
 5942:     {
 5943:         use integer;
 5944:         $e=($a+$b);
 5945:         $f=($c+$d);
 5946:         if ($_64bit) {
 5947:             $e=(($e<<32)>>32);
 5948:             $f=(($f<<32)>>32);
 5949:         }
 5950:     }
 5951:     if (wantarray) {
 5952: 	return ($e,$f);
 5953:     } else {
 5954: 	my $g;
 5955: 	{
 5956: 	    use integer;
 5957: 	    $g=($e+$f);
 5958: 	    if ($_64bit) {
 5959: 		$g=(($g<<32)>>32);
 5960: 	    }
 5961: 	}
 5962: 	return $g;
 5963:     }
 5964: }
 5965: 
 5966: sub latest_rnd_algorithm_id {
 5967:     return '64bit5';
 5968: }
 5969: 
 5970: sub get_rand_alg {
 5971:     my ($courseid)=@_;
 5972:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
 5973:     if ($courseid) {
 5974: 	return $env{"course.$courseid.rndseed"};
 5975:     }
 5976:     return &latest_rnd_algorithm_id();
 5977: }
 5978: 
 5979: sub validCODE {
 5980:     my ($CODE)=@_;
 5981:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 5982:     return 0;
 5983: }
 5984: 
 5985: sub getCODE {
 5986:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 5987:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 5988: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 5989: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 5990: 	return $Apache::lonhomework::history{'resource.CODE'};
 5991:     }
 5992:     return undef;
 5993: }
 5994: 
 5995: sub rndseed {
 5996:     my ($symb,$courseid,$domain,$username)=@_;
 5997: 
 5998:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
 5999:     if (!$symb) {
 6000: 	unless ($symb=$wsymb) { return time; }
 6001:     }
 6002:     if (!$courseid) { $courseid=$wcourseid; }
 6003:     if (!$domain) { $domain=$wdomain; }
 6004:     if (!$username) { $username=$wusername }
 6005:     my $which=&get_rand_alg();
 6006:     if (defined(&getCODE())) {
 6007: 	if ($which eq '64bit5') {
 6008: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 6009: 	} elsif ($which eq '64bit4') {
 6010: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 6011: 	} else {
 6012: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 6013: 	}
 6014:     } elsif ($which eq '64bit5') {
 6015: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 6016:     } elsif ($which eq '64bit4') {
 6017: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 6018:     } elsif ($which eq '64bit3') {
 6019: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 6020:     } elsif ($which eq '64bit2') {
 6021: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 6022:     } elsif ($which eq '64bit') {
 6023: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 6024:     }
 6025:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 6026: }
 6027: 
 6028: sub rndseed_32bit {
 6029:     my ($symb,$courseid,$domain,$username)=@_;
 6030:     {
 6031: 	use integer;
 6032: 	my $symbchck=unpack("%32C*",$symb) << 27;
 6033: 	my $symbseed=numval($symb) << 22;
 6034: 	my $namechck=unpack("%32C*",$username) << 17;
 6035: 	my $nameseed=numval($username) << 12;
 6036: 	my $domainseed=unpack("%32C*",$domain) << 7;
 6037: 	my $courseseed=unpack("%32C*",$courseid);
 6038: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 6039: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6040: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 6041: 	if ($_64bit) { $num=(($num<<32)>>32); }
 6042: 	return $num;
 6043:     }
 6044: }
 6045: 
 6046: sub rndseed_64bit {
 6047:     my ($symb,$courseid,$domain,$username)=@_;
 6048:     {
 6049: 	use integer;
 6050: 	my $symbchck=unpack("%32S*",$symb) << 21;
 6051: 	my $symbseed=numval($symb) << 10;
 6052: 	my $namechck=unpack("%32S*",$username);
 6053: 	
 6054: 	my $nameseed=numval($username) << 21;
 6055: 	my $domainseed=unpack("%32S*",$domain) << 10;
 6056: 	my $courseseed=unpack("%32S*",$courseid);
 6057: 	
 6058: 	my $num1=$symbchck+$symbseed+$namechck;
 6059: 	my $num2=$nameseed+$domainseed+$courseseed;
 6060: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6061: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 6062: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6063: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6064: 	return "$num1,$num2";
 6065:     }
 6066: }
 6067: 
 6068: sub rndseed_64bit2 {
 6069:     my ($symb,$courseid,$domain,$username)=@_;
 6070:     {
 6071: 	use integer;
 6072: 	# strings need to be an even # of cahracters long, it it is odd the
 6073:         # last characters gets thrown away
 6074: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6075: 	my $symbseed=numval($symb) << 10;
 6076: 	my $namechck=unpack("%32S*",$username.' ');
 6077: 	
 6078: 	my $nameseed=numval($username) << 21;
 6079: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6080: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6081: 	
 6082: 	my $num1=$symbchck+$symbseed+$namechck;
 6083: 	my $num2=$nameseed+$domainseed+$courseseed;
 6084: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6085: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 6086: 	return "$num1,$num2";
 6087:     }
 6088: }
 6089: 
 6090: sub rndseed_64bit3 {
 6091:     my ($symb,$courseid,$domain,$username)=@_;
 6092:     {
 6093: 	use integer;
 6094: 	# strings need to be an even # of cahracters long, it it is odd the
 6095:         # last characters gets thrown away
 6096: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6097: 	my $symbseed=numval2($symb) << 10;
 6098: 	my $namechck=unpack("%32S*",$username.' ');
 6099: 	
 6100: 	my $nameseed=numval2($username) << 21;
 6101: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6102: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6103: 	
 6104: 	my $num1=$symbchck+$symbseed+$namechck;
 6105: 	my $num2=$nameseed+$domainseed+$courseseed;
 6106: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6107: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
 6108: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6109: 	
 6110: 	return "$num1:$num2";
 6111:     }
 6112: }
 6113: 
 6114: sub rndseed_64bit4 {
 6115:     my ($symb,$courseid,$domain,$username)=@_;
 6116:     {
 6117: 	use integer;
 6118: 	# strings need to be an even # of cahracters long, it it is odd the
 6119:         # last characters gets thrown away
 6120: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6121: 	my $symbseed=numval3($symb) << 10;
 6122: 	my $namechck=unpack("%32S*",$username.' ');
 6123: 	
 6124: 	my $nameseed=numval3($username) << 21;
 6125: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6126: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6127: 	
 6128: 	my $num1=$symbchck+$symbseed+$namechck;
 6129: 	my $num2=$nameseed+$domainseed+$courseseed;
 6130: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6131: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
 6132: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6133: 	
 6134: 	return "$num1:$num2";
 6135:     }
 6136: }
 6137: 
 6138: sub rndseed_64bit5 {
 6139:     my ($symb,$courseid,$domain,$username)=@_;
 6140:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 6141:     return "$num1:$num2";
 6142: }
 6143: 
 6144: sub rndseed_CODE_64bit {
 6145:     my ($symb,$courseid,$domain,$username)=@_;
 6146:     {
 6147: 	use integer;
 6148: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 6149: 	my $symbseed=numval2($symb);
 6150: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 6151: 	my $CODEseed=numval(&getCODE());
 6152: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6153: 	my $num1=$symbseed+$CODEchck;
 6154: 	my $num2=$CODEseed+$courseseed+$symbchck;
 6155: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 6156: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
 6157: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 6158: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 6159: 	return "$num1:$num2";
 6160:     }
 6161: }
 6162: 
 6163: sub rndseed_CODE_64bit4 {
 6164:     my ($symb,$courseid,$domain,$username)=@_;
 6165:     {
 6166: 	use integer;
 6167: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 6168: 	my $symbseed=numval3($symb);
 6169: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 6170: 	my $CODEseed=numval3(&getCODE());
 6171: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6172: 	my $num1=$symbseed+$CODEchck;
 6173: 	my $num2=$CODEseed+$courseseed+$symbchck;
 6174: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 6175: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
 6176: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 6177: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 6178: 	return "$num1:$num2";
 6179:     }
 6180: }
 6181: 
 6182: sub rndseed_CODE_64bit5 {
 6183:     my ($symb,$courseid,$domain,$username)=@_;
 6184:     my $code = &getCODE();
 6185:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 6186:     return "$num1:$num2";
 6187: }
 6188: 
 6189: sub setup_random_from_rndseed {
 6190:     my ($rndseed)=@_;
 6191:     if ($rndseed =~/([,:])/) {
 6192: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 6193: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 6194:     } else {
 6195: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 6196:     }
 6197: }
 6198: 
 6199: sub latest_receipt_algorithm_id {
 6200:     return 'receipt2';
 6201: }
 6202: 
 6203: sub recunique {
 6204:     my $fucourseid=shift;
 6205:     my $unique;
 6206:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 6207: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 6208:     } else {
 6209: 	$unique=$perlvar{'lonReceipt'};
 6210:     }
 6211:     return unpack("%32C*",$unique);
 6212: }
 6213: 
 6214: sub recprefix {
 6215:     my $fucourseid=shift;
 6216:     my $prefix;
 6217:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 6218: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 6219:     } else {
 6220: 	$prefix=$perlvar{'lonHostID'};
 6221:     }
 6222:     return unpack("%32C*",$prefix);
 6223: }
 6224: 
 6225: sub ireceipt {
 6226:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 6227:     my $cuname=unpack("%32C*",$funame);
 6228:     my $cudom=unpack("%32C*",$fudom);
 6229:     my $cucourseid=unpack("%32C*",$fucourseid);
 6230:     my $cusymb=unpack("%32C*",$fusymb);
 6231:     my $cunique=&recunique($fucourseid);
 6232:     my $cpart=unpack("%32S*",$part);
 6233:     my $return =&recprefix($fucourseid).'-';
 6234:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 6235: 	$env{'request.state'} eq 'construct') {
 6236: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
 6237: 			       " and ".($cpart%$cudom));
 6238: 			       
 6239: 	$return.= ($cunique%$cuname+
 6240: 		   $cunique%$cudom+
 6241: 		   $cusymb%$cuname+
 6242: 		   $cusymb%$cudom+
 6243: 		   $cucourseid%$cuname+
 6244: 		   $cucourseid%$cudom+
 6245: 		   $cpart%$cuname+
 6246: 		   $cpart%$cudom);
 6247:     } else {
 6248: 	$return.= ($cunique%$cuname+
 6249: 		   $cunique%$cudom+
 6250: 		   $cusymb%$cuname+
 6251: 		   $cusymb%$cudom+
 6252: 		   $cucourseid%$cuname+
 6253: 		   $cucourseid%$cudom);
 6254:     }
 6255:     return $return;
 6256: }
 6257: 
 6258: sub receipt {
 6259:     my ($part)=@_;
 6260:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
 6261:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 6262: }
 6263: 
 6264: # ------------------------------------------------------------ Serves up a file
 6265: # returns either the contents of the file or 
 6266: # -1 if the file doesn't exist
 6267: #
 6268: # if the target is a file that was uploaded via DOCS, 
 6269: # a check will be made to see if a current copy exists on the local server,
 6270: # if it does this will be served, otherwise a copy will be retrieved from
 6271: # the home server for the course and stored in /home/httpd/html/userfiles on
 6272: # the local server.   
 6273: 
 6274: sub getfile {
 6275:     my ($file) = @_;
 6276:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 6277:     &repcopy($file);
 6278:     return &readfile($file);
 6279: }
 6280: 
 6281: sub repcopy_userfile {
 6282:     my ($file)=@_;
 6283:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 6284:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 6285:     my ($cdom,$cnum,$filename) = 
 6286: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
 6287:     my ($info,$rtncode);
 6288:     my $uri="/uploaded/$cdom/$cnum/$filename";
 6289:     if (-e "$file") {
 6290: 	my @fileinfo = stat($file);
 6291: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 6292: 	if ($lwpresp ne 'ok') {
 6293: 	    if ($rtncode eq '404') {
 6294: 		unlink($file);
 6295: 	    }
 6296: 	    #my $ua=new LWP::UserAgent;
 6297: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
 6298: 	    #my $response=$ua->request($request);
 6299: 	    #if ($response->is_success()) {
 6300: 	#	return $response->content;
 6301: 	#    } else {
 6302: 	#	return -1;
 6303: 	#    }
 6304: 	    return -1;
 6305: 	}
 6306: 	if ($info < $fileinfo[9]) {
 6307: 	    return 'ok';
 6308: 	}
 6309: 	$info = '';
 6310: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
 6311: 	if ($lwpresp ne 'ok') {
 6312: 	    return -1;
 6313: 	}
 6314:     } else {
 6315: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
 6316: 	if ($lwpresp ne 'ok') {
 6317: 	    my $ua=new LWP::UserAgent;
 6318: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
 6319: 	    my $response=$ua->request($request);
 6320: 	    if ($response->is_success()) {
 6321: 		$info=$response->content;
 6322: 	    } else {
 6323: 		return -1;
 6324: 	    }
 6325: 	}
 6326: 	my @parts = ($cdom,$cnum); 
 6327: 	if ($filename =~ m|^(.+)/[^/]+$|) {
 6328: 	    push @parts, split(/\//,$1);
 6329: 	}
 6330: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 6331: 	foreach my $part (@parts) {
 6332: 	    $path .= '/'.$part;
 6333: 	    if (!-e $path) {
 6334: 		mkdir($path,0770);
 6335: 	    }
 6336: 	}
 6337:     }
 6338:     open(FILE,">$file");
 6339:     print FILE $info;
 6340:     close(FILE);
 6341:     return 'ok';
 6342: }
 6343: 
 6344: sub tokenwrapper {
 6345:     my $uri=shift;
 6346:     $uri=~s|^http\://([^/]+)||;
 6347:     $uri=~s|^/||;
 6348:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 6349:     my $token=$1;
 6350:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 6351:     if ($udom && $uname && $file) {
 6352: 	$file=~s|(\?\.*)*$||;
 6353:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
 6354:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
 6355:                (($uri=~/\?/)?'&':'?').'token='.$token.
 6356:                                '&tokenissued='.$perlvar{'lonHostID'};
 6357:     } else {
 6358:         return '/adm/notfound.html';
 6359:     }
 6360: }
 6361: 
 6362: sub getuploaded {
 6363:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 6364:     $uri=~s/^\///;
 6365:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
 6366:     my $ua=new LWP::UserAgent;
 6367:     my $request=new HTTP::Request($reqtype,$uri);
 6368:     my $response=$ua->request($request);
 6369:     $$rtncode = $response->code;
 6370:     if (! $response->is_success()) {
 6371: 	return 'failed';
 6372:     }      
 6373:     if ($reqtype eq 'HEAD') {
 6374: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 6375:     } elsif ($reqtype eq 'GET') {
 6376: 	$$info = $response->content;
 6377:     }
 6378:     return 'ok';
 6379: }
 6380: 
 6381: sub readfile {
 6382:     my $file = shift;
 6383:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 6384:     my $fh;
 6385:     open($fh,"<$file");
 6386:     my $a='';
 6387:     while (<$fh>) { $a .=$_; }
 6388:     return $a;
 6389: }
 6390: 
 6391: sub filelocation {
 6392:     my ($dir,$file) = @_;
 6393:     my $location;
 6394:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 6395: 
 6396:     if ($file =~ m-^/adm/-) {
 6397: 	$file=~s-^/adm/wrapper/-/-;
 6398: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 6399:     }
 6400:     if ($file=~m:^/~:) { # is a contruction space reference
 6401:         $location = $file;
 6402:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 6403:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
 6404: 	# is a correct contruction space reference
 6405:         $location = $file;
 6406:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 6407:         my ($udom,$uname,$filename)=
 6408:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
 6409:         my $home=&homeserver($uname,$udom);
 6410:         my $is_me=0;
 6411:         my @ids=&current_machine_ids();
 6412:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 6413:         if ($is_me) {
 6414:   	    $location=&Apache::loncommon::propath($udom,$uname).
 6415:   	      '/userfiles/'.$filename;
 6416:         } else {
 6417:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 6418:   	      $udom.'/'.$uname.'/'.$filename;
 6419:         }
 6420:     } else {
 6421:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 6422:         $file=~s:^/res/:/:;
 6423:         if ( !( $file =~ m:^/:) ) {
 6424:             $location = $dir. '/'.$file;
 6425:         } else {
 6426:             $location = '/home/httpd/html/res'.$file;
 6427:         }
 6428:     }
 6429:     $location=~s://+:/:g; # remove duplicate /
 6430:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 6431:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 6432:     return $location;
 6433: }
 6434: 
 6435: sub hreflocation {
 6436:     my ($dir,$file)=@_;
 6437:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 6438: 	$file=filelocation($dir,$file);
 6439:     } elsif ($file=~m-^/adm/-) {
 6440: 	$file=~s-^/adm/wrapper/-/-;
 6441: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 6442:     }
 6443:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 6444: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 6445:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
 6446: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
 6447:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 6448: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
 6449: 	    -/uploaded/$1/$2/-x;
 6450:     }
 6451:     return $file;
 6452: }
 6453: 
 6454: sub current_machine_domains {
 6455:     my $hostname=$hostname{$perlvar{'lonHostID'}};
 6456:     my @domains;
 6457:     while( my($id, $name) = each(%hostname)) {
 6458: #	&logthis("-$id-$name-$hostname-");
 6459: 	if ($hostname eq $name) {
 6460: 	    push(@domains,$hostdom{$id});
 6461: 	}
 6462:     }
 6463:     return @domains;
 6464: }
 6465: 
 6466: sub current_machine_ids {
 6467:     my $hostname=$hostname{$perlvar{'lonHostID'}};
 6468:     my @ids;
 6469:     while( my($id, $name) = each(%hostname)) {
 6470: #	&logthis("-$id-$name-$hostname-");
 6471: 	if ($hostname eq $name) {
 6472: 	    push(@ids,$id);
 6473: 	}
 6474:     }
 6475:     return @ids;
 6476: }
 6477: 
 6478: # ------------------------------------------------------------- Declutters URLs
 6479: 
 6480: sub declutter {
 6481:     my $thisfn=shift;
 6482:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 6483:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 6484:     $thisfn=~s/^\///;
 6485:     $thisfn=~s|^adm/wrapper/||;
 6486:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 6487:     $thisfn=~s/^res\///;
 6488:     $thisfn=~s/\?.+$//;
 6489:     return $thisfn;
 6490: }
 6491: 
 6492: # ------------------------------------------------------------- Clutter up URLs
 6493: 
 6494: sub clutter {
 6495:     my $thisfn='/'.&declutter(shift);
 6496:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
 6497:        $thisfn='/res'.$thisfn; 
 6498:     }
 6499:     if ($thisfn !~m|/adm|) {
 6500: 	if ($thisfn =~ m|/ext/|) {
 6501: 	    $thisfn='/adm/wrapper'.$thisfn;
 6502: 	} else {
 6503: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 6504: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 6505: 	    if ($embstyle eq 'ssi'
 6506: 		|| ($embstyle eq 'hdn')
 6507: 		|| ($embstyle eq 'rat')
 6508: 		|| ($embstyle eq 'prv')
 6509: 		|| ($embstyle eq 'ign')) {
 6510: 		#do nothing with these
 6511: 	    } elsif (($embstyle eq 'img') 
 6512: 		|| ($embstyle eq 'emb')
 6513: 		|| ($embstyle eq 'wrp')) {
 6514: 		$thisfn='/adm/wrapper'.$thisfn;
 6515: 	    } elsif ($embstyle eq 'unk'
 6516: 		     && $thisfn!~/\.(sequence|page)$/) {
 6517: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 6518: 	    } else {
 6519: #		&logthis("Got a blank emb style");
 6520: 	    }
 6521: 	}
 6522:     }
 6523:     return $thisfn;
 6524: }
 6525: 
 6526: sub freeze_escape {
 6527:     my ($value)=@_;
 6528:     if (ref($value)) {
 6529: 	$value=&nfreeze($value);
 6530: 	return '__FROZEN__'.&escape($value);
 6531:     }
 6532:     return &escape($value);
 6533: }
 6534: 
 6535: # -------------------------------------------------------- Escape Special Chars
 6536: 
 6537: sub escape {
 6538:     my $str=shift;
 6539:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
 6540:     return $str;
 6541: }
 6542: 
 6543: # ----------------------------------------------------- Un-Escape Special Chars
 6544: 
 6545: sub unescape {
 6546:     my $str=shift;
 6547:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 6548:     return $str;
 6549: }
 6550: 
 6551: sub thaw_unescape {
 6552:     my ($value)=@_;
 6553:     if ($value =~ /^__FROZEN__/) {
 6554: 	substr($value,0,10,undef);
 6555: 	$value=&unescape($value);
 6556: 	return &thaw($value);
 6557:     }
 6558:     return &unescape($value);
 6559: }
 6560: 
 6561: sub correct_line_ends {
 6562:     my ($result)=@_;
 6563:     $$result =~s/\r\n/\n/mg;
 6564:     $$result =~s/\r/\n/mg;
 6565: }
 6566: # ================================================================ Main Program
 6567: 
 6568: sub goodbye {
 6569:    &logthis("Starting Shut down");
 6570: #not converted to using infrastruture and probably shouldn't be
 6571:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
 6572: #converted
 6573: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 6574:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
 6575: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
 6576: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
 6577: #1.1 only
 6578: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
 6579: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
 6580: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
 6581: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
 6582:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 6583:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 6584:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 6585:    &flushcourselogs();
 6586:    &logthis("Shutting down");
 6587: }
 6588: 
 6589: BEGIN {
 6590: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 6591:     unless ($readit) {
 6592: {
 6593:     # FIXME: Use LONCAPA::Configuration::read_conf here and omit next block
 6594:     open(my $config,"</etc/httpd/conf/loncapa.conf");
 6595: 
 6596:     while (my $configline=<$config>) {
 6597:         if ($configline=~/\S/ && $configline =~ /^[^\#]*PerlSetVar/) {
 6598: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 6599:            chomp($varvalue);
 6600:            $perlvar{$varname}=$varvalue;
 6601:         }
 6602:     }
 6603:     close($config);
 6604: }
 6605: {
 6606:     open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
 6607: 
 6608:     while (my $configline=<$config>) {
 6609:         if ($configline =~ /^[^\#]*PerlSetVar/) {
 6610: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 6611:            chomp($varvalue);
 6612:            $perlvar{$varname}=$varvalue;
 6613:         }
 6614:     }
 6615:     close($config);
 6616: }
 6617: 
 6618: # ------------------------------------------------------------ Read domain file
 6619: {
 6620:     %domaindescription = ();
 6621:     %domain_auth_def = ();
 6622:     %domain_auth_arg_def = ();
 6623:     my $fh;
 6624:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
 6625:        while (<$fh>) {
 6626:            next if (/^(\#|\s*$)/);
 6627: #           next if /^\#/;
 6628:            chomp;
 6629:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
 6630: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$_);
 6631: 	   $domain_auth_def{$domain}=$def_auth;
 6632:            $domain_auth_arg_def{$domain}=$def_auth_arg;
 6633: 	   $domaindescription{$domain}=$domain_description;
 6634: 	   $domain_lang_def{$domain}=$def_lang;
 6635: 	   $domain_city{$domain}=$city;
 6636: 	   $domain_longi{$domain}=$longi;
 6637: 	   $domain_lati{$domain}=$lati;
 6638:            $domain_primary{$domain}=$primary;
 6639: 
 6640:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
 6641: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
 6642: 	}
 6643:     }
 6644:     close ($fh);
 6645: }
 6646: 
 6647: 
 6648: # ------------------------------------------------------------- Read hosts file
 6649: {
 6650:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 6651: 
 6652:     while (my $configline=<$config>) {
 6653:        next if ($configline =~ /^(\#|\s*$)/);
 6654:        chomp($configline);
 6655:        my ($id,$domain,$role,$name)=split(/:/,$configline);
 6656:        $name=~s/\s//g;
 6657:        if ($id && $domain && $role && $name) {
 6658: 	 $hostname{$id}=$name;
 6659: 	 $hostdom{$id}=$domain;
 6660: 	 if ($role eq 'library') { $libserv{$id}=$name; }
 6661:        }
 6662:     }
 6663:     close($config);
 6664:     # FIXME: dev server don't want this, production servers _do_ want this
 6665:     #&get_iphost();
 6666: }
 6667: 
 6668: sub get_iphost {
 6669:     if (%iphost) { return %iphost; }
 6670:     my %name_to_ip;
 6671:     foreach my $id (keys(%hostname)) {
 6672: 	my $name=$hostname{$id};
 6673: 	my $ip;
 6674: 	if (!exists($name_to_ip{$name})) {
 6675: 	    $ip = gethostbyname($name);
 6676: 	    if (!$ip || length($ip) ne 4) {
 6677: 		&logthis("Skipping host $id name $name no IP found\n");
 6678: 		next;
 6679: 	    }
 6680: 	    $ip=inet_ntoa($ip);
 6681: 	    $name_to_ip{$name} = $ip;
 6682: 	} else {
 6683: 	    $ip = $name_to_ip{$name};
 6684: 	}
 6685: 	push(@{$iphost{$ip}},$id);
 6686:     }
 6687:     return %iphost;
 6688: }
 6689: 
 6690: # ------------------------------------------------------ Read spare server file
 6691: {
 6692:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 6693: 
 6694:     while (my $configline=<$config>) {
 6695:        chomp($configline);
 6696:        if ($configline) {
 6697:           $spareid{$configline}=1;
 6698:        }
 6699:     }
 6700:     close($config);
 6701: }
 6702: # ------------------------------------------------------------ Read permissions
 6703: {
 6704:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 6705: 
 6706:     while (my $configline=<$config>) {
 6707: 	chomp($configline);
 6708: 	if ($configline) {
 6709: 	    my ($role,$perm)=split(/ /,$configline);
 6710: 	    if ($perm ne '') { $pr{$role}=$perm; }
 6711: 	}
 6712:     }
 6713:     close($config);
 6714: }
 6715: 
 6716: # -------------------------------------------- Read plain texts for permissions
 6717: {
 6718:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 6719: 
 6720:     while (my $configline=<$config>) {
 6721: 	chomp($configline);
 6722: 	if ($configline) {
 6723: 	    my ($short,$plain)=split(/:/,$configline);
 6724: 	    if ($plain ne '') { $prp{$short}=$plain; }
 6725: 	}
 6726:     }
 6727:     close($config);
 6728: }
 6729: 
 6730: # ---------------------------------------------------------- Read package table
 6731: {
 6732:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 6733: 
 6734:     while (my $configline=<$config>) {
 6735: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 6736: 	chomp($configline);
 6737: 	my ($short,$plain)=split(/:/,$configline);
 6738: 	my ($pack,$name)=split(/\&/,$short);
 6739: 	if ($plain ne '') {
 6740: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 6741: 	    $packagetab{$short}=$plain; 
 6742: 	}
 6743:     }
 6744:     close($config);
 6745: }
 6746: 
 6747: # ------------- set up temporary directory
 6748: {
 6749:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 6750: 
 6751: }
 6752: 
 6753: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
 6754: 
 6755: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 6756: $dumpcount=0;
 6757: 
 6758: &logtouch();
 6759: &logthis('<font color="yellow">INFO: Read configuration</font>');
 6760: $readit=1;
 6761:     {
 6762: 	use integer;
 6763: 	my $test=(2**32)+1;
 6764: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 6765: 	&logthis(" Detected 64bit platform ($_64bit)");
 6766:     }
 6767: }
 6768: }
 6769: 
 6770: 1;
 6771: __END__
 6772: 
 6773: =pod
 6774: 
 6775: =head1 NAME
 6776: 
 6777: Apache::lonnet - Subroutines to ask questions about things in the network.
 6778: 
 6779: =head1 SYNOPSIS
 6780: 
 6781: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 6782: 
 6783:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 6784: 
 6785: Common parameters:
 6786: 
 6787: =over 4
 6788: 
 6789: =item *
 6790: 
 6791: $uname : an internal username (if $cname expecting a course Id specifically)
 6792: 
 6793: =item *
 6794: 
 6795: $udom : a domain (if $cdom expecting a course's domain specifically)
 6796: 
 6797: =item *
 6798: 
 6799: $symb : a resource instance identifier
 6800: 
 6801: =item *
 6802: 
 6803: $namespace : the name of a .db file that contains the data needed or
 6804: being set.
 6805: 
 6806: =back
 6807: 
 6808: =head1 OVERVIEW
 6809: 
 6810: lonnet provides subroutines which interact with the
 6811: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 6812: about classes, users, and resources.
 6813: 
 6814: For many of these objects you can also use this to store data about
 6815: them or modify them in various ways.
 6816: 
 6817: =head2 Symbs
 6818: 
 6819: To identify a specific instance of a resource, LON-CAPA uses symbols
 6820: or "symbs"X<symb>. These identifiers are built from the URL of the
 6821: map, the resource number of the resource in the map, and the URL of
 6822: the resource itself. The latter is somewhat redundant, but might help
 6823: if maps change.
 6824: 
 6825: An example is
 6826: 
 6827:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 6828: 
 6829: The respective map entry is
 6830: 
 6831:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 6832:   title="Problem 2">
 6833:  </resource>
 6834: 
 6835: Symbs are used by the random number generator, as well as to store and
 6836: restore data specific to a certain instance of for example a problem.
 6837: 
 6838: =head2 Storing And Retrieving Data
 6839: 
 6840: X<store()>X<cstore()>X<restore()>Three of the most important functions
 6841: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 6842: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 6843: is is the non-critical message twin of cstore. These functions are for
 6844: handlers to store a perl hash to a user's permanent data space in an
 6845: easy manner, and to retrieve it again on another call. It is expected
 6846: that a handler would use this once at the beginning to retrieve data,
 6847: and then again once at the end to send only the new data back.
 6848: 
 6849: The data is stored in the user's data directory on the user's
 6850: homeserver under the ID of the course.
 6851: 
 6852: The hash that is returned by restore will have all of the previous
 6853: value for all of the elements of the hash.
 6854: 
 6855: Example:
 6856: 
 6857:  #creating a hash
 6858:  my %hash;
 6859:  $hash{'foo'}='bar';
 6860: 
 6861:  #storing it
 6862:  &Apache::lonnet::cstore(\%hash);
 6863: 
 6864:  #changing a value
 6865:  $hash{'foo'}='notbar';
 6866: 
 6867:  #adding a new value
 6868:  $hash{'bar'}='foo';
 6869:  &Apache::lonnet::cstore(\%hash);
 6870: 
 6871:  #retrieving the hash
 6872:  my %history=&Apache::lonnet::restore();
 6873: 
 6874:  #print the hash
 6875:  foreach my $key (sort(keys(%history))) {
 6876:    print("\%history{$key} = $history{$key}");
 6877:  }
 6878: 
 6879: Will print out:
 6880: 
 6881:  %history{1:foo} = bar
 6882:  %history{1:keys} = foo:timestamp
 6883:  %history{1:timestamp} = 990455579
 6884:  %history{2:bar} = foo
 6885:  %history{2:foo} = notbar
 6886:  %history{2:keys} = foo:bar:timestamp
 6887:  %history{2:timestamp} = 990455580
 6888:  %history{bar} = foo
 6889:  %history{foo} = notbar
 6890:  %history{timestamp} = 990455580
 6891:  %history{version} = 2
 6892: 
 6893: Note that the special hash entries C<keys>, C<version> and
 6894: C<timestamp> were added to the hash. C<version> will be equal to the
 6895: total number of versions of the data that have been stored. The
 6896: C<timestamp> attribute will be the UNIX time the hash was
 6897: stored. C<keys> is available in every historical section to list which
 6898: keys were added or changed at a specific historical revision of a
 6899: hash.
 6900: 
 6901: B<Warning>: do not store the hash that restore returns directly. This
 6902: will cause a mess since it will restore the historical keys as if the
 6903: were new keys. I.E. 1:foo will become 1:1:foo etc.
 6904: 
 6905: Calling convention:
 6906: 
 6907:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 6908:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 6909: 
 6910: For more detailed information, see lonnet specific documentation.
 6911: 
 6912: =head1 RETURN MESSAGES
 6913: 
 6914: =over 4
 6915: 
 6916: =item * B<con_lost>: unable to contact remote host
 6917: 
 6918: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 6919: when the connection is brought back up
 6920: 
 6921: =item * B<con_failed>: unable to contact remote host and unable to save message
 6922: for later delivery
 6923: 
 6924: =item * B<error:>: an error a occured, a description of the error follows the :
 6925: 
 6926: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 6927: that was requested
 6928: 
 6929: =back
 6930: 
 6931: =head1 PUBLIC SUBROUTINES
 6932: 
 6933: =head2 Session Environment Functions
 6934: 
 6935: =over 4
 6936: 
 6937: =item * 
 6938: X<appenv()>
 6939: B<appenv(%hash)>: the value of %hash is written to
 6940: the user envirnoment file, and will be restored for each access this
 6941: user makes during this session, also modifies the %env for the current
 6942: process
 6943: 
 6944: =item *
 6945: X<delenv()>
 6946: B<delenv($regexp)>: removes all items from the session
 6947: environment file that matches the regular expression in $regexp. The
 6948: values are also delted from the current processes %env.
 6949: 
 6950: =back
 6951: 
 6952: =head2 User Information
 6953: 
 6954: =over 4
 6955: 
 6956: =item *
 6957: X<queryauthenticate()>
 6958: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 6959: authentication scheme
 6960: 
 6961: =item *
 6962: X<authenticate()>
 6963: B<authenticate($uname,$upass,$udom)>: try to
 6964: authenticate user from domain's lib servers (first use the current
 6965: one). C<$upass> should be the users password.
 6966: 
 6967: =item *
 6968: X<homeserver()>
 6969: B<homeserver($uname,$udom)>: find the server which has
 6970: the user's directory and files (there must be only one), this caches
 6971: the answer, and also caches if there is a borken connection.
 6972: 
 6973: =item *
 6974: X<idget()>
 6975: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 6976: (IDs are a unique resource in a domain, there must be only 1 ID per
 6977: username, and only 1 username per ID in a specific domain) (returns
 6978: hash: id=>name,id=>name)
 6979: 
 6980: =item *
 6981: X<idrget()>
 6982: B<idrget($udom,@unames)>: find the IDs behind a list of
 6983: usernames (returns hash: name=>id,name=>id)
 6984: 
 6985: =item *
 6986: X<idput()>
 6987: B<idput($udom,%ids)>: store away a list of names and associated IDs
 6988: 
 6989: =item *
 6990: X<rolesinit()>
 6991: B<rolesinit($udom,$username,$authhost)>: get user privileges
 6992: 
 6993: =item *
 6994: X<getsection()>
 6995: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 6996: course $cname, return section name/number or '' for "not in course"
 6997: and '-1' for "no section"
 6998: 
 6999: =item *
 7000: X<userenvironment()>
 7001: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 7002: passed in @what from the requested user's environment, returns a hash
 7003: 
 7004: =back
 7005: 
 7006: =head2 User Roles
 7007: 
 7008: =over 4
 7009: 
 7010: =item *
 7011: 
 7012: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
 7013: actions
 7014:  F: full access
 7015:  U,I,K: authentication modes (cxx only)
 7016:  '': forbidden
 7017:  1: user needs to choose course
 7018:  2: browse allowed
 7019: 
 7020: =item *
 7021: 
 7022: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 7023: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 7024: and course level
 7025: 
 7026: =item *
 7027: 
 7028: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 7029: explanation of a user role term
 7030: 
 7031: =back
 7032: 
 7033: =head2 User Modification
 7034: 
 7035: =over 4
 7036: 
 7037: =item *
 7038: 
 7039: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 7040: user for the level given by URL.  Optional start and end dates (leave empty
 7041: string or zero for "no date")
 7042: 
 7043: =item *
 7044: 
 7045: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 7046: change a users, password, possible return values are: ok,
 7047: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 7048: refused
 7049: 
 7050: =item *
 7051: 
 7052: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 7053: 
 7054: =item *
 7055: 
 7056: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 7057: modify user
 7058: 
 7059: =item *
 7060: 
 7061: modifystudent
 7062: 
 7063: modify a students enrollment and identification information.
 7064: The course id is resolved based on the current users environment.  
 7065: This means the envoking user must be a course coordinator or otherwise
 7066: associated with a course.
 7067: 
 7068: This call is essentially a wrapper for lonnet::modifyuser and
 7069: lonnet::modify_student_enrollment
 7070: 
 7071: Inputs: 
 7072: 
 7073: =over 4
 7074: 
 7075: =item B<$udom> Students loncapa domain
 7076: 
 7077: =item B<$uname> Students loncapa login name
 7078: 
 7079: =item B<$uid> Students id/student number
 7080: 
 7081: =item B<$umode> Students authentication mode
 7082: 
 7083: =item B<$upass> Students password
 7084: 
 7085: =item B<$first> Students first name
 7086: 
 7087: =item B<$middle> Students middle name
 7088: 
 7089: =item B<$last> Students last name
 7090: 
 7091: =item B<$gene> Students generation
 7092: 
 7093: =item B<$usec> Students section in course
 7094: 
 7095: =item B<$end> Unix time of the roles expiration
 7096: 
 7097: =item B<$start> Unix time of the roles start date
 7098: 
 7099: =item B<$forceid> If defined, allow $uid to be changed
 7100: 
 7101: =item B<$desiredhome> server to use as home server for student
 7102: 
 7103: =back
 7104: 
 7105: =item *
 7106: 
 7107: modify_student_enrollment
 7108: 
 7109: Change a students enrollment status in a class.  The environment variable
 7110: 'role.request.course' must be defined for this function to proceed.
 7111: 
 7112: Inputs:
 7113: 
 7114: =over 4
 7115: 
 7116: =item $udom, students domain
 7117: 
 7118: =item $uname, students name
 7119: 
 7120: =item $uid, students user id
 7121: 
 7122: =item $first, students first name
 7123: 
 7124: =item $middle
 7125: 
 7126: =item $last
 7127: 
 7128: =item $gene
 7129: 
 7130: =item $usec
 7131: 
 7132: =item $end
 7133: 
 7134: =item $start
 7135: 
 7136: =back
 7137: 
 7138: 
 7139: =item *
 7140: 
 7141: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 7142: custom role; give a custom role to a user for the level given by URL.  Specify
 7143: name and domain of role author, and role name
 7144: 
 7145: =item *
 7146: 
 7147: revokerole($udom,$uname,$url,$role) : revoke a role for url
 7148: 
 7149: =item *
 7150: 
 7151: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 7152: 
 7153: =back
 7154: 
 7155: =head2 Course Infomation
 7156: 
 7157: =over 4
 7158: 
 7159: =item *
 7160: 
 7161: coursedescription($courseid) : returns a hash of information about the
 7162: specified course id, including all environment settings for the
 7163: course, the description of the course will be in the hash under the
 7164: key 'description'
 7165: 
 7166: =item *
 7167: 
 7168: resdata($name,$domain,$type,@which) : request for current parameter
 7169: setting for a specific $type, where $type is either 'course' or 'user',
 7170: @what should be a list of parameters to ask about. This routine caches
 7171: answers for 5 minutes.
 7172: 
 7173: =back
 7174: 
 7175: =head2 Course Modification
 7176: 
 7177: =over 4
 7178: 
 7179: =item *
 7180: 
 7181: writecoursepref($courseid,%prefs) : write preferences (environment
 7182: database) for a course
 7183: 
 7184: =item *
 7185: 
 7186: createcourse($udom,$description,$url) : make/modify course
 7187: 
 7188: =back
 7189: 
 7190: =head2 Resource Subroutines
 7191: 
 7192: =over 4
 7193: 
 7194: =item *
 7195: 
 7196: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 7197: 
 7198: =item *
 7199: 
 7200: repcopy($filename) : subscribes to the requested file, and attempts to
 7201: replicate from the owning library server, Might return
 7202: 'unavailable', 'not_found', 'forbidden', 'ok', or
 7203: 'bad_request', also attempts to grab the metadata for the
 7204: resource. Expects the local filesystem pathname
 7205: (/home/httpd/html/res/....)
 7206: 
 7207: =back
 7208: 
 7209: =head2 Resource Information
 7210: 
 7211: =over 4
 7212: 
 7213: =item *
 7214: 
 7215: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 7216: a vairety of different possible values, $varname should be a request
 7217: string, and the other parameters can be used to specify who and what
 7218: one is asking about.
 7219: 
 7220: Possible values for $varname are environment.lastname (or other item
 7221: from the envirnment hash), user.name (or someother aspect about the
 7222: user), resource.0.maxtries (or some other part and parameter of a
 7223: resource)
 7224: 
 7225: =item *
 7226: 
 7227: directcondval($number) : get current value of a condition; reads from a state
 7228: string
 7229: 
 7230: =item *
 7231: 
 7232: condval($condidx) : value of condition index based on state
 7233: 
 7234: =item *
 7235: 
 7236: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 7237: resource's metadata, $what should be either a specific key, or either
 7238: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 7239: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 7240: 
 7241: this function automatically caches all requests
 7242: 
 7243: =item *
 7244: 
 7245: metadata_query($query,$custom,$customshow) : make a metadata query against the
 7246: network of library servers; returns file handle of where SQL and regex results
 7247: will be stored for query
 7248: 
 7249: =item *
 7250: 
 7251: symbread($filename) : return symbolic list entry (filename argument optional);
 7252: returns the data handle
 7253: 
 7254: =item *
 7255: 
 7256: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 7257: a possible symb for the URL in $thisfn, and if is an encryypted
 7258: resource that the user accessed using /enc/ returns a 1 on success, 0
 7259: on failure, user must be in a course, as it assumes the existance of
 7260: the course initial hash, and uses $env('request.course.id'}
 7261: 
 7262: 
 7263: =item *
 7264: 
 7265: symbclean($symb) : removes versions numbers from a symb, returns the
 7266: cleaned symb
 7267: 
 7268: =item *
 7269: 
 7270: is_on_map($uri) : checks if the $uri is somewhere on the current
 7271: course map, user must be in a course for it to work.
 7272: 
 7273: =item *
 7274: 
 7275: numval($salt) : return random seed value (addend for rndseed)
 7276: 
 7277: =item *
 7278: 
 7279: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 7280: a random seed, all arguments are optional, if they aren't sent it uses the
 7281: environment to derive them. Note: if symb isn't sent and it can't get one
 7282: from &symbread it will use the current time as its return value
 7283: 
 7284: =item *
 7285: 
 7286: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 7287: unfakeable, receipt
 7288: 
 7289: =item *
 7290: 
 7291: receipt() : API to ireceipt working off of env values; given out to users
 7292: 
 7293: =item *
 7294: 
 7295: countacc($url) : count the number of accesses to a given URL
 7296: 
 7297: =item *
 7298: 
 7299: 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
 7300: 
 7301: =item *
 7302: 
 7303: 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)
 7304: 
 7305: =item *
 7306: 
 7307: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 7308: 
 7309: =item *
 7310: 
 7311: devalidate($symb) : devalidate temporary spreadsheet calculations,
 7312: forcing spreadsheet to reevaluate the resource scores next time.
 7313: 
 7314: =back
 7315: 
 7316: =head2 Storing/Retreiving Data
 7317: 
 7318: =over 4
 7319: 
 7320: =item *
 7321: 
 7322: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 7323: for this url; hashref needs to be given and should be a \%hashname; the
 7324: remaining args aren't required and if they aren't passed or are '' they will
 7325: be derived from the env
 7326: 
 7327: =item *
 7328: 
 7329: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 7330: uses critical subroutine
 7331: 
 7332: =item *
 7333: 
 7334: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 7335: all args are optional
 7336: 
 7337: =item *
 7338: 
 7339: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 7340: dumps the complete (or key matching regexp) namespace into a hash
 7341: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 7342: normally &store()ed into
 7343: 
 7344: $range should be either an integer '100' (give me the first 100
 7345:                                            matching records)
 7346:               or be  two integers sperated by a - with no spaces
 7347:                  '30-50' (give me the 30th through the 50th matching
 7348:                           records)
 7349: 
 7350: 
 7351: =item *
 7352: 
 7353: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 7354: replaces a &store() version of data with a replacement set of data
 7355: for a particular resource in a namespace passed in the $storehash hash 
 7356: reference
 7357: 
 7358: =item *
 7359: 
 7360: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 7361: works very similar to store/cstore, but all data is stored in a
 7362: temporary location and can be reset using tmpreset, $storehash should
 7363: be a hash reference, returns nothing on success
 7364: 
 7365: =item *
 7366: 
 7367: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 7368: similar to restore, but all data is stored in a temporary location and
 7369: can be reset using tmpreset. Returns a hash of values on success,
 7370: error string otherwise.
 7371: 
 7372: =item *
 7373: 
 7374: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 7375: deltes all keys for $symb form the temporary storage hash.
 7376: 
 7377: =item *
 7378: 
 7379: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 7380: reference filled in from namesp ($udom and $uname are optional)
 7381: 
 7382: =item *
 7383: 
 7384: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 7385: namesp ($udom and $uname are optional)
 7386: 
 7387: =item *
 7388: 
 7389: dump($namespace,$udom,$uname,$regexp,$range) : 
 7390: dumps the complete (or key matching regexp) namespace into a hash
 7391: ($udom, $uname, $regexp, $range are optional)
 7392: 
 7393: $range should be either an integer '100' (give me the first 100
 7394:                                            matching records)
 7395:               or be  two integers sperated by a - with no spaces
 7396:                  '30-50' (give me the 30th through the 50th matching
 7397:                           records)
 7398: =item *
 7399: 
 7400: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 7401: $store can be a scalar, an array reference, or if the amount to be 
 7402: incremented is > 1, a hash reference.
 7403: 
 7404: ($udom and $uname are optional)
 7405: 
 7406: =item *
 7407: 
 7408: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 7409: ($udom and $uname are optional)
 7410: 
 7411: =item *
 7412: 
 7413: cput($namespace,$storehash,$udom,$uname) : critical put
 7414: ($udom and $uname are optional)
 7415: 
 7416: =item *
 7417: 
 7418: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 7419: reference filled in from namesp (encrypts the return communication)
 7420: ($udom and $uname are optional)
 7421: 
 7422: =item *
 7423: 
 7424: log($udom,$name,$home,$message) : write to permanent log for user; use
 7425: critical subroutine
 7426: 
 7427: =back
 7428: 
 7429: =head2 Network Status Functions
 7430: 
 7431: =over 4
 7432: 
 7433: =item *
 7434: 
 7435: dirlist($uri) : return directory list based on URI
 7436: 
 7437: =item *
 7438: 
 7439: spareserver() : find server with least workload from spare.tab
 7440: 
 7441: =back
 7442: 
 7443: =head2 Apache Request
 7444: 
 7445: =over 4
 7446: 
 7447: =item *
 7448: 
 7449: ssi($url,%hash) : server side include, does a complete request cycle on url to
 7450: localhost, posts hash
 7451: 
 7452: =back
 7453: 
 7454: =head2 Data to String to Data
 7455: 
 7456: =over 4
 7457: 
 7458: =item *
 7459: 
 7460: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 7461: and '&' separators, supports elements that are arrayrefs and hashrefs
 7462: 
 7463: =item *
 7464: 
 7465: hashref2str($hashref) : convert a hashref into a string complete with
 7466: escaping and '=' and '&' separators, supports elements that are
 7467: arrayrefs and hashrefs
 7468: 
 7469: =item *
 7470: 
 7471: arrayref2str($arrayref) : convert an arrayref into a string complete
 7472: with escaping and '&' separators, supports elements that are arrayrefs
 7473: and hashrefs
 7474: 
 7475: =item *
 7476: 
 7477: str2hash($string) : convert string to hash using unescaping and
 7478: splitting on '=' and '&', supports elements that are arrayrefs and
 7479: hashrefs
 7480: 
 7481: =item *
 7482: 
 7483: str2array($string) : convert string to hash using unescaping and
 7484: splitting on '&', supports elements that are arrayrefs and hashrefs
 7485: 
 7486: =back
 7487: 
 7488: =head2 Logging Routines
 7489: 
 7490: =over 4
 7491: 
 7492: These routines allow one to make log messages in the lonnet.log and
 7493: lonnet.perm logfiles.
 7494: 
 7495: =item *
 7496: 
 7497: logtouch() : make sure the logfile, lonnet.log, exists
 7498: 
 7499: =item *
 7500: 
 7501: logthis() : append message to the normal lonnet.log file, it gets
 7502: preiodically rolled over and deleted.
 7503: 
 7504: =item *
 7505: 
 7506: logperm() : append a permanent message to lonnet.perm.log, this log
 7507: file never gets deleted by any automated portion of the system, only
 7508: messages of critical importance should go in here.
 7509: 
 7510: =back
 7511: 
 7512: =head2 General File Helper Routines
 7513: 
 7514: =over 4
 7515: 
 7516: =item *
 7517: 
 7518: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 7519: (a) files in /uploaded
 7520:   (i) If a local copy of the file exists - 
 7521:       compares modification date of local copy with last-modified date for 
 7522:       definitive version stored on home server for course. If local copy is 
 7523:       stale, requests a new version from the home server and stores it. 
 7524:       If the original has been removed from the home server, then local copy 
 7525:       is unlinked.
 7526:   (ii) If local copy does not exist -
 7527:       requests the file from the home server and stores it. 
 7528:   
 7529:   If $caller is 'uploadrep':  
 7530:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 7531:     for request for files originally uploaded via DOCS. 
 7532:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 7533:   
 7534:   Otherwise:
 7535:      This indicates a call from the content generation phase of the request.
 7536:      -  returns the entire contents of the file or -1.
 7537:      
 7538: (b) files in /res
 7539:    - returns the entire contents of a file or -1; 
 7540:    it properly subscribes to and replicates the file if neccessary.
 7541: 
 7542: 
 7543: =item *
 7544: 
 7545: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 7546:                   reference
 7547: 
 7548: returns either a stat() list of data about the file or an empty list
 7549: if the file doesn't exist or couldn't find out about it (connection
 7550: problems or user unknown)
 7551: 
 7552: =item *
 7553: 
 7554: filelocation($dir,$file) : returns file system location of a file
 7555: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 7556: directory that relative $file lookups are to looked in ($dir of /a/dir
 7557: and a file of ../bob will become /a/bob)
 7558: 
 7559: =item *
 7560: 
 7561: hreflocation($dir,$file) : returns file system location or a URL; same as
 7562: filelocation except for hrefs
 7563: 
 7564: =item *
 7565: 
 7566: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 7567: 
 7568: =back
 7569: 
 7570: =head2 Usererfile file routines (/uploaded*)
 7571: 
 7572: =over 4
 7573: 
 7574: =item *
 7575: 
 7576: userfileupload(): main rotine for putting a file in a user or course's
 7577:                   filespace, arguments are,
 7578: 
 7579:  formname - required - this is the name of the element in $env where the
 7580:            filename, and the contents of the file to create/modifed exist
 7581:            the filename is in $env{'form.'.$formname.'.filename'} and the
 7582:            contents of the file is located in $env{'form.'.$formname}
 7583:  coursedoc - if true, store the file in the course of the active role
 7584:              of the current user
 7585:  subdir - required - subdirectory to put the file in under ../userfiles/
 7586:          if undefined, it will be placed in "unknown"
 7587: 
 7588:  (This routine calls clean_filename() to remove any dangerous
 7589:  characters from the filename, and then calls finuserfileupload() to
 7590:  complete the transaction)
 7591: 
 7592:  returns either the url of the uploaded file (/uploaded/....) if successful
 7593:  and /adm/notfound.html if unsuccessful
 7594: 
 7595: =item *
 7596: 
 7597: clean_filename(): routine for cleaing a filename up for storage in
 7598:                  userfile space, argument is:
 7599: 
 7600:  filename - proposed filename
 7601: 
 7602: returns: the new clean filename
 7603: 
 7604: =item *
 7605: 
 7606: finishuserfileupload(): routine that creaes and sends the file to
 7607: userspace, probably shouldn't be called directly
 7608: 
 7609:   docuname: username or courseid of destination for the file
 7610:   docudom: domain of user/course of destination for the file
 7611:   formname: same as for userfileupload()
 7612:   fname: filename (inculding subdirectories) for the file
 7613: 
 7614:  returns either the url of the uploaded file (/uploaded/....) if successful
 7615:  and /adm/notfound.html if unsuccessful
 7616: 
 7617: =item *
 7618: 
 7619: renameuserfile(): renames an existing userfile to a new name
 7620: 
 7621:   Args:
 7622:    docuname: username or courseid of destination for the file
 7623:    docudom: domain of user/course of destination for the file
 7624:    old: current file name (including any subdirs under userfiles)
 7625:    new: desired file name (including any subdirs under userfiles)
 7626: 
 7627: =item *
 7628: 
 7629: mkdiruserfile(): creates a directory is a userfiles dir
 7630: 
 7631:   Args:
 7632:    docuname: username or courseid of destination for the file
 7633:    docudom: domain of user/course of destination for the file
 7634:    dir: dir to create (including any subdirs under userfiles)
 7635: 
 7636: =item *
 7637: 
 7638: removeuserfile(): removes a file that exists in userfiles
 7639: 
 7640:   Args:
 7641:    docuname: username or courseid of destination for the file
 7642:    docudom: domain of user/course of destination for the file
 7643:    fname: filname to delete (including any subdirs under userfiles)
 7644: 
 7645: =item *
 7646: 
 7647: removeuploadedurl(): convience function for removeuserfile()
 7648: 
 7649:   Args:
 7650:    url:  a full /uploaded/... url to delete
 7651: 
 7652: =back
 7653: 
 7654: =head2 HTTP Helper Routines
 7655: 
 7656: =over 4
 7657: 
 7658: =item *
 7659: 
 7660: escape() : unpack non-word characters into CGI-compatible hex codes
 7661: 
 7662: =item *
 7663: 
 7664: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 7665: 
 7666: =back
 7667: 
 7668: =head1 PRIVATE SUBROUTINES
 7669: 
 7670: =head2 Underlying communication routines (Shouldn't call)
 7671: 
 7672: =over 4
 7673: 
 7674: =item *
 7675: 
 7676: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 7677: 
 7678: =item *
 7679: 
 7680: reply() : uses subreply to send a message to remote machine, logs all failures
 7681: 
 7682: =item *
 7683: 
 7684: critical() : passes a critical message to another server; if cannot
 7685: get through then place message in connection buffer directory and
 7686: returns con_delayed, if incapable of saving message, returns
 7687: con_failed
 7688: 
 7689: =item *
 7690: 
 7691: reconlonc() : tries to reconnect lonc client processes.
 7692: 
 7693: =back
 7694: 
 7695: =head2 Resource Access Logging
 7696: 
 7697: =over 4
 7698: 
 7699: =item *
 7700: 
 7701: flushcourselogs() : flush (save) buffer logs and access logs
 7702: 
 7703: =item *
 7704: 
 7705: courselog($what) : save message for course in hash
 7706: 
 7707: =item *
 7708: 
 7709: courseacclog($what) : save message for course using &courselog().  Perform
 7710: special processing for specific resource types (problems, exams, quizzes, etc).
 7711: 
 7712: =item *
 7713: 
 7714: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 7715: as a PerlChildExitHandler
 7716: 
 7717: =back
 7718: 
 7719: =head2 Other
 7720: 
 7721: =over 4
 7722: 
 7723: =item *
 7724: 
 7725: symblist($mapname,%newhash) : update symbolic storage links
 7726: 
 7727: =back
 7728: 
 7729: =cut

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