File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.727: download - view: text, annotated - select for diffs
Thu Apr 6 20:27:35 2006 UTC (18 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Correction to filtering used for deleted group membership. (loncoursegroups sets end time to current time, and start time to -1 when deleting a group member from a group).

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

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