File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.731: download - view: text, annotated - select for diffs
Wed Apr 26 14:50:56 2006 UTC (18 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- making coursedescription not update the env by default and thus faster

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

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