Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.976.2.8

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.976.2.8! raeburn     4: # $Id: lonnet.pm,v 1.976.2.7 2009/03/20 21:18:26 raeburn Exp $
1.178     www         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: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
                     76: # use Date::Parse;
1.871     albertel   77: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.968     raeburn    78:             $_64bit %env %protocol);
1.871     albertel   79: 
                     80: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     81:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     82:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        83:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        84: 
1.1       albertel   85: use IO::Socket;
1.31      www        86: use GDBM_File;
1.208     albertel   87: use HTML::LCParser;
1.88      www        88: use Fcntl qw(:flock);
1.870     albertel   89: use Storable qw(thaw nfreeze);
1.539     albertel   90: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   91: use Cache::Memcached;
1.676     albertel   92: use Digest::MD5;
1.790     albertel   93: use Math::Random;
1.807     albertel   94: use LONCAPA qw(:DEFAULT :match);
1.740     www        95: use LONCAPA::Configuration;
1.676     albertel   96: 
1.195     www        97: my $readit;
1.550     foxr       98: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   99: 
1.619     albertel  100: require Exporter;
                    101: 
                    102: our @ISA = qw (Exporter);
                    103: our @EXPORT = qw(%env);
                    104: 
1.449     matthew   105: 
1.1       albertel  106: # --------------------------------------------------------------------- Logging
1.729     www       107: {
                    108:     my $logid;
                    109:     sub instructor_log {
1.957     raeburn   110: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    111:         if (($cnum eq '') || ($cdom eq '')) {
                    112:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    113:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    114:         }
1.729     www       115: 	$logid++;
1.957     raeburn   116:         my $now = time();
                    117: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       118: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       119: 				    { $id => {
                    120: 					'exe_uname' => $env{'user.name'},
                    121: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   122: 					'exe_time'  => $now,
1.730     www       123: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    124: 					'delflag'   => $delflag,
                    125: 					'logentry'  => $storehash,
                    126: 					'uname'     => $uname,
                    127: 					'udom'      => $udom,
                    128: 				    }
1.957     raeburn   129: 				  },$cdom,$cnum);
1.729     www       130:     }
                    131: }
1.1       albertel  132: 
1.163     harris41  133: sub logtouch {
                    134:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  135:     unless (-e "$execdir/logs/lonnet.log") {	
                    136: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  137: 	close $fh;
                    138:     }
                    139:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    140:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    141: }
                    142: 
1.1       albertel  143: sub logthis {
                    144:     my $message=shift;
                    145:     my $execdir=$perlvar{'lonDaemons'};
                    146:     my $now=time;
                    147:     my $local=localtime($now);
1.448     albertel  148:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    149: 	print $fh "$local ($$): $message\n";
                    150: 	close($fh);
                    151:     }
1.1       albertel  152:     return 1;
                    153: }
                    154: 
                    155: sub logperm {
                    156:     my $message=shift;
                    157:     my $execdir=$perlvar{'lonDaemons'};
                    158:     my $now=time;
                    159:     my $local=localtime($now);
1.448     albertel  160:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    161: 	print $fh "$now:$message:$local\n";
                    162: 	close($fh);
                    163:     }
1.1       albertel  164:     return 1;
                    165: }
                    166: 
1.850     albertel  167: sub create_connection {
1.853     albertel  168:     my ($hostname,$lonid) = @_;
1.851     albertel  169:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  170: 				     Type    => SOCK_STREAM,
                    171: 				     Timeout => 10);
                    172:     return 0 if (!$client);
1.890     albertel  173:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  174:     my $result = <$client>;
                    175:     chomp($result);
                    176:     return 1 if ($result eq 'done');
                    177:     return 0;
                    178: }
                    179: 
1.976.2.6  raeburn   180: sub get_server_timezone {
                    181:     my ($cnum,$cdom) = @_;
                    182:     my $home=&homeserver($cnum,$cdom);
                    183:     if ($home ne 'no_host') {
                    184:         my $cachetime = 24*3600;
                    185:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    186:         if (defined($cached)) {
                    187:             return $timezone;
                    188:         } else {
                    189:             my $timezone = &reply('servertimezone',$home);
                    190:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    191:         }
                    192:     }
                    193: }
1.850     albertel  194: 
1.1       albertel  195: # -------------------------------------------------- Non-critical communication
                    196: sub subreply {
                    197:     my ($cmd,$server)=@_;
1.838     albertel  198:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      199:     #
                    200:     #  With loncnew process trimming, there's a timing hole between lonc server
                    201:     #  process exit and the master server picking up the listen on the AF_UNIX
                    202:     #  socket.  In that time interval, a lock file will exist:
                    203: 
                    204:     my $lockfile=$peerfile.".lock";
                    205:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    206: 	sleep(1);
                    207:     }
                    208:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      209:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      210:     #
1.550     foxr      211:     #   We'll give the connection a few tries before abandoning it.  If
                    212:     #   connection is not possible, we'll con_lost back to the client.
                    213:     #   
                    214:     my $client;
                    215:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    216: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    217: 				      Type    => SOCK_STREAM,
                    218: 				      Timeout => 10);
1.869     albertel  219: 	if ($client) {
1.550     foxr      220: 	    last;		# Connected!
1.850     albertel  221: 	} else {
1.853     albertel  222: 	    &create_connection(&hostname($server),$server);
1.550     foxr      223: 	}
1.850     albertel  224:         sleep(1);		# Try again later if failed connection.
1.550     foxr      225:     }
                    226:     my $answer;
                    227:     if ($client) {
1.704     albertel  228: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      229: 	$answer=<$client>;
                    230: 	if (!$answer) { $answer="con_lost"; }
                    231: 	chomp($answer);
                    232:     } else {
                    233: 	$answer = 'con_lost';	# Failed connection.
                    234:     }
1.1       albertel  235:     return $answer;
                    236: }
                    237: 
                    238: sub reply {
                    239:     my ($cmd,$server)=@_;
1.838     albertel  240:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  241:     my $answer=subreply($cmd,$server);
1.65      www       242:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  243:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       244:                 " $cmd to $server returned $answer</font>");
                    245:     }
1.1       albertel  246:     return $answer;
                    247: }
                    248: 
                    249: # ----------------------------------------------------------- Send USR1 to lonc
                    250: 
                    251: sub reconlonc {
1.891     albertel  252:     my ($lonid) = @_;
                    253:     my $hostname = &hostname($lonid);
                    254:     if ($lonid) {
                    255: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    256: 	if ($hostname && -e $peerfile) {
                    257: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    258: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    259: 					     Type    => SOCK_STREAM,
                    260: 					     Timeout => 10);
                    261: 	    if ($client) {
                    262: 		print $client ("reset_retries\n");
                    263: 		my $answer=<$client>;
                    264: 		#reset just this one.
                    265: 	    }
                    266: 	}
                    267: 	return;
                    268:     }
                    269: 
1.836     www       270:     &logthis("Trying to reconnect lonc");
1.1       albertel  271:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  272:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  273: 	my $loncpid=<$fh>;
                    274:         chomp($loncpid);
                    275:         if (kill 0 => $loncpid) {
                    276: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    277:             kill USR1 => $loncpid;
                    278:             sleep 1;
1.836     www       279:          } else {
1.12      www       280: 	    &logthis(
1.672     albertel  281:                "<font color=\"blue\">WARNING:".
1.12      www       282:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  283:         }
                    284:     } else {
1.836     www       285: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  286:     }
                    287: }
                    288: 
                    289: # ------------------------------------------------------ Critical communication
1.12      www       290: 
1.1       albertel  291: sub critical {
                    292:     my ($cmd,$server)=@_;
1.838     albertel  293:     unless (&hostname($server)) {
1.672     albertel  294:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       295:                " Critical message to unknown server ($server)</font>");
                    296:         return 'no_such_host';
                    297:     }
1.1       albertel  298:     my $answer=reply($cmd,$server);
                    299:     if ($answer eq 'con_lost') {
                    300: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  301: 	my $answer=reply($cmd,$server);
1.1       albertel  302:         if ($answer eq 'con_lost') {
                    303:             my $now=time;
                    304:             my $middlename=$cmd;
1.5       www       305:             $middlename=substr($middlename,0,16);
1.1       albertel  306:             $middlename=~s/\W//g;
                    307:             my $dfilename=
1.305     www       308:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    309:             $dumpcount++;
1.1       albertel  310:             {
1.448     albertel  311: 		my $dfh;
                    312: 		if (open($dfh,">$dfilename")) {
                    313: 		    print $dfh "$cmd\n"; 
                    314: 		    close($dfh);
                    315: 		}
1.1       albertel  316:             }
                    317:             sleep 2;
                    318:             my $wcmd='';
                    319:             {
1.448     albertel  320: 		my $dfh;
                    321: 		if (open($dfh,"<$dfilename")) {
                    322: 		    $wcmd=<$dfh>; 
                    323: 		    close($dfh);
                    324: 		}
1.1       albertel  325:             }
                    326:             chomp($wcmd);
1.7       www       327:             if ($wcmd eq $cmd) {
1.672     albertel  328: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       329:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  330:                 &logperm("D:$server:$cmd");
                    331: 	        return 'con_delayed';
                    332:             } else {
1.672     albertel  333:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       334:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  335:                 &logperm("F:$server:$cmd");
                    336:                 return 'con_failed';
                    337:             }
                    338:         }
                    339:     }
                    340:     return $answer;
1.405     albertel  341: }
                    342: 
1.755     albertel  343: # ------------------------------------------- check if return value is an error
                    344: 
                    345: sub error {
                    346:     my ($result) = @_;
1.756     albertel  347:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  348: 	if ($2 == 2) { return undef; }
                    349: 	return $1;
                    350:     }
                    351:     return undef;
                    352: }
                    353: 
1.783     albertel  354: sub convert_and_load_session_env {
                    355:     my ($lonidsdir,$handle)=@_;
                    356:     my @profile;
                    357:     {
1.917     albertel  358: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    359: 	if (!$opened) {
1.915     albertel  360: 	    return 0;
                    361: 	}
1.783     albertel  362: 	flock($idf,LOCK_SH);
                    363: 	@profile=<$idf>;
                    364: 	close($idf);
                    365:     }
                    366:     my %temp_env;
                    367:     foreach my $line (@profile) {
1.786     albertel  368: 	if ($line !~ m/=/) {
                    369: 	    return 0;
                    370: 	}
1.783     albertel  371: 	chomp($line);
                    372: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    373: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    374:     }
                    375:     unlink("$lonidsdir/$handle.id");
                    376:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    377: 	    0640)) {
                    378: 	%disk_env = %temp_env;
                    379: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    380: 	untie(%disk_env);
                    381:     }
1.786     albertel  382:     return 1;
1.783     albertel  383: }
                    384: 
1.374     www       385: # ------------------------------------------- Transfer profile into environment
1.780     albertel  386: my $env_loaded;
                    387: sub transfer_profile_to_env {
1.788     albertel  388:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    389:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       390: 
1.720     albertel  391:     if (!defined($lonidsdir)) {
                    392: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    393:     }
                    394:     if (!defined($handle)) {
                    395:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    396:     }
                    397: 
1.786     albertel  398:     my $convert;
                    399:     {
1.917     albertel  400:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    401: 	if (!$opened) {
1.915     albertel  402: 	    return;
                    403: 	}
1.786     albertel  404: 	flock($idf,LOCK_SH);
                    405: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    406: 		&GDBM_READER(),0640)) {
                    407: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    408: 	    untie(%disk_env);
                    409: 	} else {
                    410: 	    $convert = 1;
                    411: 	}
                    412:     }
                    413:     if ($convert) {
                    414: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    415: 	    &logthis("Failed to load session, or convert session.");
                    416: 	}
1.374     www       417:     }
1.783     albertel  418: 
1.786     albertel  419:     my %remove;
1.783     albertel  420:     while ( my $envname = each(%env) ) {
1.433     matthew   421:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    422:             if ($time < time-300) {
1.783     albertel  423:                 $remove{$key}++;
1.433     matthew   424:             }
                    425:         }
                    426:     }
1.783     albertel  427: 
1.619     albertel  428:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  429:     $env_loaded=1;
1.783     albertel  430:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   431:         &delenv($expired_key);
1.374     www       432:     }
1.1       albertel  433: }
                    434: 
1.916     albertel  435: # ---------------------------------------------------- Check for valid session 
                    436: sub check_for_valid_session {
                    437:     my ($r) = @_;
                    438:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    439:     my $lonid=$cookies{'lonID'};
                    440:     return undef if (!$lonid);
                    441: 
                    442:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    443:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    444:     return undef if (!-e "$lonidsdir/$handle.id");
                    445: 
1.917     albertel  446:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    447:     return undef if (!$opened);
1.916     albertel  448: 
                    449:     flock($idf,LOCK_SH);
                    450:     my %disk_env;
                    451:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    452: 	    &GDBM_READER(),0640)) {
                    453: 	return undef;	
                    454:     }
                    455: 
                    456:     if (!defined($disk_env{'user.name'})
                    457: 	|| !defined($disk_env{'user.domain'})) {
                    458: 	return undef;
                    459:     }
                    460:     return $handle;
                    461: }
                    462: 
1.830     albertel  463: sub timed_flock {
                    464:     my ($file,$lock_type) = @_;
                    465:     my $failed=0;
                    466:     eval {
                    467: 	local $SIG{__DIE__}='DEFAULT';
                    468: 	local $SIG{ALRM}=sub {
                    469: 	    $failed=1;
                    470: 	    die("failed lock");
                    471: 	};
                    472: 	alarm(13);
                    473: 	flock($file,$lock_type);
                    474: 	alarm(0);
                    475:     };
                    476:     if ($failed) {
                    477: 	return undef;
                    478:     } else {
                    479: 	return 1;
                    480:     }
                    481: }
                    482: 
1.5       www       483: # ---------------------------------------------------------- Append Environment
                    484: 
                    485: sub appenv {
1.949     raeburn   486:     my ($newenv,$roles) = @_;
                    487:     if (ref($newenv) eq 'HASH') {
                    488:         foreach my $key (keys(%{$newenv})) {
                    489:             my $refused = 0;
                    490: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    491:                 $refused = 1;
                    492:                 if (ref($roles) eq 'ARRAY') {
                    493:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    494:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    495:                         $refused = 0;
                    496:                     }
                    497:                 }
                    498:             }
                    499:             if ($refused) {
                    500:                 &logthis("<font color=\"blue\">WARNING: ".
                    501:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    502:                          .'</font>');
                    503: 	        delete($newenv->{$key});
                    504:             } else {
                    505:                 $env{$key}=$newenv->{$key};
                    506:             }
                    507:         }
                    508:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    509:         if ($opened
                    510: 	    && &timed_flock($env_file,LOCK_EX)
                    511: 	    &&
                    512: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    513: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    514: 	    while (my ($key,$value) = each(%{$newenv})) {
                    515: 	        $disk_env{$key} = $value;
                    516: 	    }
                    517: 	    untie(%disk_env);
1.35      www       518:         }
1.191     harris41  519:     }
1.56      www       520:     return 'ok';
                    521: }
                    522: # ----------------------------------------------------- Delete from Environment
                    523: 
                    524: sub delenv {
1.976.2.7  raeburn   525:     my ($delthis,$regexp) = @_;
1.56      www       526:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  527:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       528:                 "Attempt to delete from environment ".$delthis);
                    529:         return 'error';
                    530:     }
1.917     albertel  531:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    532:     if ($opened
1.915     albertel  533: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  534: 	&&
                    535: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    536: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  537: 	foreach my $key (keys(%disk_env)) {
1.976.2.7  raeburn   538:             if ($regexp) {
                    539:                 if ($key=~/^$delthis/) {
                    540:                     delete($env{$key});
                    541:                     delete($disk_env{$key});
                    542:                 }
                    543:             } else {
                    544:                 if ($key=~/^\Q$delthis\E/) {
                    545:                     delete($env{$key});
                    546:                     delete($disk_env{$key});
                    547:                 }
                    548:             }
1.448     albertel  549: 	}
1.783     albertel  550: 	untie(%disk_env);
1.5       www       551:     }
                    552:     return 'ok';
1.369     albertel  553: }
                    554: 
1.790     albertel  555: sub get_env_multiple {
                    556:     my ($name) = @_;
                    557:     my @values;
                    558:     if (defined($env{$name})) {
                    559:         # exists is it an array
                    560:         if (ref($env{$name})) {
                    561:             @values=@{ $env{$name} };
                    562:         } else {
                    563:             $values[0]=$env{$name};
                    564:         }
                    565:     }
                    566:     return(@values);
                    567: }
                    568: 
1.958     www       569: # ------------------------------------------------------------------- Locking
                    570: 
                    571: sub set_lock {
                    572:     my ($text)=@_;
                    573:     $locknum++;
                    574:     my $id=$$.'-'.$locknum;
                    575:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    576:              'session.lock.'.$id => $text});
                    577:     return $id;
                    578: }
                    579: 
                    580: sub get_locks {
                    581:     my $num=0;
                    582:     my %texts=();
                    583:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    584:        if ($lock=~/\w/) {
                    585:           $num++;
                    586:           $texts{$lock}=$env{'session.lock.'.$lock};
                    587:        }
                    588:    }
                    589:    return ($num,%texts);
                    590: }
                    591: 
                    592: sub remove_lock {
                    593:     my ($id)=@_;
                    594:     my $newlocks='';
                    595:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    596:        if (($lock=~/\w/) && ($lock ne $id)) {
                    597:           $newlocks.=','.$lock;
                    598:        }
                    599:     }
                    600:     &appenv({'session.locks' => $newlocks});
                    601:     &delenv('session.lock.'.$id);
                    602: }
                    603: 
                    604: sub remove_all_locks {
                    605:     my $activelocks=$env{'session.locks'};
                    606:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    607:        if ($lock=~/\w/) {
                    608:           &remove_lock($lock);
                    609:        }
                    610:     }
                    611: }
                    612: 
                    613: 
1.369     albertel  614: # ------------------------------------------ Find out current server userload
                    615: sub userload {
                    616:     my $numusers=0;
                    617:     {
                    618: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    619: 	my $filename;
                    620: 	my $curtime=time;
                    621: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  622: 	    next if ($filename eq '.' || $filename eq '..');
                    623: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  624: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  625: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  626: 	}
                    627: 	closedir(LONIDS);
                    628:     }
                    629:     my $userloadpercent=0;
                    630:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    631:     if ($maxuserload) {
1.371     albertel  632: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  633:     }
1.372     albertel  634:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  635:     return $userloadpercent;
1.283     www       636: }
                    637: 
                    638: # ------------------------------------------ Fight off request when overloaded
                    639: 
                    640: sub overloaderror {
                    641:     my ($r,$checkserver)=@_;
                    642:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    643:     my $loadavg;
                    644:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  645:        open(my $loadfile,'/proc/loadavg');
1.283     www       646:        $loadavg=<$loadfile>;
                    647:        $loadavg =~ s/\s.*//g;
1.285     matthew   648:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  649:        close($loadfile);
1.283     www       650:     } else {
                    651:        $loadavg=&reply('load',$checkserver);
                    652:     }
1.285     matthew   653:     my $overload=$loadavg-100;
1.283     www       654:     if ($overload>0) {
1.285     matthew   655: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       656:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       657:         return 413;
1.283     www       658:     }    
                    659:     return '';
1.5       www       660: }
1.1       albertel  661: 
                    662: # ------------------------------ Find server with least workload from spare.tab
1.11      www       663: 
1.1       albertel  664: sub spareserver {
1.670     albertel  665:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  666:     my $spare_server;
1.370     albertel  667:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  668:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    669:                                                      :  $userloadpercent;
                    670:     
                    671:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    672: 	($spare_server, $lowest_load) =
                    673: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    674:     }
                    675: 
                    676:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    677: 
                    678:     if (!$found_server) {
                    679: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    680: 	    ($spare_server, $lowest_load) =
                    681: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    682: 	}
                    683:     }
                    684: 
                    685:     if (!$want_server_name) {
1.968     raeburn   686:         my $protocol = 'http';
                    687:         if ($protocol{$spare_server} eq 'https') {
                    688:             $protocol = $protocol{$spare_server};
                    689:         }
                    690: 	$spare_server = $protocol.'://'.&hostname($spare_server);
1.784     albertel  691:     }
                    692:     return $spare_server;
                    693: }
                    694: 
                    695: sub compare_server_load {
                    696:     my ($try_server, $spare_server, $lowest_load) = @_;
                    697: 
                    698:     my $loadans     = &reply('load',    $try_server);
                    699:     my $userloadans = &reply('userload',$try_server);
                    700: 
                    701:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    702: 	next; #didn't get a number from the server
                    703:     }
                    704: 
                    705:     my $load;
                    706:     if ($loadans =~ /\d/) {
                    707: 	if ($userloadans =~ /\d/) {
                    708: 	    #both are numbers, pick the bigger one
                    709: 	    $load = ($loadans > $userloadans) ? $loadans 
                    710: 		                              : $userloadans;
1.411     albertel  711: 	} else {
1.784     albertel  712: 	    $load = $loadans;
1.411     albertel  713: 	}
1.784     albertel  714:     } else {
                    715: 	$load = $userloadans;
                    716:     }
                    717: 
                    718:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    719: 	$spare_server = $try_server;
                    720: 	$lowest_load  = $load;
1.370     albertel  721:     }
1.784     albertel  722:     return ($spare_server,$lowest_load);
1.202     matthew   723: }
1.914     albertel  724: 
                    725: # --------------------------- ask offload servers if user already has a session
                    726: sub find_existing_session {
                    727:     my ($udom,$uname) = @_;
                    728:     foreach my $try_server (@{ $spareid{'primary'} },
                    729: 			    @{ $spareid{'default'} }) {
                    730: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    731:     }
                    732:     return;
                    733: }
                    734: 
                    735: # -------------------------------- ask if server already has a session for user
                    736: sub has_user_session {
                    737:     my ($lonid,$udom,$uname) = @_;
                    738:     my $result = &reply(join(':','userhassession',
                    739: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    740:     return 1 if ($result eq 'ok');
                    741: 
                    742:     return 0;
                    743: }
                    744: 
1.202     matthew   745: # --------------------------------------------- Try to change a user's password
                    746: 
                    747: sub changepass {
1.799     raeburn   748:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   749:     $currentpass = &escape($currentpass);
                    750:     $newpass     = &escape($newpass);
1.799     raeburn   751:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   752: 		       $server);
                    753:     if (! $answer) {
                    754: 	&logthis("No reply on password change request to $server ".
                    755: 		 "by $uname in domain $udom.");
                    756:     } elsif ($answer =~ "^ok") {
                    757:         &logthis("$uname in $udom successfully changed their password ".
                    758: 		 "on $server.");
                    759:     } elsif ($answer =~ "^pwchange_failure") {
                    760: 	&logthis("$uname in $udom was unable to change their password ".
                    761: 		 "on $server.  The action was blocked by either lcpasswd ".
                    762: 		 "or pwchange");
                    763:     } elsif ($answer =~ "^non_authorized") {
                    764:         &logthis("$uname in $udom did not get their password correct when ".
                    765: 		 "attempting to change it on $server.");
                    766:     } elsif ($answer =~ "^auth_mode_error") {
                    767:         &logthis("$uname in $udom attempted to change their password despite ".
                    768: 		 "not being locally or internally authenticated on $server.");
                    769:     } elsif ($answer =~ "^unknown_user") {
                    770:         &logthis("$uname in $udom attempted to change their password ".
                    771: 		 "on $server but were unable to because $server is not ".
                    772: 		 "their home server.");
                    773:     } elsif ($answer =~ "^refused") {
                    774: 	&logthis("$server refused to change $uname in $udom password because ".
                    775: 		 "it was sent an unencrypted request to change the password.");
                    776:     }
                    777:     return $answer;
1.1       albertel  778: }
                    779: 
1.169     harris41  780: # ----------------------- Try to determine user's current authentication scheme
                    781: 
                    782: sub queryauthenticate {
                    783:     my ($uname,$udom)=@_;
1.456     albertel  784:     my $uhome=&homeserver($uname,$udom);
                    785:     if (!$uhome) {
                    786: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    787: 	return 'no_host';
                    788:     }
                    789:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    790:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    791: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  792:     }
1.456     albertel  793:     return $answer;
1.169     harris41  794: }
                    795: 
1.1       albertel  796: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       797: 
1.1       albertel  798: sub authenticate {
1.952     raeburn   799:     my ($uname,$upass,$udom,$checkdefauth)=@_;
1.807     albertel  800:     $upass=&escape($upass);
                    801:     $uname= &LONCAPA::clean_username($uname);
1.836     www       802:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn   803:     my $newhome;
1.836     www       804:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    805: # Maybe the machine was offline and only re-appeared again recently?
                    806:         &reconlonc();
                    807: # One more
1.952     raeburn   808: 	$uhome=&homeserver($uname,$udom,1);
                    809:         if (($uhome eq 'no_host') && $checkdefauth) {
                    810:             if (defined(&domain($udom,'primary'))) {
                    811:                 $newhome=&domain($udom,'primary');
                    812:             }
                    813:             if ($newhome ne '') {
                    814:                 $uhome = $newhome;
                    815:             }
                    816:         }
1.836     www       817: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    818: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn   819: 	    return 'no_host';
                    820:         }
1.1       albertel  821:     }
1.952     raeburn   822:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
1.471     albertel  823:     if ($answer eq 'authorized') {
1.952     raeburn   824:         if ($newhome) {
                    825:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                    826:             return 'no_account_on_host'; 
                    827:         } else {
                    828:             &logthis("User $uname at $udom authorized by $uhome");
                    829:             return $uhome;
                    830:         }
1.471     albertel  831:     }
                    832:     if ($answer eq 'non_authorized') {
                    833: 	&logthis("User $uname at $udom rejected by $uhome");
                    834: 	return 'no_host'; 
1.9       www       835:     }
1.471     albertel  836:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  837:     return 'no_host';
                    838: }
                    839: 
                    840: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       841: 
1.599     albertel  842: my %homecache;
1.1       albertel  843: sub homeserver {
1.230     stredwic  844:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  845:     my $index="$uname:$udom";
1.426     albertel  846: 
1.599     albertel  847:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  848: 
                    849:     my %servers = &get_servers($udom,'library');
                    850:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  851:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  852: 		 exists($badServerCache{$tryserver}));
1.841     albertel  853: 
                    854: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    855: 	if ($answer eq 'found') {
                    856: 	    delete($badServerCache{$tryserver}); 
                    857: 	    return $homecache{$index}=$tryserver;
                    858: 	} elsif ($answer eq 'no_host') {
                    859: 	    $badServerCache{$tryserver}=1;
                    860: 	}
1.1       albertel  861:     }    
                    862:     return 'no_host';
1.70      www       863: }
                    864: 
                    865: # ------------------------------------- Find the usernames behind a list of IDs
                    866: 
                    867: sub idget {
                    868:     my ($udom,@ids)=@_;
                    869:     my %returnhash=();
                    870:     
1.841     albertel  871:     my %servers = &get_servers($udom,'library');
                    872:     foreach my $tryserver (keys(%servers)) {
                    873: 	my $idlist=join('&',@ids);
                    874: 	$idlist=~tr/A-Z/a-z/; 
                    875: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    876: 	my @answer=();
                    877: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    878: 	    @answer=split(/\&/,$reply);
                    879: 	}                    ;
                    880: 	my $i;
                    881: 	for ($i=0;$i<=$#ids;$i++) {
                    882: 	    if ($answer[$i]) {
                    883: 		$returnhash{$ids[$i]}=$answer[$i];
                    884: 	    } 
                    885: 	}
                    886:     } 
1.70      www       887:     return %returnhash;
                    888: }
                    889: 
                    890: # ------------------------------------- Find the IDs behind a list of usernames
                    891: 
                    892: sub idrget {
                    893:     my ($udom,@unames)=@_;
                    894:     my %returnhash=();
1.800     albertel  895:     foreach my $uname (@unames) {
                    896:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  897:     }
1.70      www       898:     return %returnhash;
                    899: }
                    900: 
                    901: # ------------------------------- Store away a list of names and associated IDs
                    902: 
                    903: sub idput {
                    904:     my ($udom,%ids)=@_;
                    905:     my %servers=();
1.800     albertel  906:     foreach my $uname (keys(%ids)) {
                    907: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    908:         my $uhom=&homeserver($uname,$udom);
1.70      www       909:         if ($uhom ne 'no_host') {
1.800     albertel  910:             my $id=&escape($ids{$uname});
1.70      www       911:             $id=~tr/A-Z/a-z/;
1.800     albertel  912:             my $esc_unam=&escape($uname);
1.70      www       913: 	    if ($servers{$uhom}) {
1.800     albertel  914: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       915:             } else {
1.800     albertel  916:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       917:             }
                    918:         }
1.191     harris41  919:     }
1.800     albertel  920:     foreach my $server (keys(%servers)) {
                    921:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  922:     }
1.344     www       923: }
                    924: 
1.806     raeburn   925: # ------------------------------------------- get items from domain db files   
                    926: 
                    927: sub get_dom {
1.860     raeburn   928:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   929:     my $items='';
                    930:     foreach my $item (@$storearr) {
                    931:         $items.=&escape($item).'&';
                    932:     }
                    933:     $items=~s/\&$//;
1.860     raeburn   934:     if (!$udom) {
                    935:         $udom=$env{'user.domain'};
                    936:         if (defined(&domain($udom,'primary'))) {
                    937:             $uhome=&domain($udom,'primary');
                    938:         } else {
1.874     albertel  939:             undef($uhome);
1.860     raeburn   940:         }
                    941:     } else {
                    942:         if (!$uhome) {
                    943:             if (defined(&domain($udom,'primary'))) {
                    944:                 $uhome=&domain($udom,'primary');
                    945:             }
                    946:         }
                    947:     }
                    948:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   949:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn   950:         my %returnhash;
1.875     albertel  951:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn   952:             return %returnhash;
                    953:         }
1.806     raeburn   954:         my @pairs=split(/\&/,$rep);
                    955:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    956:             return @pairs;
                    957:         }
                    958:         my $i=0;
                    959:         foreach my $item (@$storearr) {
                    960:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    961:             $i++;
                    962:         }
                    963:         return %returnhash;
                    964:     } else {
1.880     banghart  965:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn   966:     }
                    967: }
                    968: 
                    969: # -------------------------------------------- put items in domain db files 
                    970: 
                    971: sub put_dom {
1.860     raeburn   972:     my ($namespace,$storehash,$udom,$uhome)=@_;
                    973:     if (!$udom) {
                    974:         $udom=$env{'user.domain'};
                    975:         if (defined(&domain($udom,'primary'))) {
                    976:             $uhome=&domain($udom,'primary');
                    977:         } else {
1.874     albertel  978:             undef($uhome);
1.860     raeburn   979:         }
                    980:     } else {
                    981:         if (!$uhome) {
                    982:             if (defined(&domain($udom,'primary'))) {
                    983:                 $uhome=&domain($udom,'primary');
                    984:             }
                    985:         }
                    986:     } 
                    987:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   988:         my $items='';
                    989:         foreach my $item (keys(%$storehash)) {
                    990:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    991:         }
                    992:         $items=~s/\&$//;
                    993:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    994:     } else {
1.860     raeburn   995:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn   996:     }
                    997: }
                    998: 
1.837     raeburn   999: sub retrieve_inst_usertypes {
                   1000:     my ($udom) = @_;
                   1001:     my (%returnhash,@order);
1.846     albertel 1002:     if (defined(&domain($udom,'primary'))) {
                   1003:         my $uhome=&domain($udom,'primary');
1.837     raeburn  1004:         my $rep=&reply("inst_usertypes:$udom",$uhome);
1.960     raeburn  1005:         if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1006:             &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1007:             return (\%returnhash,\@order);
                   1008:         }
1.837     raeburn  1009:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1010:         my @pairs=split(/\&/,$hashitems);
                   1011:         foreach my $item (@pairs) {
                   1012:             my ($key,$value)=split(/=/,$item,2);
                   1013:             $key = &unescape($key);
                   1014:             next if ($key =~ /^error: 2 /);
                   1015:             $returnhash{$key}=&thaw_unescape($value);
                   1016:         }
                   1017:         my @esc_order = split(/\&/,$orderitems);
                   1018:         foreach my $item (@esc_order) {
                   1019:             push(@order,&unescape($item));
                   1020:         }
                   1021:     } else {
                   1022:         &logthis("get_dom failed - no primary domain server for $udom");
                   1023:     }
                   1024:     return (\%returnhash,\@order);
                   1025: }
                   1026: 
1.868     raeburn  1027: sub is_domainimage {
                   1028:     my ($url) = @_;
                   1029:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1030:         if (&domain($1) ne '') {
                   1031:             return '1';
                   1032:         }
                   1033:     }
                   1034:     return;
                   1035: }
                   1036: 
1.899     raeburn  1037: sub inst_directory_query {
                   1038:     my ($srch) = @_;
                   1039:     my $udom = $srch->{'srchdomain'};
                   1040:     my %results;
                   1041:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1042:     my $outcome;
1.899     raeburn  1043:     if ($homeserver ne '') {
1.904     albertel 1044: 	my $queryid=&reply("querysend:instdirsearch:".
                   1045: 			   &escape($srch->{'srchby'}).':'.
                   1046: 			   &escape($srch->{'srchterm'}).':'.
                   1047: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1048: 	my $host=&hostname($homeserver);
                   1049: 	if ($queryid !~/^\Q$host\E\_/) {
                   1050: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1051: 	    return;
                   1052: 	}
                   1053: 	my $response = &get_query_reply($queryid);
                   1054: 	my $maxtries = 5;
                   1055: 	my $tries = 1;
                   1056: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1057: 	    $response = &get_query_reply($queryid);
                   1058: 	    $tries ++;
                   1059: 	}
                   1060: 
                   1061:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1062:             if ($response eq 'unavailable') {
                   1063:                 $outcome = $response;
                   1064:             } else {
                   1065:                 $outcome = 'ok';
                   1066:                 my @matches = split(/\n/,$response);
                   1067:                 foreach my $match (@matches) {
                   1068:                     my ($key,$value) = split(/=/,$match);
                   1069:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1070:                 }
1.899     raeburn  1071:             }
                   1072:         }
                   1073:     }
1.909     raeburn  1074:     return ($outcome,%results);
1.899     raeburn  1075: }
                   1076: 
                   1077: sub usersearch {
                   1078:     my ($srch) = @_;
                   1079:     my $dom = $srch->{'srchdomain'};
                   1080:     my %results;
                   1081:     my %libserv = &all_library();
                   1082:     my $query = 'usersearch';
                   1083:     foreach my $tryserver (keys(%libserv)) {
                   1084:         if (&host_domain($tryserver) eq $dom) {
                   1085:             my $host=&hostname($tryserver);
                   1086:             my $queryid=
1.911     raeburn  1087:                 &reply("querysend:".&escape($query).':'.
                   1088:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1089:                        &escape($srch->{'srchtype'}).':'.
                   1090:                        &escape($srch->{'srchterm'}),$tryserver);
                   1091:             if ($queryid !~/^\Q$host\E\_/) {
                   1092:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1093:                 next;
1.899     raeburn  1094:             }
                   1095:             my $reply = &get_query_reply($queryid);
                   1096:             my $maxtries = 1;
                   1097:             my $tries = 1;
                   1098:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1099:                 $reply = &get_query_reply($queryid);
                   1100:                 $tries ++;
                   1101:             }
                   1102:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1103:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1104:             } else {
1.911     raeburn  1105:                 my @matches;
                   1106:                 if ($reply =~ /\n/) {
                   1107:                     @matches = split(/\n/,$reply);
                   1108:                 } else {
                   1109:                     @matches = split(/\&/,$reply);
                   1110:                 }
1.899     raeburn  1111:                 foreach my $match (@matches) {
                   1112:                     my ($uname,$udom,%userhash);
1.911     raeburn  1113:                     foreach my $entry (split(/:/,$match)) {
                   1114:                         my ($key,$value) =
                   1115:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1116:                         $userhash{$key} = $value;
                   1117:                         if ($key eq 'username') {
                   1118:                             $uname = $value;
                   1119:                         } elsif ($key eq 'domain') {
                   1120:                             $udom = $value;
1.911     raeburn  1121:                         }
1.899     raeburn  1122:                     }
                   1123:                     $results{$uname.':'.$udom} = \%userhash;
                   1124:                 }
                   1125:             }
                   1126:         }
                   1127:     }
                   1128:     return %results;
                   1129: }
                   1130: 
1.912     raeburn  1131: sub get_instuser {
                   1132:     my ($udom,$uname,$id) = @_;
                   1133:     my $homeserver = &domain($udom,'primary');
                   1134:     my ($outcome,%results);
                   1135:     if ($homeserver ne '') {
                   1136:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1137:                            &escape($id).':'.&escape($udom),$homeserver);
                   1138:         my $host=&hostname($homeserver);
                   1139:         if ($queryid !~/^\Q$host\E\_/) {
                   1140:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1141:             return;
                   1142:         }
                   1143:         my $response = &get_query_reply($queryid);
                   1144:         my $maxtries = 5;
                   1145:         my $tries = 1;
                   1146:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1147:             $response = &get_query_reply($queryid);
                   1148:             $tries ++;
                   1149:         }
                   1150:         if (!&error($response) && $response ne 'refused') {
                   1151:             if ($response eq 'unavailable') {
                   1152:                 $outcome = $response;
                   1153:             } else {
                   1154:                 $outcome = 'ok';
                   1155:                 my @matches = split(/\n/,$response);
                   1156:                 foreach my $match (@matches) {
                   1157:                     my ($key,$value) = split(/=/,$match);
                   1158:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1159:                 }
                   1160:             }
                   1161:         }
                   1162:     }
                   1163:     my %userinfo;
                   1164:     if (ref($results{$uname}) eq 'HASH') {
                   1165:         %userinfo = %{$results{$uname}};
                   1166:     } 
                   1167:     return ($outcome,%userinfo);
                   1168: }
                   1169: 
                   1170: sub inst_rulecheck {
1.923     raeburn  1171:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1172:     my %returnhash;
                   1173:     if ($udom ne '') {
                   1174:         if (ref($rules) eq 'ARRAY') {
                   1175:             @{$rules} = map {&escape($_);} (@{$rules});
                   1176:             my $rulestr = join(':',@{$rules});
                   1177:             my $homeserver=&domain($udom,'primary');
                   1178:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1179:                 my $response;
                   1180:                 if ($item eq 'username') {                
                   1181:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1182:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1183:                                               $homeserver));
1.923     raeburn  1184:                 } elsif ($item eq 'id') {
                   1185:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1186:                                               ':'.&escape($id).':'.$rulestr,
                   1187:                                               $homeserver));
1.945     raeburn  1188:                 } elsif ($item eq 'selfcreate') {
                   1189:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1190:                                                &escape($udom).':'.&escape($uname).
                   1191:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1192:                 }
1.912     raeburn  1193:                 if ($response ne 'refused') {
                   1194:                     my @pairs=split(/\&/,$response);
                   1195:                     foreach my $item (@pairs) {
                   1196:                         my ($key,$value)=split(/=/,$item,2);
                   1197:                         $key = &unescape($key);
                   1198:                         next if ($key =~ /^error: 2 /);
                   1199:                         $returnhash{$key}=&thaw_unescape($value);
                   1200:                     }
                   1201:                 }
                   1202:             }
                   1203:         }
                   1204:     }
                   1205:     return %returnhash;
                   1206: }
                   1207: 
                   1208: sub inst_userrules {
1.923     raeburn  1209:     my ($udom,$check) = @_;
1.912     raeburn  1210:     my (%ruleshash,@ruleorder);
                   1211:     if ($udom ne '') {
                   1212:         my $homeserver=&domain($udom,'primary');
                   1213:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1214:             my $response;
                   1215:             if ($check eq 'id') {
                   1216:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1217:                                  $homeserver);
1.943     raeburn  1218:             } elsif ($check eq 'email') {
                   1219:                 $response=&reply('instemailrules:'.&escape($udom),
                   1220:                                  $homeserver);
1.923     raeburn  1221:             } else {
                   1222:                 $response=&reply('instuserrules:'.&escape($udom),
                   1223:                                  $homeserver);
                   1224:             }
1.912     raeburn  1225:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1226:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1227:                 ($response ne 'no_such_host')) {
                   1228:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1229:                 my @pairs=split(/\&/,$hashitems);
                   1230:                 foreach my $item (@pairs) {
                   1231:                     my ($key,$value)=split(/=/,$item,2);
                   1232:                     $key = &unescape($key);
                   1233:                     next if ($key =~ /^error: 2 /);
                   1234:                     $ruleshash{$key}=&thaw_unescape($value);
                   1235:                 }
                   1236:                 my @esc_order = split(/\&/,$orderitems);
                   1237:                 foreach my $item (@esc_order) {
                   1238:                     push(@ruleorder,&unescape($item));
                   1239:                 }
                   1240:             }
                   1241:         }
                   1242:     }
                   1243:     return (\%ruleshash,\@ruleorder);
                   1244: }
                   1245: 
1.976     raeburn  1246: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1247: 
                   1248: sub get_domain_defaults {
                   1249:     my ($domain) = @_;
                   1250:     my $cachetime = 60*60*24;
                   1251:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1252:     if (defined($cached)) {
                   1253:         if (ref($result) eq 'HASH') {
                   1254:             return %{$result};
                   1255:         }
                   1256:     }
                   1257:     my %domdefaults;
                   1258:     my %domconfig =
1.976     raeburn  1259:          &Apache::lonnet::get_dom('configuration',['defaults','quotas'],$domain);
1.943     raeburn  1260:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1261:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1262:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1263:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.976.2.5  raeburn  1264:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
                   1265:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1266:     } else {
                   1267:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1268:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1269:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1270:     }
1.976     raeburn  1271:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1272:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1273:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1274:         } else {
                   1275:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1276:         } 
                   1277:         my @usertools = ('aboutme','blog','portfolio');
                   1278:         foreach my $item (@usertools) {
                   1279:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1280:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1281:             }
                   1282:         }
                   1283:     }
1.943     raeburn  1284:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1285:                                   $cachetime);
                   1286:     return %domdefaults;
                   1287: }
                   1288: 
1.344     www      1289: # --------------------------------------------------- Assign a key to a student
                   1290: 
                   1291: sub assign_access_key {
1.364     www      1292: #
                   1293: # a valid key looks like uname:udom#comments
                   1294: # comments are being appended
                   1295: #
1.498     www      1296:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1297:     $kdom=
1.620     albertel 1298:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1299:     $knum=
1.620     albertel 1300:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1301:     $cdom=
1.620     albertel 1302:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1303:     $cnum=
1.620     albertel 1304:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1305:     $udom=$env{'user.name'} unless (defined($udom));
                   1306:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1307:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1308:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1309:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1310:                                                   # assigned to this person
                   1311:                                                   # - this should not happen,
1.345     www      1312:                                                   # unless something went wrong
                   1313:                                                   # the first time around
                   1314: # ready to assign
1.364     www      1315:         $logentry=$1.'; '.$logentry;
1.496     www      1316:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1317:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1318: # key now belongs to user
1.346     www      1319: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1320:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  1321:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      1322:                 return 'ok';
                   1323:             } else {
                   1324:                 return 
                   1325:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1326: 	    }
                   1327:         } else {
                   1328:             return 'error: Could not assign key, try again later.';
                   1329:         }
1.364     www      1330:     } elsif (!$existing{$ckey}) {
1.345     www      1331: # the key does not exist
                   1332: 	return 'error: The key does not exist';
                   1333:     } else {
                   1334: # the key is somebody else's
                   1335: 	return 'error: The key is already in use';
                   1336:     }
1.344     www      1337: }
                   1338: 
1.364     www      1339: # ------------------------------------------ put an additional comment on a key
                   1340: 
                   1341: sub comment_access_key {
                   1342: #
                   1343: # a valid key looks like uname:udom#comments
                   1344: # comments are being appended
                   1345: #
                   1346:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1347:     $cdom=
1.620     albertel 1348:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1349:     $cnum=
1.620     albertel 1350:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1351:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1352:     if ($existing{$ckey}) {
                   1353:         $existing{$ckey}.='; '.$logentry;
                   1354: # ready to assign
1.367     www      1355:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1356:                                                  $cdom,$cnum) eq 'ok') {
                   1357: 	    return 'ok';
                   1358:         } else {
                   1359: 	    return 'error: Count not store comment.';
                   1360:         }
                   1361:     } else {
                   1362: # the key does not exist
                   1363: 	return 'error: The key does not exist';
                   1364:     }
                   1365: }
                   1366: 
1.344     www      1367: # ------------------------------------------------------ Generate a set of keys
                   1368: 
                   1369: sub generate_access_keys {
1.364     www      1370:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1371:     $cdom=
1.620     albertel 1372:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1373:     $cnum=
1.620     albertel 1374:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1375:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1376:     unless (($cdom) && ($cnum)) { return 0; }
                   1377:     if ($number>10000) { return 0; }
                   1378:     sleep(2); # make sure don't get same seed twice
                   1379:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1380:     my $total=0;
                   1381:     for (my $i=1;$i<=$number;$i++) {
                   1382:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1383:                   sprintf("%lx",int(100000*rand)).'-'.
                   1384:                   sprintf("%lx",int(100000*rand));
                   1385:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1386:        $newkey=~s/0/h/g; # and also 0 and O
                   1387:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1388:        if ($existing{$newkey}) {
                   1389:            $i--;
                   1390:        } else {
1.364     www      1391: 	  if (&put('accesskeys',
                   1392:               { $newkey => '# generated '.localtime().
1.620     albertel 1393:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1394:                            '; '.$logentry },
                   1395: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1396:               $total++;
                   1397: 	  }
                   1398:        }
                   1399:     }
1.620     albertel 1400:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1401:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1402:     return $total;
                   1403: }
                   1404: 
                   1405: # ------------------------------------------------------- Validate an accesskey
                   1406: 
                   1407: sub validate_access_key {
                   1408:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1409:     $cdom=
1.620     albertel 1410:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1411:     $cnum=
1.620     albertel 1412:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1413:     $udom=$env{'user.domain'} unless (defined($udom));
                   1414:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1415:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1416:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1417: }
                   1418: 
                   1419: # ------------------------------------- Find the section of student in a course
1.652     albertel 1420: sub devalidate_getsection_cache {
                   1421:     my ($udom,$unam,$courseid)=@_;
                   1422:     my $hashid="$udom:$unam:$courseid";
                   1423:     &devalidate_cache_new('getsection',$hashid);
                   1424: }
1.298     matthew  1425: 
1.815     albertel 1426: sub courseid_to_courseurl {
                   1427:     my ($courseid) = @_;
                   1428:     #already url style courseid
                   1429:     return $courseid if ($courseid =~ m{^/});
                   1430: 
                   1431:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1432: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1433: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1434: 	return "/$cdom/$cnum";
                   1435:     }
                   1436: 
                   1437:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1438:     if (exists($courseinfo{'num'})) {
                   1439: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1440:     }
                   1441: 
                   1442:     return undef;
                   1443: }
                   1444: 
1.298     matthew  1445: sub getsection {
                   1446:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1447:     my $cachetime=1800;
1.551     albertel 1448: 
                   1449:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1450:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1451:     if (defined($cached)) { return $result; }
                   1452: 
1.298     matthew  1453:     my %Pending; 
                   1454:     my %Expired;
                   1455:     #
                   1456:     # Each role can either have not started yet (pending), be active, 
                   1457:     #    or have expired.
                   1458:     #
                   1459:     # If there is an active role, we are done.
                   1460:     #
                   1461:     # If there is more than one role which has not started yet, 
                   1462:     #     choose the one which will start sooner
                   1463:     # If there is one role which has not started yet, return it.
                   1464:     #
                   1465:     # If there is more than one expired role, choose the one which ended last.
                   1466:     # If there is a role which has expired, return it.
                   1467:     #
1.815     albertel 1468:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1469:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1470:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1471:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1472:         my $section=$1;
                   1473:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1474:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1475:         my $now=time;
1.548     albertel 1476:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1477:             $Expired{$end}=$section;
                   1478:             next;
                   1479:         }
1.548     albertel 1480:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1481:             $Pending{$start}=$section;
                   1482:             next;
                   1483:         }
1.599     albertel 1484:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1485:     }
                   1486:     #
                   1487:     # Presumedly there will be few matching roles from the above
                   1488:     # loop and the sorting time will be negligible.
                   1489:     if (scalar(keys(%Pending))) {
                   1490:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1491:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1492:     } 
                   1493:     if (scalar(keys(%Expired))) {
                   1494:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1495:         my $time = pop(@sorted);
1.599     albertel 1496:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1497:     }
1.599     albertel 1498:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1499: }
1.70      www      1500: 
1.599     albertel 1501: sub save_cache {
                   1502:     &purge_remembered();
1.722     albertel 1503:     #&Apache::loncommon::validate_page();
1.620     albertel 1504:     undef(%env);
1.780     albertel 1505:     undef($env_loaded);
1.599     albertel 1506: }
1.452     albertel 1507: 
1.599     albertel 1508: my $to_remember=-1;
                   1509: my %remembered;
                   1510: my %accessed;
                   1511: my $kicks=0;
                   1512: my $hits=0;
1.849     albertel 1513: sub make_key {
                   1514:     my ($name,$id) = @_;
1.872     albertel 1515:     if (length($id) > 65 
                   1516: 	&& length(&escape($id)) > 200) {
                   1517: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1518:     }
1.849     albertel 1519:     return &escape($name.':'.$id);
                   1520: }
                   1521: 
1.599     albertel 1522: sub devalidate_cache_new {
                   1523:     my ($name,$id,$debug) = @_;
                   1524:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1525:     $id=&make_key($name,$id);
1.599     albertel 1526:     $memcache->delete($id);
                   1527:     delete($remembered{$id});
                   1528:     delete($accessed{$id});
                   1529: }
                   1530: 
                   1531: sub is_cached_new {
                   1532:     my ($name,$id,$debug) = @_;
1.849     albertel 1533:     $id=&make_key($name,$id);
1.599     albertel 1534:     if (exists($remembered{$id})) {
                   1535: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1536: 	$accessed{$id}=[&gettimeofday()];
                   1537: 	$hits++;
                   1538: 	return ($remembered{$id},1);
                   1539:     }
                   1540:     my $value = $memcache->get($id);
                   1541:     if (!(defined($value))) {
                   1542: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1543: 	return (undef,undef);
1.416     albertel 1544:     }
1.599     albertel 1545:     if ($value eq '__undef__') {
                   1546: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1547: 	$value=undef;
                   1548:     }
                   1549:     &make_room($id,$value,$debug);
                   1550:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1551:     return ($value,1);
                   1552: }
                   1553: 
                   1554: sub do_cache_new {
                   1555:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1556:     $id=&make_key($name,$id);
1.599     albertel 1557:     my $setvalue=$value;
                   1558:     if (!defined($setvalue)) {
                   1559: 	$setvalue='__undef__';
                   1560:     }
1.623     albertel 1561:     if (!defined($time) ) {
                   1562: 	$time=600;
                   1563:     }
1.599     albertel 1564:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1565:     my $result = $memcache->set($id,$setvalue,$time);
                   1566:     if (! $result) {
1.872     albertel 1567: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1568: 	$memcache->disconnect_all();
1.872     albertel 1569:     }
1.600     albertel 1570:     # need to make a copy of $value
1.919     albertel 1571:     &make_room($id,$value,$debug);
1.599     albertel 1572:     return $value;
                   1573: }
                   1574: 
                   1575: sub make_room {
                   1576:     my ($id,$value,$debug)=@_;
1.919     albertel 1577: 
                   1578:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1579:                                     : $value;
1.599     albertel 1580:     if ($to_remember<0) { return; }
                   1581:     $accessed{$id}=[&gettimeofday()];
                   1582:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1583:     my $to_kick;
                   1584:     my $max_time=0;
                   1585:     foreach my $other (keys(%accessed)) {
                   1586: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1587: 	    $to_kick=$other;
                   1588: 	    $max_time=&tv_interval($accessed{$other});
                   1589: 	}
                   1590:     }
                   1591:     delete($remembered{$to_kick});
                   1592:     delete($accessed{$to_kick});
                   1593:     $kicks++;
                   1594:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1595:     return;
                   1596: }
                   1597: 
1.599     albertel 1598: sub purge_remembered {
1.604     albertel 1599:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1600:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1601:     undef(%remembered);
                   1602:     undef(%accessed);
1.428     albertel 1603: }
1.70      www      1604: # ------------------------------------- Read an entry from a user's environment
                   1605: 
                   1606: sub userenvironment {
                   1607:     my ($udom,$unam,@what)=@_;
1.976     raeburn  1608:     my $items;
                   1609:     foreach my $item (@what) {
                   1610:         $items.=&escape($item).'&';
                   1611:     }
                   1612:     $items=~s/\&$//;
1.70      www      1613:     my %returnhash=();
                   1614:     my @answer=split(/\&/,
1.976     raeburn  1615:                 &reply('get:'.$udom.':'.$unam.':environment:'.$items,
1.70      www      1616:                       &homeserver($unam,$udom)));
                   1617:     my $i;
                   1618:     for ($i=0;$i<=$#what;$i++) {
                   1619: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1620:     }
                   1621:     return %returnhash;
1.1       albertel 1622: }
                   1623: 
1.617     albertel 1624: # ---------------------------------------------------------- Get a studentphoto
                   1625: sub studentphoto {
                   1626:     my ($udom,$unam,$ext) = @_;
                   1627:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1628:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1629:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1630:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1631:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1632:             } else {
                   1633:                 my ($result,$perm_reqd)=
1.707     albertel 1634: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1635:                 if ($result eq 'ok') {
                   1636:                     if (!($perm_reqd eq 'yes')) {
                   1637:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1638:                     }
                   1639:                 }
                   1640:             }
                   1641:         }
                   1642:     } else {
                   1643:         my ($result,$perm_reqd) = 
1.707     albertel 1644: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1645:         if ($result eq 'ok') {
                   1646:             if (!($perm_reqd eq 'yes')) {
                   1647:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1648:             }
                   1649:         }
                   1650:     }
                   1651:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1652: }
                   1653: 
                   1654: sub retrievestudentphoto {
                   1655:     my ($udom,$unam,$ext,$type) = @_;
                   1656:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1657:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1658:     if ($ret eq 'ok') {
                   1659:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1660:         if ($type eq 'thumbnail') {
                   1661:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1662:         }
                   1663:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1664:         return $tokenurl;
                   1665:     } else {
                   1666:         if ($type eq 'thumbnail') {
                   1667:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1668:         } else { 
                   1669:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1670:         }
1.617     albertel 1671:     }
                   1672: }
                   1673: 
1.263     www      1674: # -------------------------------------------------------------------- New chat
                   1675: 
                   1676: sub chatsend {
1.724     raeburn  1677:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1678:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1679:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1680:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1681:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1682: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1683: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1684: }
                   1685: 
                   1686: # ------------------------------------------ Find current version of a resource
                   1687: 
                   1688: sub getversion {
                   1689:     my $fname=&clutter(shift);
                   1690:     unless ($fname=~/^\/res\//) { return -1; }
                   1691:     return &currentversion(&filelocation('',$fname));
                   1692: }
                   1693: 
                   1694: sub currentversion {
                   1695:     my $fname=shift;
1.599     albertel 1696:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1697:     if (defined($cached)) { return $result; }
1.292     www      1698:     my $author=$fname;
                   1699:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1700:     my ($udom,$uname)=split(/\//,$author);
                   1701:     my $home=homeserver($uname,$udom);
                   1702:     if ($home eq 'no_host') { 
                   1703:         return -1; 
                   1704:     }
                   1705:     my $answer=reply("currentversion:$fname",$home);
                   1706:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1707: 	return -1;
                   1708:     }
1.599     albertel 1709:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1710: }
                   1711: 
1.1       albertel 1712: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1713: 
1.1       albertel 1714: sub subscribe {
                   1715:     my $fname=shift;
1.761     raeburn  1716:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1717:     $fname=~s/[\n\r]//g;
1.1       albertel 1718:     my $author=$fname;
                   1719:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1720:     my ($udom,$uname)=split(/\//,$author);
                   1721:     my $home=homeserver($uname,$udom);
1.335     albertel 1722:     if ($home eq 'no_host') {
                   1723:         return 'not_found';
1.1       albertel 1724:     }
                   1725:     my $answer=reply("sub:$fname",$home);
1.64      www      1726:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1727: 	$answer.=' by '.$home;
                   1728:     }
1.1       albertel 1729:     return $answer;
                   1730: }
                   1731:     
1.8       www      1732: # -------------------------------------------------------------- Replicate file
                   1733: 
                   1734: sub repcopy {
                   1735:     my $filename=shift;
1.23      www      1736:     $filename=~s/\/+/\//g;
1.607     raeburn  1737:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1738:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1739:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1740: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1741: 	return &repcopy_userfile($filename);
                   1742:     }
1.532     albertel 1743:     $filename=~s/[\n\r]//g;
1.8       www      1744:     my $transname="$filename.in.transfer";
1.828     www      1745: # FIXME: this should flock
1.607     raeburn  1746:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1747:     my $remoteurl=subscribe($filename);
1.64      www      1748:     if ($remoteurl =~ /^con_lost by/) {
                   1749: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1750:            return 'unavailable';
1.8       www      1751:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1752: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1753: 	   return 'not_found';
1.64      www      1754:     } elsif ($remoteurl =~ /^rejected by/) {
                   1755: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1756:            return 'forbidden';
1.20      www      1757:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1758:            return 'ok';
1.8       www      1759:     } else {
1.290     www      1760:         my $author=$filename;
                   1761:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1762:         my ($udom,$uname)=split(/\//,$author);
                   1763:         my $home=homeserver($uname,$udom);
                   1764:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1765:            my @parts=split(/\//,$filename);
                   1766:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1767:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1768:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1769: 	       return 'bad_request';
1.8       www      1770:            }
                   1771:            my $count;
                   1772:            for ($count=5;$count<$#parts;$count++) {
                   1773:                $path.="/$parts[$count]";
                   1774:                if ((-e $path)!=1) {
                   1775: 		   mkdir($path,0777);
                   1776:                }
                   1777:            }
                   1778:            my $ua=new LWP::UserAgent;
                   1779:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1780:            my $response=$ua->request($request,$transname);
                   1781:            if ($response->is_error()) {
                   1782: 	       unlink($transname);
                   1783:                my $message=$response->status_line;
1.672     albertel 1784:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1785:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1786:                return 'unavailable';
1.8       www      1787:            } else {
1.16      www      1788: 	       if ($remoteurl!~/\.meta$/) {
                   1789:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1790:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1791:                   if ($mresponse->is_error()) {
                   1792: 		      unlink($filename.'.meta');
                   1793:                       &logthis(
1.672     albertel 1794:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1795:                   }
                   1796: 	       }
1.8       www      1797:                rename($transname,$filename);
1.607     raeburn  1798:                return 'ok';
1.8       www      1799:            }
1.290     www      1800:        }
1.8       www      1801:     }
1.330     www      1802: }
                   1803: 
                   1804: # ------------------------------------------------ Get server side include body
                   1805: sub ssi_body {
1.381     albertel 1806:     my ($filelink,%form)=@_;
1.606     matthew  1807:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1808:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1809:     }
1.953     www      1810:     my $output='';
                   1811:     my $response;
1.976.2.3  raeburn  1812:     if ($filelink=~/^https?\:/) {
1.954     raeburn  1813:        ($output,$response)=&externalssi($filelink);
1.953     www      1814:     } else {
                   1815:        ($output,$response)=&ssi($filelink,%form);
                   1816:     }
1.778     albertel 1817:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1818:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1819:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      1820:     if (wantarray) {
                   1821:         return ($output, $response);
                   1822:     } else {
                   1823:         return $output;
                   1824:     }
1.8       www      1825: }
                   1826: 
1.15      www      1827: # --------------------------------------------------------- Server Side Include
                   1828: 
1.782     albertel 1829: sub absolute_url {
                   1830:     my ($host_name) = @_;
                   1831:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1832:     if ($host_name eq '') {
                   1833: 	$host_name = $ENV{'SERVER_NAME'};
                   1834:     }
                   1835:     return $protocol.$host_name;
                   1836: }
                   1837: 
1.942     foxr     1838: #
                   1839: #   Server side include.
                   1840: # Parameters:
                   1841: #  fn     Possibly encrypted resource name/id.
                   1842: #  form   Hash that describes how the rendering should be done
                   1843: #         and other things.
1.944     foxr     1844: # Returns:
1.950     raeburn  1845: #   Scalar context: The content of the response.
                   1846: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     1847: #     
1.15      www      1848: sub ssi {
                   1849: 
1.944     foxr     1850:     my ($fn,%form)=@_;
1.15      www      1851:     my $ua=new LWP::UserAgent;
1.23      www      1852:     my $request;
1.711     albertel 1853: 
                   1854:     $form{'no_update_last_known'}=1;
1.895     albertel 1855:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1856:     if (%form) {
1.782     albertel 1857:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1858:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1859:     } else {
1.782     albertel 1860:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1861:     }
                   1862: 
1.15      www      1863:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1864:     my $response=$ua->request($request);
                   1865: 
1.944     foxr     1866:     if (wantarray) {
                   1867: 	return ($response->content, $response);
                   1868:     } else {
                   1869: 	return $response->content;
1.942     foxr     1870:     }
1.324     www      1871: }
                   1872: 
                   1873: sub externalssi {
                   1874:     my ($url)=@_;
                   1875:     my $ua=new LWP::UserAgent;
                   1876:     my $request=new HTTP::Request('GET',$url);
                   1877:     my $response=$ua->request($request);
1.954     raeburn  1878:     if (wantarray) {
                   1879:         return ($response->content, $response);
                   1880:     } else {
                   1881:         return $response->content;
                   1882:     }
1.15      www      1883: }
1.254     www      1884: 
1.492     albertel 1885: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1886: 
                   1887: sub allowuploaded {
                   1888:     my ($srcurl,$url)=@_;
                   1889:     $url=&clutter(&declutter($url));
                   1890:     my $dir=$url;
                   1891:     $dir=~s/\/[^\/]+$//;
                   1892:     my %httpref=();
                   1893:     my $httpurl=&hreflocation('',$url);
                   1894:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  1895:     &Apache::lonnet::appenv(\%httpref);
1.254     www      1896: }
1.477     raeburn  1897: 
1.478     albertel 1898: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1899: # input: action, courseID, current domain, intended
1.637     raeburn  1900: #        path to file, source of file, instruction to parse file for objects,
                   1901: #        ref to hash for embedded objects,
                   1902: #        ref to hash for codebase of java objects.
                   1903: #
1.485     raeburn  1904: # output: url to file (if action was uploaddoc), 
                   1905: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1906: #
1.478     albertel 1907: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1908: # course.
1.477     raeburn  1909: #
1.478     albertel 1910: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1911: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1912: #          course's home server.
1.477     raeburn  1913: #
1.478     albertel 1914: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1915: #          be copied from $source (current location) to 
                   1916: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1917: #         and will then be copied to
                   1918: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1919: #         course's home server.
1.485     raeburn  1920: #
1.481     raeburn  1921: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1922: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1923: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1924: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1925: #         in course's home server.
1.637     raeburn  1926: #
1.477     raeburn  1927: 
                   1928: sub process_coursefile {
1.638     albertel 1929:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1930:     my $fetchresult;
1.638     albertel 1931:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1932:     if ($action eq 'propagate') {
1.638     albertel 1933:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1934: 			     $home);
1.481     raeburn  1935:     } else {
1.477     raeburn  1936:         my $fpath = '';
                   1937:         my $fname = $file;
1.478     albertel 1938:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1939:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1940:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1941:         if ($action eq 'copy') {
                   1942:             if ($source eq '') {
                   1943:                 $fetchresult = 'no source file';
                   1944:                 return $fetchresult;
                   1945:             } else {
                   1946:                 my $destination = $filepath.'/'.$fname;
                   1947:                 rename($source,$destination);
                   1948:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1949:                                  $home);
1.481     raeburn  1950:             }
                   1951:         } elsif ($action eq 'uploaddoc') {
                   1952:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1953:             print $fh $env{'form.'.$source};
1.481     raeburn  1954:             close($fh);
1.637     raeburn  1955:             if ($parser eq 'parse') {
1.961     raeburn  1956:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
1.637     raeburn  1957:                 unless ($parse_result eq 'ok') {
                   1958:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1959:                 }
                   1960:             }
1.477     raeburn  1961:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1962:                                  $home);
1.481     raeburn  1963:             if ($fetchresult eq 'ok') {
                   1964:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1965:             } else {
                   1966:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1967:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1968:                 return '/adm/notfound.html';
                   1969:             }
1.477     raeburn  1970:         }
                   1971:     }
1.485     raeburn  1972:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1973:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1974:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1975:     }
                   1976:     return $fetchresult;
                   1977: }
                   1978: 
1.637     raeburn  1979: sub build_filepath {
                   1980:     my ($fpath) = @_;
                   1981:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1982:     unless ($fpath eq '') {
                   1983:         my @parts=split('/',$fpath);
                   1984:         foreach my $part (@parts) {
                   1985:             $filepath.= '/'.$part;
                   1986:             if ((-e $filepath)!=1) {
                   1987:                 mkdir($filepath,0777);
                   1988:             }
                   1989:         }
                   1990:     }
                   1991:     return $filepath;
                   1992: }
                   1993: 
                   1994: sub store_edited_file {
1.638     albertel 1995:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1996:     my $file = $primary_url;
                   1997:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1998:     my $fpath = '';
                   1999:     my $fname = $file;
                   2000:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2001:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2002:     my $filepath = &build_filepath($fpath);
                   2003:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2004:     print $fh $content;
                   2005:     close($fh);
1.638     albertel 2006:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2007:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2008: 			  $home);
1.637     raeburn  2009:     if ($$fetchresult eq 'ok') {
                   2010:         return '/uploaded/'.$fpath.'/'.$fname;
                   2011:     } else {
1.638     albertel 2012:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2013: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2014:         return '/adm/notfound.html';
                   2015:     }
                   2016: }
                   2017: 
1.531     albertel 2018: sub clean_filename {
1.831     albertel 2019:     my ($fname,$args)=@_;
1.315     www      2020: # Replace Windows backslashes by forward slashes
1.257     www      2021:     $fname=~s/\\/\//g;
1.831     albertel 2022:     if (!$args->{'keep_path'}) {
                   2023:         # Get rid of everything but the actual filename
                   2024: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2025:     }
1.315     www      2026: # Replace spaces by underscores
                   2027:     $fname=~s/\s+/\_/g;
                   2028: # Replace all other weird characters by nothing
1.831     albertel 2029:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2030: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2031: # numbers
                   2032:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2033:     return $fname;
                   2034: }
                   2035: 
1.608     albertel 2036: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2037: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 2038: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 2039: #        $coursedoc - if true up to the current course
                   2040: #                     if false
                   2041: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2042: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2043: #        $allfiles - reference to hash for embedded objects
                   2044: #        $codebase - reference to hash for codebase of java objects
                   2045: #        $desuname - username for permanent storage of uploaded file
                   2046: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2047: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2048: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  2049: # 
1.686     albertel 2050: # output: url of file in userspace, or error: <message> 
                   2051: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2052: 
                   2053: 
1.531     albertel 2054: sub userfileupload {
1.860     raeburn  2055:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   2056:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 2057:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2058:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2059:     $fname=&clean_filename($fname);
1.315     www      2060: # See if there is anything left
1.257     www      2061:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 2062:     chop($env{'form.'.$formname});
1.523     raeburn  2063:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   2064:         my $now = time;
                   2065:         my $filepath = 'tmp/helprequests/'.$now;
                   2066:         my @parts=split(/\//,$filepath);
                   2067:         my $fullpath = $perlvar{'lonDaemons'};
                   2068:         for (my $i=0;$i<@parts;$i++) {
                   2069:             $fullpath .= '/'.$parts[$i];
                   2070:             if ((-e $fullpath)!=1) {
                   2071:                 mkdir($fullpath,0777);
                   2072:             }
                   2073:         }
                   2074:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 2075:         print $fh $env{'form.'.$formname};
1.523     raeburn  2076:         close($fh);
1.741     raeburn  2077:         return $fullpath.'/'.$fname;
                   2078:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   2079:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2080:                        '_'.$env{'user.domain'}.'/pending';
                   2081:         my @parts=split(/\//,$filepath);
                   2082:         my $fullpath = $perlvar{'lonDaemons'};
                   2083:         for (my $i=0;$i<@parts;$i++) {
                   2084:             $fullpath .= '/'.$parts[$i];
                   2085:             if ((-e $fullpath)!=1) {
                   2086:                 mkdir($fullpath,0777);
                   2087:             }
                   2088:         }
                   2089:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2090:         print $fh $env{'form.'.$formname};
                   2091:         close($fh);
                   2092:         return $fullpath.'/'.$fname;
1.523     raeburn  2093:     }
1.719     banghart 2094:     
1.258     www      2095: # Create the directory if not present
1.493     albertel 2096:     $fname="$subdir/$fname";
1.259     www      2097:     if ($coursedoc) {
1.638     albertel 2098: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2099: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2100:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2101:             return &finishuserfileupload($docuname,$docudom,
                   2102: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  2103: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  2104:         } else {
1.620     albertel 2105:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2106:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2107: 				       $fname,$formname,$parser,
                   2108: 				       $allfiles,$codebase);
1.481     raeburn  2109:         }
1.719     banghart 2110:     } elsif (defined($destuname)) {
                   2111:         my $docuname=$destuname;
                   2112:         my $docudom=$destudom;
1.860     raeburn  2113: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2114: 				     $parser,$allfiles,$codebase,
                   2115:                                      $thumbwidth,$thumbheight);
1.719     banghart 2116:         
1.259     www      2117:     } else {
1.638     albertel 2118:         my $docuname=$env{'user.name'};
                   2119:         my $docudom=$env{'user.domain'};
1.714     raeburn  2120:         if (exists($env{'form.group'})) {
                   2121:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2122:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2123:         }
1.860     raeburn  2124: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2125: 				     $parser,$allfiles,$codebase,
                   2126:                                      $thumbwidth,$thumbheight);
1.259     www      2127:     }
1.271     www      2128: }
                   2129: 
                   2130: sub finishuserfileupload {
1.860     raeburn  2131:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   2132:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  2133:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2134:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  2135:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2136:     $file=$fname;
                   2137:     if ($fname=~m|/|) {
                   2138:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2139: 	$path.=$fnamepath.'/';
                   2140:     }
1.259     www      2141:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2142:     my $count;
                   2143:     for ($count=4;$count<=$#parts;$count++) {
                   2144:         $filepath.="/$parts[$count]";
                   2145:         if ((-e $filepath)!=1) {
                   2146: 	    mkdir($filepath,0777);
                   2147:         }
                   2148:     }
                   2149: # Save the file
                   2150:     {
1.701     albertel 2151: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2152: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2153: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2154: 	    return '/adm/notfound.html';
                   2155: 	}
                   2156: 	if (!print FH ($env{'form.'.$formname})) {
                   2157: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2158: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2159: 	    return '/adm/notfound.html';
                   2160: 	}
1.570     albertel 2161: 	close(FH);
1.258     www      2162:     }
1.637     raeburn  2163:     if ($parser eq 'parse') {
1.961     raeburn  2164:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
1.638     albertel 2165: 						   $codebase);
1.637     raeburn  2166:         unless ($parse_result eq 'ok') {
1.638     albertel 2167:             &logthis('Failed to parse '.$filepath.$file.
                   2168: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  2169:         }
                   2170:     }
1.860     raeburn  2171:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2172:         my $input = $filepath.'/'.$file;
                   2173:         my $output = $filepath.'/'.'tn-'.$file;
                   2174:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2175:         system("convert -sample $thumbsize $input $output");
                   2176:         if (-e $filepath.'/'.'tn-'.$file) {
                   2177:             $fetchthumb  = 1; 
                   2178:         }
                   2179:     }
1.858     raeburn  2180:  
1.259     www      2181: # Notify homeserver to grep it
                   2182: #
1.638     albertel 2183:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 2184:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2185:     if ($fetchresult eq 'ok') {
1.860     raeburn  2186:         if ($fetchthumb) {
                   2187:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2188:             if ($thumbresult ne 'ok') {
                   2189:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2190:                          $docuhome.': '.$thumbresult);
                   2191:             }
                   2192:         }
1.259     www      2193: #
1.258     www      2194: # Return the URL to it
1.494     albertel 2195:         return '/uploaded/'.$path.$file;
1.263     www      2196:     } else {
1.494     albertel 2197:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2198: 		 ': '.$fetchresult);
1.263     www      2199:         return '/adm/notfound.html';
1.858     raeburn  2200:     }
1.493     albertel 2201: }
                   2202: 
1.637     raeburn  2203: sub extract_embedded_items {
1.961     raeburn  2204:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2205:     my @state = ();
                   2206:     my %javafiles = (
                   2207:                       codebase => '',
                   2208:                       code => '',
                   2209:                       archive => ''
                   2210:                     );
                   2211:     my %mediafiles = (
                   2212:                       src => '',
                   2213:                       movie => '',
                   2214:                      );
1.648     raeburn  2215:     my $p;
                   2216:     if ($content) {
                   2217:         $p = HTML::LCParser->new($content);
                   2218:     } else {
1.961     raeburn  2219:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  2220:     }
1.641     albertel 2221:     while (my $t=$p->get_token()) {
1.640     albertel 2222: 	if ($t->[0] eq 'S') {
                   2223: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2224: 	    push(@state, $tagname);
1.648     raeburn  2225:             if (lc($tagname) eq 'allow') {
                   2226:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2227:             }
1.640     albertel 2228: 	    if (lc($tagname) eq 'img') {
                   2229: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2230: 	    }
1.886     albertel 2231: 	    if (lc($tagname) eq 'a') {
                   2232: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2233: 	    }
1.645     raeburn  2234:             if (lc($tagname) eq 'script') {
                   2235:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2236:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2237:                 } else {
                   2238:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2239:                 }
                   2240:             }
                   2241:             if (lc($tagname) eq 'link') {
                   2242:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2243:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2244:                 }
                   2245:             }
1.640     albertel 2246: 	    if (lc($tagname) eq 'object' ||
                   2247: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2248: 		foreach my $item (keys(%javafiles)) {
                   2249: 		    $javafiles{$item} = '';
                   2250: 		}
                   2251: 	    }
                   2252: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2253: 		my $name = lc($attr->{'name'});
                   2254: 		foreach my $item (keys(%javafiles)) {
                   2255: 		    if ($name eq $item) {
                   2256: 			$javafiles{$item} = $attr->{'value'};
                   2257: 			last;
                   2258: 		    }
                   2259: 		}
                   2260: 		foreach my $item (keys(%mediafiles)) {
                   2261: 		    if ($name eq $item) {
                   2262: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2263: 			last;
                   2264: 		    }
                   2265: 		}
                   2266: 	    }
                   2267: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2268: 		foreach my $item (keys(%javafiles)) {
                   2269: 		    if ($attr->{$item}) {
                   2270: 			$javafiles{$item} = $attr->{$item};
                   2271: 			last;
                   2272: 		    }
                   2273: 		}
                   2274: 		foreach my $item (keys(%mediafiles)) {
                   2275: 		    if ($attr->{$item}) {
                   2276: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2277: 			last;
                   2278: 		    }
                   2279: 		}
                   2280: 	    }
                   2281: 	} elsif ($t->[0] eq 'E') {
                   2282: 	    my ($tagname) = ($t->[1]);
                   2283: 	    if ($javafiles{'codebase'} ne '') {
                   2284: 		$javafiles{'codebase'} .= '/';
                   2285: 	    }  
                   2286: 	    if (lc($tagname) eq 'applet' ||
                   2287: 		lc($tagname) eq 'object' ||
                   2288: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2289: 		) {
                   2290: 		foreach my $item (keys(%javafiles)) {
                   2291: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2292: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2293: 			&add_filetype($allfiles,$file,$item);
                   2294: 		    }
                   2295: 		}
                   2296: 	    } 
                   2297: 	    pop @state;
                   2298: 	}
                   2299:     }
1.637     raeburn  2300:     return 'ok';
                   2301: }
                   2302: 
1.639     albertel 2303: sub add_filetype {
                   2304:     my ($allfiles,$file,$type)=@_;
                   2305:     if (exists($allfiles->{$file})) {
                   2306: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2307: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2308: 	}
                   2309:     } else {
                   2310: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2311:     }
                   2312: }
                   2313: 
1.493     albertel 2314: sub removeuploadedurl {
                   2315:     my ($url)=@_;
                   2316:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 2317:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2318: }
                   2319: 
                   2320: sub removeuserfile {
                   2321:     my ($docuname,$docudom,$fname)=@_;
                   2322:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2323:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   2324:     if ($result eq 'ok') {
                   2325:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2326:             my $metafile = $fname.'.meta';
                   2327:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2328: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   2329:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2330:             my $sqlresult = 
1.823     albertel 2331:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2332:                                         'portfolio_metadata',$group,
                   2333:                                         'delete');
1.798     raeburn  2334:         }
                   2335:     }
                   2336:     return $result;
1.257     www      2337: }
1.15      www      2338: 
1.530     albertel 2339: sub mkdiruserfile {
                   2340:     my ($docuname,$docudom,$dir)=@_;
                   2341:     my $home=&homeserver($docuname,$docudom);
                   2342:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2343: }
                   2344: 
1.531     albertel 2345: sub renameuserfile {
                   2346:     my ($docuname,$docudom,$old,$new)=@_;
                   2347:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2348:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2349:                         &escape("$old").':'.&escape("$new"),$home);
                   2350:     if ($result eq 'ok') {
                   2351:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2352:             my $oldmeta = $old.'.meta';
                   2353:             my $newmeta = $new.'.meta';
                   2354:             my $metaresult = 
                   2355:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2356: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2357:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2358:             my $sqlresult = 
1.823     albertel 2359:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2360:                                         'portfolio_metadata',$group,
                   2361:                                         'delete');
1.798     raeburn  2362:         }
                   2363:     }
                   2364:     return $result;
1.531     albertel 2365: }
                   2366: 
1.14      www      2367: # ------------------------------------------------------------------------- Log
                   2368: 
                   2369: sub log {
                   2370:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2371:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2372: }
                   2373: 
                   2374: # ------------------------------------------------------------------ Course Log
1.352     www      2375: #
                   2376: # This routine flushes several buffers of non-mission-critical nature
                   2377: #
1.157     www      2378: 
                   2379: sub flushcourselogs {
1.352     www      2380:     &logthis('Flushing log buffers');
                   2381: #
                   2382: # course logs
                   2383: # This is a log of all transactions in a course, which can be used
                   2384: # for data mining purposes
                   2385: #
                   2386: # It also collects the courseid database, which lists last transaction
                   2387: # times and course titles for all courseids
                   2388: #
                   2389:     my %courseidbuffer=();
1.921     raeburn  2390:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2391:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2392: 		          &escape($courselogs{$crsid}),
                   2393: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2394: 	    delete $courselogs{$crsid};
                   2395:         } else {
                   2396:             &logthis('Failed to flush log buffer for '.$crsid);
                   2397:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2398:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2399:                         " exceeded maximum size, deleting.</font>");
                   2400:                delete $courselogs{$crsid};
                   2401:             }
1.352     www      2402:         }
1.920     raeburn  2403:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2404:             'description' => $coursedescrbuf{$crsid},
                   2405:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2406:             'type'        => $coursetypebuf{$crsid},
                   2407:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2408:         };
1.191     harris41 2409:     }
1.352     www      2410: #
                   2411: # Write course id database (reverse lookup) to homeserver of courses 
                   2412: # Is used in pickcourse
                   2413: #
1.840     albertel 2414:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2415:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2416:                                     $courseidbuffer{$crs_home},
                   2417:                                     $crs_home,'timeonly');
1.352     www      2418:     }
                   2419: #
                   2420: # File accesses
                   2421: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2422: #
1.449     matthew  2423:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2424:         if ($entry =~ /___count$/) {
                   2425:             my ($dom,$name);
1.807     albertel 2426:             ($dom,$name,undef)=
1.811     albertel 2427: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2428:             if (! defined($dom) || $dom eq '' || 
                   2429:                 ! defined($name) || $name eq '') {
1.620     albertel 2430:                 my $cid = $env{'request.course.id'};
                   2431:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2432:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2433:             }
1.450     matthew  2434:             my $value = $accesshash{$entry};
                   2435:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2436:             my %temphash=($url => $value);
1.449     matthew  2437:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2438:             if ($result eq 'ok') {
                   2439:                 delete $accesshash{$entry};
                   2440:             } elsif ($result eq 'unknown_cmd') {
                   2441:                 # Target server has old code running on it.
1.450     matthew  2442:                 my %temphash=($entry => $value);
1.449     matthew  2443:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2444:                     delete $accesshash{$entry};
                   2445:                 }
                   2446:             }
                   2447:         } else {
1.811     albertel 2448:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2449:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2450:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2451:                 delete $accesshash{$entry};
                   2452:             }
1.185     www      2453:         }
1.191     harris41 2454:     }
1.352     www      2455: #
                   2456: # Roles
                   2457: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2458: #
1.800     albertel 2459:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2460:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2461: 	    split(/\:/,$entry);
                   2462:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2463:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2464:                 $rudom,$runame) eq 'ok') {
                   2465: 	    delete $userrolehash{$entry};
                   2466:         }
                   2467:     }
1.662     raeburn  2468: #
                   2469: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2470: #
                   2471:     my %domrolebuffer = ();
                   2472:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2473:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2474:         if ($domrolebuffer{$rudom}) {
                   2475:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2476:                       '='.&escape($domainrolehash{$entry});
                   2477:         } else {
                   2478:             $domrolebuffer{$rudom}.=&escape($entry).
                   2479:                       '='.&escape($domainrolehash{$entry});
                   2480:         }
                   2481:         delete $domainrolehash{$entry};
                   2482:     }
                   2483:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2484: 	my %servers = &get_servers($dom,'library');
                   2485: 	foreach my $tryserver (keys(%servers)) {
                   2486: 	    unless (&reply('domroleput:'.$dom.':'.
                   2487: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2488: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2489: 	    }
1.662     raeburn  2490:         }
                   2491:     }
1.186     www      2492:     $dumpcount++;
1.157     www      2493: }
                   2494: 
                   2495: sub courselog {
                   2496:     my $what=shift;
1.158     www      2497:     $what=time.':'.$what;
1.620     albertel 2498:     unless ($env{'request.course.id'}) { return ''; }
                   2499:     $coursedombuf{$env{'request.course.id'}}=
                   2500:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2501:     $coursenumbuf{$env{'request.course.id'}}=
                   2502:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2503:     $coursehombuf{$env{'request.course.id'}}=
                   2504:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2505:     $coursedescrbuf{$env{'request.course.id'}}=
                   2506:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2507:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2508:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2509:     $courseownerbuf{$env{'request.course.id'}}=
                   2510:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2511:     $coursetypebuf{$env{'request.course.id'}}=
                   2512:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2513:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2514: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2515:     } else {
1.620     albertel 2516: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2517:     }
1.620     albertel 2518:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2519: 	&flushcourselogs();
                   2520:     }
1.158     www      2521: }
                   2522: 
                   2523: sub courseacclog {
                   2524:     my $fnsymb=shift;
1.620     albertel 2525:     unless ($env{'request.course.id'}) { return ''; }
                   2526:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2527:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2528:         $what.=':POST';
1.583     matthew  2529:         # FIXME: Probably ought to escape things....
1.800     albertel 2530: 	foreach my $key (keys(%env)) {
                   2531:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  2532:                 my $formitem = $1;
                   2533:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   2534:                     $what.=':'.$formitem.'='.$env{$key};
                   2535:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   2536:                     $what.=':'.$formitem.'='.$env{$key};
                   2537:                 }
1.158     www      2538:             }
1.191     harris41 2539:         }
1.583     matthew  2540:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2541:         # FIXME: We should not be depending on a form parameter that someone
                   2542:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2543:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2544:             $what.= ':POST';
                   2545:             # FIXME: Probably ought to escape things....
                   2546:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2547:                                  'crsdiscuss') {
1.620     albertel 2548:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2549:             }
                   2550:         }
1.158     www      2551:     }
                   2552:     &courselog($what);
1.149     www      2553: }
                   2554: 
1.185     www      2555: sub countacc {
                   2556:     my $url=&declutter(shift);
1.458     matthew  2557:     return if (! defined($url) || $url eq '');
1.620     albertel 2558:     unless ($env{'request.course.id'}) { return ''; }
                   2559:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2560:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2561:     $accesshash{$key}++;
1.185     www      2562: }
1.349     www      2563: 
1.361     www      2564: sub linklog {
                   2565:     my ($from,$to)=@_;
                   2566:     $from=&declutter($from);
                   2567:     $to=&declutter($to);
                   2568:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2569:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2570: }
                   2571:   
1.349     www      2572: sub userrolelog {
                   2573:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2574:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2575:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2576:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2577:         ($trole=~/^ta/)) {
1.350     www      2578:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2579:        $userrolehash
                   2580:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2581:                     =$tend.':'.$tstart;
1.662     raeburn  2582:     }
1.898     albertel 2583:     if (($env{'request.role'} =~ /dc\./) &&
                   2584: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2585: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2586: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2587:        $userrolehash
                   2588:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2589:                     =$tend.':'.$tstart;
                   2590:     }
1.662     raeburn  2591:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2592:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2593:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2594:         ($trole=~/^sc/)) {
                   2595:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2596:        $domainrolehash
                   2597:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2598:                     = $tend.':'.$tstart;
                   2599:     }
1.351     www      2600: }
                   2601: 
1.957     raeburn  2602: sub courserolelog {
                   2603:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   2604:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   2605:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   2606:         ($trole eq 'ta') || ($trole eq 'st') ||
                   2607:         ($trole=~/^cr/) || ($trole eq 'gr')) {
                   2608:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   2609:             my $cdom = $1;
                   2610:             my $cnum = $2;
                   2611:             my $sec = $3;
                   2612:             my $namespace = 'rolelog';
                   2613:             my %storehash = (
                   2614:                                role    => $trole,
                   2615:                                start   => $tstart,
                   2616:                                end     => $tend,
                   2617:                                selfenroll => $selfenroll,
                   2618:                                context    => $context,
                   2619:                             );
                   2620:             if ($trole eq 'gr') {
                   2621:                 $namespace = 'groupslog';
                   2622:                 $storehash{'group'} = $sec;
                   2623:             } else {
                   2624:                 $storehash{'section'} = $sec;
                   2625:             }
                   2626:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.976.2.8! raeburn  2627:             if (($trole ne 'st') || ($sec ne '')) {
        !          2628:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
        !          2629:             }
1.957     raeburn  2630:         }
                   2631:     }
                   2632:     return;
                   2633: }
                   2634: 
1.351     www      2635: sub get_course_adv_roles {
1.948     raeburn  2636:     my ($cid,$codes) = @_;
1.620     albertel 2637:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2638:     my %coursehash=&coursedescription($cid);
1.470     www      2639:     my %nothide=();
1.800     albertel 2640:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2641:         if ($user !~ /:/) {
                   2642: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2643:         } else {
                   2644:             $nothide{$user}=1;
                   2645:         }
1.470     www      2646:     }
1.351     www      2647:     my %returnhash=();
                   2648:     my %dumphash=
                   2649:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2650:     my $now=time;
1.976.2.8! raeburn  2651:     my %privileged;
1.800     albertel 2652:     foreach my $entry (keys %dumphash) {
                   2653: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2654:         if (($tstart) && ($tstart<0)) { next; }
                   2655:         if (($tend) && ($tend<$now)) { next; }
                   2656:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2657:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2658: 	if ($username eq '' || $domain eq '') { next; }
1.976.2.8! raeburn  2659:         unless (ref($privileged{$domain}) eq 'HASH') {
        !          2660:             my %dompersonnel =
        !          2661:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
        !          2662:             $privileged{$domain} = {};
        !          2663:             foreach my $server (keys(%dompersonnel)) {
        !          2664:                 if (ref($dompersonnel{$server}) eq 'HASH') {
        !          2665:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
        !          2666:                         my ($trole,$uname,$udom) = split(/:/,$user);
        !          2667:                         $privileged{$udom}{$uname} = 1;
        !          2668:                     }
        !          2669:                 }
        !          2670:             }
        !          2671:         }
        !          2672:         if ((exists($privileged{$domain}{$username})) &&
        !          2673:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2674: 	if ($role eq 'cr') { next; }
1.948     raeburn  2675:         if ($codes) {
                   2676:             if ($section) { $role .= ':'.$section; }
                   2677:             if ($returnhash{$role}) {
                   2678:                 $returnhash{$role}.=','.$username.':'.$domain;
                   2679:             } else {
                   2680:                 $returnhash{$role}=$username.':'.$domain;
                   2681:             }
1.351     www      2682:         } else {
1.948     raeburn  2683:             my $key=&plaintext($role);
1.973     bisitz   2684:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  2685:             if ($returnhash{$key}) {
                   2686: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   2687:             } else {
                   2688:                 $returnhash{$key}=$username.':'.$domain;
                   2689:             }
1.351     www      2690:         }
1.948     raeburn  2691:     }
1.400     www      2692:     return %returnhash;
                   2693: }
                   2694: 
                   2695: sub get_my_roles {
1.937     raeburn  2696:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2697:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2698:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2699:     my (%dumphash,%nothide);
1.858     raeburn  2700:     if ($context eq 'userroles') { 
                   2701:         %dumphash = &dump('roles',$udom,$uname);
                   2702:     } else {
                   2703:         %dumphash=
1.400     www      2704:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2705:         if ($hidepriv) {
                   2706:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2707:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2708:                 if ($user !~ /:/) {
                   2709:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2710:                 } else {
                   2711:                     $nothide{$user} = 1;
                   2712:                 }
                   2713:             }
                   2714:         }
1.858     raeburn  2715:     }
1.400     www      2716:     my %returnhash=();
                   2717:     my $now=time;
1.800     albertel 2718:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2719:         my ($role,$tend,$tstart);
                   2720:         if ($context eq 'userroles') {
                   2721: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2722:         } else {
                   2723:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2724:         }
1.400     www      2725:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2726:         my $status = 'active';
1.939     raeburn  2727:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2728:             $status = 'previous';
                   2729:         } 
                   2730:         if (($tstart) && ($now<$tstart)) {
                   2731:             $status = 'future';
                   2732:         }
                   2733:         if (ref($types) eq 'ARRAY') {
                   2734:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2735:                 next;
                   2736:             } 
                   2737:         } else {
                   2738:             if ($status ne 'active') {
                   2739:                 next;
                   2740:             }
                   2741:         }
1.867     raeburn  2742:         my ($rolecode,$username,$domain,$section,$area);
                   2743:         if ($context eq 'userroles') {
                   2744:             ($area,$rolecode) = split(/_/,$entry);
                   2745:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2746:         } else {
                   2747:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2748:         }
1.832     raeburn  2749:         if (ref($roledoms) eq 'ARRAY') {
                   2750:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2751:                 next;
                   2752:             }
                   2753:         }
                   2754:         if (ref($roles) eq 'ARRAY') {
                   2755:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2756:                 if ($role =~ /^cr\//) {
                   2757:                     if (!grep(/^cr$/,@{$roles})) {
                   2758:                         next;
                   2759:                     }
                   2760:                 } else {
                   2761:                     next;
                   2762:                 }
1.832     raeburn  2763:             }
1.867     raeburn  2764:         }
1.937     raeburn  2765:         if ($hidepriv) {
1.976.2.8! raeburn  2766:             if ($context eq 'userroles') {
        !          2767:                 if ((&privileged($username,$domain)) &&
        !          2768:                     (!$nothide{$username.':'.$domain})) {
        !          2769:                     next;
        !          2770:                 }
        !          2771:             } else {
        !          2772:                 unless (ref($privileged{$domain}) eq 'HASH') {
        !          2773:                     my %dompersonnel =
        !          2774:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
        !          2775:                     $privileged{$domain} = {};
        !          2776:                     if (keys(%dompersonnel)) {
        !          2777:                         foreach my $server (keys(%dompersonnel)) {
        !          2778:                             if (ref($dompersonnel{$server}) eq 'HASH') {
        !          2779:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
        !          2780:                                     my ($trole,$uname,$udom) = split(/:/,$user);
        !          2781:                                     $privileged{$udom}{$uname} = $trole;
        !          2782:                                 }
        !          2783:                             }
        !          2784:                         }
        !          2785:                     }
        !          2786:                 }
        !          2787:                 if (exists($privileged{$domain}{$username})) {
        !          2788:                     if (!$nothide{$username.':'.$domain}) {
        !          2789:                         next;
        !          2790:                     }
        !          2791:                 }
1.937     raeburn  2792:             }
                   2793:         }
1.933     raeburn  2794:         if ($withsec) {
                   2795:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2796:                 $tstart.':'.$tend;
                   2797:         } else {
                   2798:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2799:         }
1.832     raeburn  2800:     }
1.373     www      2801:     return %returnhash;
1.399     www      2802: }
                   2803: 
                   2804: # ----------------------------------------------------- Frontpage Announcements
                   2805: #
                   2806: #
                   2807: 
                   2808: sub postannounce {
                   2809:     my ($server,$text)=@_;
1.844     albertel 2810:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2811:     unless ($text=~/\w/) { $text=''; }
                   2812:     return &reply('setannounce:'.&escape($text),$server);
                   2813: }
                   2814: 
                   2815: sub getannounce {
1.448     albertel 2816: 
                   2817:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2818: 	my $announcement='';
1.800     albertel 2819: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2820: 	close($fh);
1.399     www      2821: 	if ($announcement=~/\w/) { 
                   2822: 	    return 
                   2823:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2824:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2825: 	} else {
                   2826: 	    return '';
                   2827: 	}
                   2828:     } else {
                   2829: 	return '';
                   2830:     }
1.351     www      2831: }
1.353     www      2832: 
                   2833: # ---------------------------------------------------------- Course ID routines
                   2834: # Deal with domain's nohist_courseid.db files
                   2835: #
                   2836: 
                   2837: sub courseidput {
1.921     raeburn  2838:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2839:     my $outcome;
                   2840:     if ($caller eq 'timeonly') {
                   2841:         my $cids = '';
                   2842:         foreach my $item (keys(%$storehash)) {
                   2843:             $cids.=&escape($item).'&';
                   2844:         }
                   2845:         $cids=~s/\&$//;
                   2846:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2847:                           $coursehome);       
                   2848:     } else {
                   2849:         my $items = '';
                   2850:         foreach my $item (keys(%$storehash)) {
                   2851:             $items.= &escape($item).'='.
                   2852:                      &freeze_escape($$storehash{$item}).'&';
                   2853:         }
                   2854:         $items=~s/\&$//;
                   2855:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2856:                           $coursehome);
1.918     raeburn  2857:     }
                   2858:     if ($outcome eq 'unknown_cmd') {
                   2859:         my $what;
                   2860:         foreach my $cid (keys(%$storehash)) {
                   2861:             $what .= &escape($cid).'=';
1.921     raeburn  2862:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2863:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2864:             }
                   2865:             $what =~ s/\:$/&/;
                   2866:         }
                   2867:         $what =~ s/\&$//;  
                   2868:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2869:     } else {
                   2870:         return $outcome;
                   2871:     }
1.353     www      2872: }
                   2873: 
                   2874: sub courseiddump {
1.921     raeburn  2875:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  2876:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.962     raeburn  2877:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
1.918     raeburn  2878:     my $as_hash = 1;
                   2879:     my %returnhash;
                   2880:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2881:     my %libserv = &all_library();
                   2882:     foreach my $tryserver (keys(%libserv)) {
                   2883:         if ( (  $hostidflag == 1 
                   2884: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2885: 	     || (!defined($hostidflag)) ) {
                   2886: 
1.918     raeburn  2887: 	    if (($domfilter eq '') ||
                   2888: 		(&host_domain($tryserver) eq $domfilter)) {
                   2889:                 my $rep = 
                   2890:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2891:                          $sincefilter.':'.&escape($descfilter).':'.
                   2892:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2893:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  2894:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  2895:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   2896:                          $showhidden.':'.$caller,$tryserver);
1.918     raeburn  2897:                 my @pairs=split(/\&/,$rep);
                   2898:                 foreach my $item (@pairs) {
                   2899:                     my ($key,$value)=split(/\=/,$item,2);
                   2900:                     $key = &unescape($key);
                   2901:                     next if ($key =~ /^error: 2 /);
                   2902:                     my $result = &thaw_unescape($value);
                   2903:                     if (ref($result) eq 'HASH') {
                   2904:                         $returnhash{$key}=$result;
                   2905:                     } else {
1.921     raeburn  2906:                         my @responses = split(/:/,$value);
                   2907:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  2908:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  2909:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  2910:                         }
                   2911:                     } 
1.353     www      2912:                 }
                   2913:             }
                   2914:         }
                   2915:     }
                   2916:     return %returnhash;
                   2917: }
                   2918: 
1.658     raeburn  2919: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2920: 
                   2921: sub dcmailput {
1.685     raeburn  2922:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2923:     my $status = &Apache::lonnet::critical(
1.740     www      2924:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2925:        &escape($message),$server);
1.662     raeburn  2926:     return $status;
                   2927: }
                   2928: 
1.658     raeburn  2929: sub dcmaildump {
                   2930:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2931:     my %returnhash=();
1.846     albertel 2932: 
                   2933:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2934:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2935:                                                          &escape($enddate).':';
                   2936: 	my @esc_senders=map { &escape($_)} @$senders;
                   2937: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2938: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2939:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2940:             if (($key) && ($value)) {
                   2941:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2942:             }
                   2943:         }
                   2944:     }
                   2945:     return %returnhash;
                   2946: }
1.662     raeburn  2947: # ---------------------------------------------------------- Domain roles
                   2948: 
                   2949: sub get_domain_roles {
                   2950:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2951:     if (undef($startdate) || $startdate eq '') {
                   2952:         $startdate = '.';
                   2953:     }
                   2954:     if (undef($enddate) || $enddate eq '') {
                   2955:         $enddate = '.';
                   2956:     }
1.922     raeburn  2957:     my $rolelist;
                   2958:     if (ref($roles) eq 'ARRAY') {
                   2959:         $rolelist = join(':',@{$roles});
                   2960:     }
1.662     raeburn  2961:     my %personnel = ();
1.841     albertel 2962: 
                   2963:     my %servers = &get_servers($dom,'library');
                   2964:     foreach my $tryserver (keys(%servers)) {
                   2965: 	%{$personnel{$tryserver}}=();
                   2966: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2967: 					    &escape($startdate).':'.
                   2968: 					    &escape($enddate).':'.
                   2969: 					    &escape($rolelist), $tryserver))) {
                   2970: 	    my ($key,$value) = split(/\=/,$line,2);
                   2971: 	    if (($key) && ($value)) {
                   2972: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2973: 	    }
                   2974: 	}
1.662     raeburn  2975:     }
                   2976:     return %personnel;
                   2977: }
1.658     raeburn  2978: 
1.149     www      2979: # ----------------------------------------------------------- Check out an item
                   2980: 
1.504     albertel 2981: sub get_first_access {
                   2982:     my ($type,$argsymb)=@_;
1.790     albertel 2983:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2984:     if ($argsymb) { $symb=$argsymb; }
                   2985:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 2986:     if ($type eq 'course') {
                   2987: 	$res='course';
                   2988:     } elsif ($type eq 'map') {
1.588     albertel 2989: 	$res=&symbread($map);
                   2990:     } else {
                   2991: 	$res=$symb;
                   2992:     }
                   2993:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2994:     return $times{"$courseid\0$res"};
1.504     albertel 2995: }
                   2996: 
                   2997: sub set_first_access {
                   2998:     my ($type)=@_;
1.790     albertel 2999:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3000:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3001:     if ($type eq 'course') {
                   3002: 	$res='course';
                   3003:     } elsif ($type eq 'map') {
1.588     albertel 3004: 	$res=&symbread($map);
                   3005:     } else {
                   3006: 	$res=$symb;
                   3007:     }
                   3008:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3009:     if (!$firstaccess) {
1.588     albertel 3010: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3011:     }
                   3012:     return 'already_set';
1.504     albertel 3013: }
                   3014: 
1.149     www      3015: sub checkout {
                   3016:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   3017:     my $now=time;
                   3018:     my $lonhost=$perlvar{'lonHostID'};
                   3019:     my $infostr=&escape(
1.234     www      3020:                  'CHECKOUTTOKEN&'.
1.149     www      3021:                  $tuname.'&'.
                   3022:                  $tudom.'&'.
                   3023:                  $tcrsid.'&'.
                   3024:                  $symb.'&'.
                   3025: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   3026:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      3027:     if ($token=~/^error\:/) { 
1.672     albertel 3028:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3029:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3030:                  "</font>");
                   3031:         return ''; 
                   3032:     }
                   3033: 
1.149     www      3034:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   3035:     $token=~tr/a-z/A-Z/;
                   3036: 
1.153     www      3037:     my %infohash=('resource.0.outtoken' => $token,
                   3038:                   'resource.0.checkouttime' => $now,
                   3039:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      3040: 
                   3041:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3042:        return '';
1.151     www      3043:     } else {
1.672     albertel 3044:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3045:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3046:                  "</font>");
1.149     www      3047:     }    
                   3048: 
                   3049:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3050:                          &escape('Checkout '.$infostr.' - '.
                   3051:                                                  $token)) ne 'ok') {
                   3052: 	return '';
1.151     www      3053:     } else {
1.672     albertel 3054:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      3055:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   3056:                  "</font>");
1.149     www      3057:     }
1.151     www      3058:     return $token;
1.149     www      3059: }
                   3060: 
                   3061: # ------------------------------------------------------------ Check in an item
                   3062: 
                   3063: sub checkin {
                   3064:     my $token=shift;
1.150     www      3065:     my $now=time;
                   3066:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   3067:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 3068:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      3069:     $dtoken=~s/\W/\_/g;
1.234     www      3070:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      3071:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   3072: 
1.154     www      3073:     unless (($tuname) && ($tudom)) {
                   3074:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   3075:         return '';
                   3076:     }
                   3077:     
                   3078:     unless (&allowed('mgr',$tcrsid)) {
                   3079:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 3080:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      3081:         return '';
                   3082:     }
                   3083: 
1.153     www      3084:     my %infohash=('resource.0.intoken' => $token,
                   3085:                   'resource.0.checkintime' => $now,
                   3086:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      3087: 
                   3088:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   3089:        return '';
                   3090:     }    
                   3091: 
                   3092:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   3093:                          &escape('Checkin - '.$token)) ne 'ok') {
                   3094: 	return '';
                   3095:     }
                   3096: 
                   3097:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      3098: }
                   3099: 
                   3100: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3101: 
                   3102: sub expirespread {
                   3103:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3104:     my $cid=$env{'request.course.id'}; 
1.110     www      3105:     if ($cid) {
                   3106:        my $now=time;
                   3107:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3108:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3109:                             $env{'course.'.$cid.'.num'}.
1.110     www      3110: 	        	    ':nohist_expirationdates:'.
                   3111:                             &escape($key).'='.$now,
1.620     albertel 3112:                             $env{'course.'.$cid.'.home'})
1.110     www      3113:     }
                   3114:     return 'ok';
1.14      www      3115: }
                   3116: 
1.109     www      3117: # ----------------------------------------------------- Devalidate Spreadsheets
                   3118: 
                   3119: sub devalidate {
1.325     www      3120:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3121:     my $cid=$env{'request.course.id'}; 
1.109     www      3122:     if ($cid) {
1.391     matthew  3123:         # delete the stored spreadsheets for
                   3124:         # - the student level sheet of this user in course's homespace
                   3125:         # - the assessment level sheet for this resource 
                   3126:         #   for this user in user's homespace
1.553     albertel 3127: 	# - current conditional state info
1.325     www      3128: 	my $key=$uname.':'.$udom.':';
1.109     www      3129:         my $status=
1.299     matthew  3130: 	    &del('nohist_calculatedsheets',
1.391     matthew  3131: 		 [$key.'studentcalc:'],
1.620     albertel 3132: 		 $env{'course.'.$cid.'.domain'},
                   3133: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3134: 		.' '.
                   3135: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3136: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3137:         unless ($status eq 'ok ok') {
                   3138:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3139:                     $uname.' at '.$udom.' for '.
1.109     www      3140: 		    $symb.': '.$status);
1.133     albertel 3141:         }
1.553     albertel 3142: 	&delenv('user.state.'.$cid);
1.109     www      3143:     }
                   3144: }
                   3145: 
1.265     albertel 3146: sub get_scalar {
                   3147:     my ($string,$end) = @_;
                   3148:     my $value;
                   3149:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3150: 	$value = $1;
                   3151:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3152: 	$value = $1;
                   3153:     }
                   3154:     return &unescape($value);
                   3155: }
                   3156: 
                   3157: sub array2str {
                   3158:   my (@array) = @_;
                   3159:   my $result=&arrayref2str(\@array);
                   3160:   $result=~s/^__ARRAY_REF__//;
                   3161:   $result=~s/__END_ARRAY_REF__$//;
                   3162:   return $result;
                   3163: }
                   3164: 
1.204     albertel 3165: sub arrayref2str {
                   3166:   my ($arrayref) = @_;
1.265     albertel 3167:   my $result='__ARRAY_REF__';
1.204     albertel 3168:   foreach my $elem (@$arrayref) {
1.265     albertel 3169:     if(ref($elem) eq 'ARRAY') {
                   3170:       $result.=&arrayref2str($elem).'&';
                   3171:     } elsif(ref($elem) eq 'HASH') {
                   3172:       $result.=&hashref2str($elem).'&';
                   3173:     } elsif(ref($elem)) {
                   3174:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3175:     } else {
                   3176:       $result.=&escape($elem).'&';
                   3177:     }
                   3178:   }
                   3179:   $result=~s/\&$//;
1.265     albertel 3180:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3181:   return $result;
                   3182: }
                   3183: 
1.168     albertel 3184: sub hash2str {
1.204     albertel 3185:   my (%hash) = @_;
                   3186:   my $result=&hashref2str(\%hash);
1.265     albertel 3187:   $result=~s/^__HASH_REF__//;
                   3188:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3189:   return $result;
                   3190: }
                   3191: 
                   3192: sub hashref2str {
                   3193:   my ($hashref)=@_;
1.265     albertel 3194:   my $result='__HASH_REF__';
1.800     albertel 3195:   foreach my $key (sort(keys(%$hashref))) {
                   3196:     if (ref($key) eq 'ARRAY') {
                   3197:       $result.=&arrayref2str($key).'=';
                   3198:     } elsif (ref($key) eq 'HASH') {
                   3199:       $result.=&hashref2str($key).'=';
                   3200:     } elsif (ref($key)) {
1.265     albertel 3201:       $result.='=';
1.800     albertel 3202:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3203:     } else {
1.800     albertel 3204: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3205:     }
                   3206: 
1.800     albertel 3207:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3208:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3209:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3210:       $result.=&hashref2str($hashref->{$key}).'&';
                   3211:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3212:        $result.='&';
1.800     albertel 3213:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3214:     } else {
1.800     albertel 3215:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 3216:     }
                   3217:   }
1.168     albertel 3218:   $result=~s/\&$//;
1.265     albertel 3219:   $result .= '__END_HASH_REF__';
1.168     albertel 3220:   return $result;
                   3221: }
                   3222: 
                   3223: sub str2hash {
1.265     albertel 3224:     my ($string)=@_;
                   3225:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   3226:     return %$hash;
                   3227: }
                   3228: 
                   3229: sub str2hashref {
1.168     albertel 3230:   my ($string) = @_;
1.265     albertel 3231: 
                   3232:   my %hash;
                   3233: 
                   3234:   if($string !~ /^__HASH_REF__/) {
                   3235:       if (! ($string eq '' || !defined($string))) {
                   3236: 	  $hash{'error'}='Not hash reference';
                   3237:       }
                   3238:       return (\%hash, $string);
                   3239:   }
                   3240: 
                   3241:   $string =~ s/^__HASH_REF__//;
                   3242: 
                   3243:   while($string !~ /^__END_HASH_REF__/) {
                   3244:       #key
                   3245:       my $key='';
                   3246:       if($string =~ /^__HASH_REF__/) {
                   3247:           ($key, $string)=&str2hashref($string);
                   3248:           if(defined($key->{'error'})) {
                   3249:               $hash{'error'}='Bad data';
                   3250:               return (\%hash, $string);
                   3251:           }
                   3252:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3253:           ($key, $string)=&str2arrayref($string);
                   3254:           if($key->[0] eq 'Array reference error') {
                   3255:               $hash{'error'}='Bad data';
                   3256:               return (\%hash, $string);
                   3257:           }
                   3258:       } else {
                   3259:           $string =~ s/^(.*?)=//;
1.267     albertel 3260: 	  $key=&unescape($1);
1.265     albertel 3261:       }
                   3262:       $string =~ s/^=//;
                   3263: 
                   3264:       #value
                   3265:       my $value='';
                   3266:       if($string =~ /^__HASH_REF__/) {
                   3267:           ($value, $string)=&str2hashref($string);
                   3268:           if(defined($value->{'error'})) {
                   3269:               $hash{'error'}='Bad data';
                   3270:               return (\%hash, $string);
                   3271:           }
                   3272:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3273:           ($value, $string)=&str2arrayref($string);
                   3274:           if($value->[0] eq 'Array reference error') {
                   3275:               $hash{'error'}='Bad data';
                   3276:               return (\%hash, $string);
                   3277:           }
                   3278:       } else {
                   3279: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3280:       }
                   3281:       $string =~ s/^&//;
                   3282: 
                   3283:       $hash{$key}=$value;
1.204     albertel 3284:   }
1.265     albertel 3285: 
                   3286:   $string =~ s/^__END_HASH_REF__//;
                   3287: 
                   3288:   return (\%hash, $string);
1.204     albertel 3289: }
                   3290: 
                   3291: sub str2array {
1.265     albertel 3292:     my ($string)=@_;
                   3293:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3294:     return @$array;
                   3295: }
                   3296: 
                   3297: sub str2arrayref {
1.204     albertel 3298:   my ($string) = @_;
1.265     albertel 3299:   my @array;
                   3300: 
                   3301:   if($string !~ /^__ARRAY_REF__/) {
                   3302:       if (! ($string eq '' || !defined($string))) {
                   3303: 	  $array[0]='Array reference error';
                   3304:       }
                   3305:       return (\@array, $string);
                   3306:   }
                   3307: 
                   3308:   $string =~ s/^__ARRAY_REF__//;
                   3309: 
                   3310:   while($string !~ /^__END_ARRAY_REF__/) {
                   3311:       my $value='';
                   3312:       if($string =~ /^__HASH_REF__/) {
                   3313:           ($value, $string)=&str2hashref($string);
                   3314:           if(defined($value->{'error'})) {
                   3315:               $array[0] ='Array reference error';
                   3316:               return (\@array, $string);
                   3317:           }
                   3318:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3319:           ($value, $string)=&str2arrayref($string);
                   3320:           if($value->[0] eq 'Array reference error') {
                   3321:               $array[0] ='Array reference error';
                   3322:               return (\@array, $string);
                   3323:           }
                   3324:       } else {
                   3325: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3326:       }
                   3327:       $string =~ s/^&//;
                   3328: 
                   3329:       push(@array, $value);
1.191     harris41 3330:   }
1.265     albertel 3331: 
                   3332:   $string =~ s/^__END_ARRAY_REF__//;
                   3333: 
                   3334:   return (\@array, $string);
1.168     albertel 3335: }
                   3336: 
1.167     albertel 3337: # -------------------------------------------------------------------Temp Store
                   3338: 
1.168     albertel 3339: sub tmpreset {
                   3340:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3341:   if (!$symb) {
                   3342:     $symb=&symbread();
1.620     albertel 3343:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3344:   }
                   3345:   $symb=escape($symb);
                   3346: 
1.620     albertel 3347:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3348:   $namespace=~s/\//\_/g;
                   3349:   $namespace=~s/\W//g;
                   3350: 
1.620     albertel 3351:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3352:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3353:   if ($domain eq 'public' && $stuname eq 'public') {
                   3354:       $stuname=$ENV{'REMOTE_ADDR'};
                   3355:   }
1.168     albertel 3356:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3357:   my %hash;
                   3358:   if (tie(%hash,'GDBM_File',
                   3359: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3360: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3361:     foreach my $key (keys %hash) {
1.180     albertel 3362:       if ($key=~ /:$symb/) {
1.168     albertel 3363: 	delete($hash{$key});
                   3364:       }
                   3365:     }
                   3366:   }
                   3367: }
                   3368: 
1.167     albertel 3369: sub tmpstore {
1.168     albertel 3370:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3371: 
                   3372:   if (!$symb) {
                   3373:     $symb=&symbread();
1.620     albertel 3374:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3375:   }
                   3376:   $symb=escape($symb);
                   3377: 
                   3378:   if (!$namespace) {
                   3379:     # I don't think we would ever want to store this for a course.
                   3380:     # it seems this will only be used if we don't have a course.
1.620     albertel 3381:     #$namespace=$env{'request.course.id'};
1.168     albertel 3382:     #if (!$namespace) {
1.620     albertel 3383:       $namespace=$env{'request.state'};
1.168     albertel 3384:     #}
                   3385:   }
                   3386:   $namespace=~s/\//\_/g;
                   3387:   $namespace=~s/\W//g;
1.620     albertel 3388:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3389:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3390:   if ($domain eq 'public' && $stuname eq 'public') {
                   3391:       $stuname=$ENV{'REMOTE_ADDR'};
                   3392:   }
1.168     albertel 3393:   my $now=time;
                   3394:   my %hash;
                   3395:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3396:   if (tie(%hash,'GDBM_File',
                   3397: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3398: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3399:     $hash{"version:$symb"}++;
                   3400:     my $version=$hash{"version:$symb"};
                   3401:     my $allkeys=''; 
                   3402:     foreach my $key (keys(%$storehash)) {
                   3403:       $allkeys.=$key.':';
1.591     albertel 3404:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3405:     }
                   3406:     $hash{"$version:$symb:timestamp"}=$now;
                   3407:     $allkeys.='timestamp';
                   3408:     $hash{"$version:keys:$symb"}=$allkeys;
                   3409:     if (untie(%hash)) {
                   3410:       return 'ok';
                   3411:     } else {
                   3412:       return "error:$!";
                   3413:     }
                   3414:   } else {
                   3415:     return "error:$!";
                   3416:   }
                   3417: }
1.167     albertel 3418: 
1.168     albertel 3419: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3420: 
1.168     albertel 3421: sub tmprestore {
                   3422:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3423: 
1.168     albertel 3424:   if (!$symb) {
                   3425:     $symb=&symbread();
1.620     albertel 3426:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3427:   }
                   3428:   $symb=escape($symb);
                   3429: 
1.620     albertel 3430:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3431: 
1.620     albertel 3432:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3433:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3434:   if ($domain eq 'public' && $stuname eq 'public') {
                   3435:       $stuname=$ENV{'REMOTE_ADDR'};
                   3436:   }
1.168     albertel 3437:   my %returnhash;
                   3438:   $namespace=~s/\//\_/g;
                   3439:   $namespace=~s/\W//g;
                   3440:   my %hash;
                   3441:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3442:   if (tie(%hash,'GDBM_File',
                   3443: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3444: 	  &GDBM_READER(),0640)) {
1.168     albertel 3445:     my $version=$hash{"version:$symb"};
                   3446:     $returnhash{'version'}=$version;
                   3447:     my $scope;
                   3448:     for ($scope=1;$scope<=$version;$scope++) {
                   3449:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3450:       my @keys=split(/:/,$vkeys);
                   3451:       my $key;
                   3452:       $returnhash{"$scope:keys"}=$vkeys;
                   3453:       foreach $key (@keys) {
1.591     albertel 3454: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3455: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3456:       }
                   3457:     }
1.168     albertel 3458:     if (!(untie(%hash))) {
                   3459:       return "error:$!";
                   3460:     }
                   3461:   } else {
                   3462:     return "error:$!";
                   3463:   }
                   3464:   return %returnhash;
1.167     albertel 3465: }
                   3466: 
1.9       www      3467: # ----------------------------------------------------------------------- Store
                   3468: 
                   3469: sub store {
1.124     www      3470:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3471:     my $home='';
                   3472: 
1.168     albertel 3473:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3474: 
1.213     www      3475:     $symb=&symbclean($symb);
1.122     albertel 3476:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3477: 
1.620     albertel 3478:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3479:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3480: 
                   3481:     &devalidate($symb,$stuname,$domain);
1.109     www      3482: 
                   3483:     $symb=escape($symb);
1.187     www      3484:     if (!$namespace) { 
1.620     albertel 3485:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3486:           return ''; 
                   3487:        } 
                   3488:     }
1.620     albertel 3489:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3490: 
                   3491:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3492:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3493: 
1.12      www      3494:     my $namevalue='';
1.800     albertel 3495:     foreach my $key (keys(%$storehash)) {
                   3496:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3497:     }
1.12      www      3498:     $namevalue=~s/\&$//;
1.187     www      3499:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3500:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3501: }
                   3502: 
1.47      www      3503: # -------------------------------------------------------------- Critical Store
                   3504: 
                   3505: sub cstore {
1.124     www      3506:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3507:     my $home='';
                   3508: 
1.168     albertel 3509:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3510: 
1.213     www      3511:     $symb=&symbclean($symb);
1.122     albertel 3512:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3513: 
1.620     albertel 3514:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3515:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3516: 
                   3517:     &devalidate($symb,$stuname,$domain);
1.109     www      3518: 
                   3519:     $symb=escape($symb);
1.187     www      3520:     if (!$namespace) { 
1.620     albertel 3521:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3522:           return ''; 
                   3523:        } 
                   3524:     }
1.620     albertel 3525:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3526: 
                   3527:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3528:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3529: 
1.47      www      3530:     my $namevalue='';
1.800     albertel 3531:     foreach my $key (keys(%$storehash)) {
                   3532:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3533:     }
1.47      www      3534:     $namevalue=~s/\&$//;
1.187     www      3535:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3536:     return critical
                   3537:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3538: }
                   3539: 
1.9       www      3540: # --------------------------------------------------------------------- Restore
                   3541: 
                   3542: sub restore {
1.124     www      3543:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3544:     my $home='';
                   3545: 
1.168     albertel 3546:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3547: 
1.122     albertel 3548:     if (!$symb) {
                   3549:       unless ($symb=escape(&symbread())) { return ''; }
                   3550:     } else {
1.213     www      3551:       $symb=&escape(&symbclean($symb));
1.122     albertel 3552:     }
1.188     www      3553:     if (!$namespace) { 
1.620     albertel 3554:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3555:           return ''; 
                   3556:        } 
                   3557:     }
1.620     albertel 3558:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3559:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3560:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3561:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3562: 
1.12      www      3563:     my %returnhash=();
1.800     albertel 3564:     foreach my $line (split(/\&/,$answer)) {
                   3565: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3566:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3567:     }
1.75      www      3568:     my $version;
                   3569:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3570:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3571:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3572:        }
1.75      www      3573:     }
1.13      www      3574:     return %returnhash;
1.34      www      3575: }
                   3576: 
                   3577: # ---------------------------------------------------------- Course Description
                   3578: 
                   3579: sub coursedescription {
1.731     albertel 3580:     my ($courseid,$args)=@_;
1.34      www      3581:     $courseid=~s/^\///;
1.49      www      3582:     $courseid=~s/\_/\//g;
1.34      www      3583:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3584:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3585:     my $normalid=$cdomain.'_'.$cnum;
                   3586:     # need to always cache even if we get errors otherwise we keep 
                   3587:     # trying and trying and trying to get the course description.
                   3588:     my %envhash=();
                   3589:     my %returnhash=();
1.731     albertel 3590:     
                   3591:     my $expiretime=600;
                   3592:     if ($env{'request.course.id'} eq $normalid) {
                   3593: 	$expiretime=120;
                   3594:     }
                   3595: 
                   3596:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3597:     if (!$args->{'freshen_cache'}
                   3598: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3599: 	foreach my $key (keys(%env)) {
                   3600: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3601: 	    my ($setting) = $1;
                   3602: 	    $returnhash{$setting} = $env{$key};
                   3603: 	}
                   3604: 	return %returnhash;
                   3605:     }
                   3606: 
                   3607:     # get the data agin
                   3608:     if (!$args->{'one_time'}) {
                   3609: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3610:     }
1.811     albertel 3611: 
1.34      www      3612:     if ($chome ne 'no_host') {
1.302     albertel 3613:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3614:        if (!exists($returnhash{'con_lost'})) {
                   3615:            $returnhash{'home'}= $chome;
                   3616: 	   $returnhash{'domain'} = $cdomain;
                   3617: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3618:            if (!defined($returnhash{'type'})) {
                   3619:                $returnhash{'type'} = 'Course';
                   3620:            }
1.130     albertel 3621:            while (my ($name,$value) = each %returnhash) {
1.53      www      3622:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3623:            }
1.270     www      3624:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3625:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3626: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3627:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3628:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3629:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3630:        }
                   3631:     }
1.731     albertel 3632:     if (!$args->{'one_time'}) {
1.949     raeburn  3633: 	&appenv(\%envhash);
1.731     albertel 3634:     }
1.302     albertel 3635:     return %returnhash;
1.461     www      3636: }
                   3637: 
                   3638: # -------------------------------------------------See if a user is privileged
                   3639: 
                   3640: sub privileged {
                   3641:     my ($username,$domain)=@_;
                   3642:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3643: 			&homeserver($username,$domain));
                   3644:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3645:     my $now=time;
                   3646:     if ($rolesdump ne '') {
1.800     albertel 3647:         foreach my $entry (split(/&/,$rolesdump)) {
                   3648: 	    if ($entry!~/^rolesdef_/) {
                   3649: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3650: 		$area=~s/\_\w\w$//;
                   3651: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3652: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3653: 		    my $active=1;
                   3654: 		    if ($tend) {
                   3655: 			if ($tend<$now) { $active=0; }
                   3656: 		    }
                   3657: 		    if ($tstart) {
                   3658: 			if ($tstart>$now) { $active=0; }
                   3659: 		    }
                   3660: 		    if ($active) { return 1; }
                   3661: 		}
                   3662: 	    }
                   3663: 	}
                   3664:     }
                   3665:     return 0;
1.9       www      3666: }
1.1       albertel 3667: 
1.103     harris41 3668: # -------------------------------------------------------- Get user privileges
1.11      www      3669: 
                   3670: sub rolesinit {
                   3671:     my ($domain,$username,$authhost)=@_;
1.966     raeburn  3672:     my %userroles;
1.11      www      3673:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.966     raeburn  3674:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
1.11      www      3675:     my %allroles=();
1.678     raeburn  3676:     my %allgroups=();   
1.11      www      3677:     my $now=time;
1.966     raeburn  3678:     %userroles = ('user.login.time' => $now);
1.678     raeburn  3679:     my $group_privs;
1.11      www      3680: 
                   3681:     if ($rolesdump ne '') {
1.800     albertel 3682:         foreach my $entry (split(/&/,$rolesdump)) {
                   3683: 	  if ($entry!~/^rolesdef_/) {
                   3684:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3685: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3686:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3687: 	    if ($role=~/^cr/) { 
1.807     albertel 3688: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3689: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3690: 		    ($tend,$tstart)=split('_',$trest);
                   3691: 		} else {
                   3692: 		    $trole=$role;
                   3693: 		}
1.678     raeburn  3694:             } elsif ($role =~ m|^gr/|) {
                   3695:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3696:                 ($trole,$group_privs) = split(/\//,$trole);
                   3697:                 $group_privs = &unescape($group_privs);
1.587     albertel 3698: 	    } else {
                   3699: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3700: 	    }
1.743     albertel 3701: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3702: 					 $username);
                   3703: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3704:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3705:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3706:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3707: 		my $spec=$trole.'.'.$area;
                   3708: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3709: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3710:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3711:                 } elsif ($trole eq 'gr') {
                   3712:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3713: 		} else {
1.567     raeburn  3714:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3715: 		}
1.12      www      3716:             }
1.662     raeburn  3717:           }
1.191     harris41 3718:         }
1.743     albertel 3719:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3720:         $userroles{'user.adv'}    = $adv;
                   3721: 	$userroles{'user.author'} = $author;
1.620     albertel 3722:         $env{'user.adv'}=$adv;
1.11      www      3723:     }
1.743     albertel 3724:     return \%userroles;  
1.11      www      3725: }
                   3726: 
1.567     raeburn  3727: sub set_arearole {
                   3728:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3729: # log the associated role with the area
                   3730:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3731:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3732: }
                   3733: 
                   3734: sub custom_roleprivs {
                   3735:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3736:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3737:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3738:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3739:         my ($rdummy,$roledef)=
                   3740:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3741:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3742:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3743:             if (defined($syspriv)) {
                   3744:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3745:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3746:             }
                   3747:             if ($tdomain ne '') {
                   3748:                 if (defined($dompriv)) {
                   3749:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3750:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3751:                 }
                   3752:                 if (($trest ne '') && (defined($coursepriv))) {
                   3753:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3754:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3755:                 }
                   3756:             }
                   3757:         }
                   3758:     }
                   3759: }
                   3760: 
1.678     raeburn  3761: sub group_roleprivs {
                   3762:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3763:     my $access = 1;
                   3764:     my $now = time;
                   3765:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3766:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3767:     if ($access) {
1.811     albertel 3768:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3769:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3770:     }
                   3771: }
1.567     raeburn  3772: 
                   3773: sub standard_roleprivs {
                   3774:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3775:     if (defined($pr{$trole.':s'})) {
                   3776:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3777:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3778:     }
                   3779:     if ($tdomain ne '') {
                   3780:         if (defined($pr{$trole.':d'})) {
                   3781:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3782:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3783:         }
                   3784:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3785:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3786:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3787:         }
                   3788:     }
                   3789: }
                   3790: 
                   3791: sub set_userprivs {
1.678     raeburn  3792:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3793:     my $author=0;
                   3794:     my $adv=0;
1.678     raeburn  3795:     my %grouproles = ();
                   3796:     if (keys(%{$allgroups}) > 0) {
                   3797:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3798:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3799:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3800:                 $trole = $1;
                   3801:                 $area = $2;
1.681     raeburn  3802:                 $sec = $3;
                   3803:                 $extendedarea = $area.$sec;
                   3804:                 if (exists($$allgroups{$area})) {
                   3805:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3806:                         my $spec = $trole.'.'.$extendedarea;
                   3807:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3808:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3809:                     }
                   3810:                 }
                   3811:             }
                   3812:         }
                   3813:     }
1.800     albertel 3814:     foreach my $group (keys(%grouproles)) {
                   3815:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3816:     }
1.800     albertel 3817:     foreach my $role (keys(%{$allroles})) {
                   3818:         my %thesepriv;
1.941     raeburn  3819:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3820:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3821:             if ($item ne '') {
                   3822:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3823:                 if ($restrictions eq '') {
                   3824:                     $thesepriv{$privilege}='F';
                   3825:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3826:                     $thesepriv{$privilege}.=$restrictions;
                   3827:                 }
                   3828:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3829:             }
                   3830:         }
                   3831:         my $thesestr='';
1.800     albertel 3832:         foreach my $priv (keys(%thesepriv)) {
                   3833: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3834: 	}
                   3835:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3836:     }
                   3837:     return ($author,$adv);
                   3838: }
                   3839: 
1.12      www      3840: # --------------------------------------------------------------- get interface
                   3841: 
                   3842: sub get {
1.131     albertel 3843:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3844:    my $items='';
1.800     albertel 3845:    foreach my $item (@$storearr) {
                   3846:        $items.=&escape($item).'&';
1.191     harris41 3847:    }
1.12      www      3848:    $items=~s/\&$//;
1.620     albertel 3849:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3850:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3851:    my $uhome=&homeserver($uname,$udomain);
                   3852: 
1.133     albertel 3853:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3854:    my @pairs=split(/\&/,$rep);
1.273     albertel 3855:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3856:      return @pairs;
                   3857:    }
1.15      www      3858:    my %returnhash=();
1.42      www      3859:    my $i=0;
1.800     albertel 3860:    foreach my $item (@$storearr) {
                   3861:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3862:       $i++;
1.191     harris41 3863:    }
1.15      www      3864:    return %returnhash;
1.27      www      3865: }
                   3866: 
                   3867: # --------------------------------------------------------------- del interface
                   3868: 
                   3869: sub del {
1.133     albertel 3870:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3871:    my $items='';
1.800     albertel 3872:    foreach my $item (@$storearr) {
                   3873:        $items.=&escape($item).'&';
1.191     harris41 3874:    }
1.27      www      3875:    $items=~s/\&$//;
1.620     albertel 3876:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3877:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3878:    my $uhome=&homeserver($uname,$udomain);
                   3879: 
                   3880:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3881: }
                   3882: 
                   3883: # -------------------------------------------------------------- dump interface
                   3884: 
                   3885: sub dump {
1.755     albertel 3886:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3887:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3888:     if (!$uname) { $uname=$env{'user.name'}; }
                   3889:     my $uhome=&homeserver($uname,$udomain);
                   3890:     if ($regexp) {
                   3891: 	$regexp=&escape($regexp);
                   3892:     } else {
                   3893: 	$regexp='.';
                   3894:     }
                   3895:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3896:     my @pairs=split(/\&/,$rep);
                   3897:     my %returnhash=();
                   3898:     foreach my $item (@pairs) {
                   3899: 	my ($key,$value)=split(/=/,$item,2);
                   3900: 	$key = &unescape($key);
                   3901: 	next if ($key =~ /^error: 2 /);
                   3902: 	$returnhash{$key}=&thaw_unescape($value);
                   3903:     }
                   3904:     return %returnhash;
1.407     www      3905: }
                   3906: 
1.717     albertel 3907: # --------------------------------------------------------- dumpstore interface
                   3908: 
                   3909: sub dumpstore {
                   3910:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3911:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3912:    if (!$uname) { $uname=$env{'user.name'}; }
                   3913:    my $uhome=&homeserver($uname,$udomain);
                   3914:    if ($regexp) {
                   3915:        $regexp=&escape($regexp);
                   3916:    } else {
                   3917:        $regexp='.';
                   3918:    }
                   3919:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3920:    my @pairs=split(/\&/,$rep);
                   3921:    my %returnhash=();
                   3922:    foreach my $item (@pairs) {
                   3923:        my ($key,$value)=split(/=/,$item,2);
                   3924:        next if ($key =~ /^error: 2 /);
                   3925:        $returnhash{$key}=&thaw_unescape($value);
                   3926:    }
                   3927:    return %returnhash;
1.717     albertel 3928: }
                   3929: 
1.407     www      3930: # -------------------------------------------------------------- keys interface
                   3931: 
                   3932: sub getkeys {
                   3933:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3934:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3935:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3936:    my $uhome=&homeserver($uname,$udomain);
                   3937:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3938:    my @keyarray=();
1.800     albertel 3939:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3940:       next if ($key =~ /^error: 2 /);
1.800     albertel 3941:       push(@keyarray,&unescape($key));
1.407     www      3942:    }
                   3943:    return @keyarray;
1.318     matthew  3944: }
                   3945: 
1.319     matthew  3946: # --------------------------------------------------------------- currentdump
                   3947: sub currentdump {
1.328     matthew  3948:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3949:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3950:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3951:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3952:    my $uhome = &homeserver($sname,$sdom);
                   3953:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3954:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3955:    #
1.318     matthew  3956:    my %returnhash=();
1.319     matthew  3957:    #
                   3958:    if ($rep eq "unknown_cmd") { 
                   3959:        # an old lond will not know currentdump
                   3960:        # Do a dump and make it look like a currentdump
1.822     albertel 3961:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3962:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3963:        my %hash = @tmp;
                   3964:        @tmp=();
1.424     matthew  3965:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3966:    } else {
                   3967:        my @pairs=split(/\&/,$rep);
1.800     albertel 3968:        foreach my $pair (@pairs) {
                   3969:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3970:            my ($symb,$param) = split(/:/,$key);
                   3971:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3972:                                                         &thaw_unescape($value);
1.319     matthew  3973:        }
1.191     harris41 3974:    }
1.12      www      3975:    return %returnhash;
1.424     matthew  3976: }
                   3977: 
                   3978: sub convert_dump_to_currentdump{
                   3979:     my %hash = %{shift()};
                   3980:     my %returnhash;
                   3981:     # Code ripped from lond, essentially.  The only difference
                   3982:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3983:     # we might run in to problems with parameter names =~ /^v\./
                   3984:     while (my ($key,$value) = each(%hash)) {
                   3985:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3986: 	$symb  = &unescape($symb);
                   3987: 	$param = &unescape($param);
1.424     matthew  3988:         next if ($v eq 'version' || $symb eq 'keys');
                   3989:         next if (exists($returnhash{$symb}) &&
                   3990:                  exists($returnhash{$symb}->{$param}) &&
                   3991:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3992:         $returnhash{$symb}->{$param}=$value;
                   3993:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3994:     }
                   3995:     #
                   3996:     # Remove all of the keys in the hashes which keep track of
                   3997:     # the version of the parameter.
                   3998:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3999:         # use a foreach because we are going to delete from the hash.
                   4000:         foreach my $key (keys(%$param_hash)) {
                   4001:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   4002:         }
                   4003:     }
                   4004:     return \%returnhash;
1.12      www      4005: }
                   4006: 
1.627     albertel 4007: # ------------------------------------------------------ critical inc interface
                   4008: 
                   4009: sub cinc {
                   4010:     return &inc(@_,'critical');
                   4011: }
                   4012: 
1.449     matthew  4013: # --------------------------------------------------------------- inc interface
                   4014: 
                   4015: sub inc {
1.627     albertel 4016:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 4017:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4018:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  4019:     my $uhome=&homeserver($uname,$udomain);
                   4020:     my $items='';
                   4021:     if (! ref($store)) {
                   4022:         # got a single value, so use that instead
                   4023:         $items = &escape($store).'=&';
                   4024:     } elsif (ref($store) eq 'SCALAR') {
                   4025:         $items = &escape($$store).'=&';        
                   4026:     } elsif (ref($store) eq 'ARRAY') {
                   4027:         $items = join('=&',map {&escape($_);} @{$store});
                   4028:     } elsif (ref($store) eq 'HASH') {
                   4029:         while (my($key,$value) = each(%{$store})) {
                   4030:             $items.= &escape($key).'='.&escape($value).'&';
                   4031:         }
                   4032:     }
                   4033:     $items=~s/\&$//;
1.627     albertel 4034:     if ($critical) {
                   4035: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4036:     } else {
                   4037: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   4038:     }
1.449     matthew  4039: }
                   4040: 
1.12      www      4041: # --------------------------------------------------------------- put interface
                   4042: 
                   4043: sub put {
1.134     albertel 4044:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4045:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4046:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4047:    my $uhome=&homeserver($uname,$udomain);
1.12      www      4048:    my $items='';
1.800     albertel 4049:    foreach my $item (keys(%$storehash)) {
                   4050:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4051:    }
1.12      www      4052:    $items=~s/\&$//;
1.134     albertel 4053:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      4054: }
                   4055: 
1.631     albertel 4056: # ------------------------------------------------------------ newput interface
                   4057: 
                   4058: sub newput {
                   4059:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   4060:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4061:    if (!$uname) { $uname=$env{'user.name'}; }
                   4062:    my $uhome=&homeserver($uname,$udomain);
                   4063:    my $items='';
                   4064:    foreach my $key (keys(%$storehash)) {
                   4065:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   4066:    }
                   4067:    $items=~s/\&$//;
                   4068:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   4069: }
                   4070: 
                   4071: # ---------------------------------------------------------  putstore interface
                   4072: 
1.524     raeburn  4073: sub putstore {
1.715     albertel 4074:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 4075:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4076:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  4077:    my $uhome=&homeserver($uname,$udomain);
                   4078:    my $items='';
1.715     albertel 4079:    foreach my $key (keys(%$storehash)) {
                   4080:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  4081:    }
1.715     albertel 4082:    $items=~s/\&$//;
1.716     albertel 4083:    my $esc_symb=&escape($symb);
                   4084:    my $esc_v=&escape($version);
1.715     albertel 4085:    my $reply =
1.716     albertel 4086:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 4087: 	      $uhome);
                   4088:    if ($reply eq 'unknown_cmd') {
1.716     albertel 4089:        # gfall back to way things use to be done
1.715     albertel 4090:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   4091: 			    $uname);
1.524     raeburn  4092:    }
1.715     albertel 4093:    return $reply;
                   4094: }
                   4095: 
                   4096: sub old_putstore {
1.716     albertel 4097:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   4098:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4099:     if (!$uname) { $uname=$env{'user.name'}; }
                   4100:     my $uhome=&homeserver($uname,$udomain);
                   4101:     my %newstorehash;
1.800     albertel 4102:     foreach my $item (keys(%$storehash)) {
                   4103: 	my $key = $version.':'.&escape($symb).':'.$item;
                   4104: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 4105:     }
                   4106:     my $items='';
                   4107:     my %allitems = ();
1.800     albertel 4108:     foreach my $item (keys(%newstorehash)) {
                   4109: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 4110: 	    my $key = $1.':keys:'.$2;
                   4111: 	    $allitems{$key} .= $3.':';
                   4112: 	}
1.800     albertel 4113: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 4114:     }
1.800     albertel 4115:     foreach my $item (keys(%allitems)) {
                   4116: 	$allitems{$item} =~ s/\:$//;
                   4117: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 4118:     }
                   4119:     $items=~s/\&$//;
                   4120:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  4121: }
                   4122: 
1.47      www      4123: # ------------------------------------------------------ critical put interface
                   4124: 
                   4125: sub cput {
1.134     albertel 4126:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 4127:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4128:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 4129:    my $uhome=&homeserver($uname,$udomain);
1.47      www      4130:    my $items='';
1.800     albertel 4131:    foreach my $item (keys(%$storehash)) {
                   4132:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 4133:    }
1.47      www      4134:    $items=~s/\&$//;
1.134     albertel 4135:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4136: }
                   4137: 
                   4138: # -------------------------------------------------------------- eget interface
                   4139: 
                   4140: sub eget {
1.133     albertel 4141:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4142:    my $items='';
1.800     albertel 4143:    foreach my $item (@$storearr) {
                   4144:        $items.=&escape($item).'&';
1.191     harris41 4145:    }
1.12      www      4146:    $items=~s/\&$//;
1.620     albertel 4147:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4148:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4149:    my $uhome=&homeserver($uname,$udomain);
                   4150:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      4151:    my @pairs=split(/\&/,$rep);
                   4152:    my %returnhash=();
1.42      www      4153:    my $i=0;
1.800     albertel 4154:    foreach my $item (@$storearr) {
                   4155:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4156:       $i++;
1.191     harris41 4157:    }
1.12      www      4158:    return %returnhash;
                   4159: }
                   4160: 
1.667     albertel 4161: # ------------------------------------------------------------ tmpput interface
                   4162: sub tmpput {
1.802     raeburn  4163:     my ($storehash,$server,$context)=@_;
1.667     albertel 4164:     my $items='';
1.800     albertel 4165:     foreach my $item (keys(%$storehash)) {
                   4166: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 4167:     }
                   4168:     $items=~s/\&$//;
1.802     raeburn  4169:     if (defined($context)) {
                   4170:         $items .= ':'.&escape($context);
                   4171:     }
1.667     albertel 4172:     return &reply("tmpput:$items",$server);
                   4173: }
                   4174: 
                   4175: # ------------------------------------------------------------ tmpget interface
                   4176: sub tmpget {
1.688     albertel 4177:     my ($token,$server)=@_;
                   4178:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4179:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 4180:     my %returnhash;
                   4181:     foreach my $item (split(/\&/,$rep)) {
                   4182: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  4183:         next if ($key =~ /^error: 2 /);
1.667     albertel 4184: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   4185:     }
                   4186:     return %returnhash;
                   4187: }
                   4188: 
1.688     albertel 4189: # ------------------------------------------------------------ tmpget interface
                   4190: sub tmpdel {
                   4191:     my ($token,$server)=@_;
                   4192:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   4193:     return &reply("tmpdel:$token",$server);
                   4194: }
                   4195: 
1.765     albertel 4196: # -------------------------------------------------- portfolio access checking
                   4197: 
                   4198: sub portfolio_access {
1.766     albertel 4199:     my ($requrl) = @_;
1.765     albertel 4200:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   4201:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  4202:     if ($result) {
                   4203:         my %setters;
                   4204:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4205:             my ($startblock,$endblock) =
                   4206:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   4207:             if ($startblock && $endblock) {
                   4208:                 return 'B';
                   4209:             }
                   4210:         } else {
                   4211:             my ($startblock,$endblock) =
                   4212:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   4213:             if ($startblock && $endblock) {
                   4214:                 return 'B';
                   4215:             }
                   4216:         }
                   4217:     }
1.765     albertel 4218:     if ($result eq 'ok') {
1.766     albertel 4219:        return 'F';
1.765     albertel 4220:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 4221:        return 'A';
1.765     albertel 4222:     }
1.766     albertel 4223:     return '';
1.765     albertel 4224: }
                   4225: 
                   4226: sub get_portfolio_access {
1.767     albertel 4227:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   4228: 
                   4229:     if (!ref($access_hash)) {
                   4230: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   4231: 	my %access_controls = &get_access_controls($current_perms,$group,
                   4232: 						   $file_name);
                   4233: 	$access_hash = $access_controls{$file_name};
                   4234:     }
                   4235: 
1.765     albertel 4236:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4237:     my $now = time;
                   4238:     if (ref($access_hash) eq 'HASH') {
                   4239:         foreach my $key (keys(%{$access_hash})) {
                   4240:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4241:             if ($start > $now) {
                   4242:                 next;
                   4243:             }
                   4244:             if ($end && $end<$now) {
                   4245:                 next;
                   4246:             }
                   4247:             if ($scope eq 'public') {
                   4248:                 $public = $key;
                   4249:                 last;
                   4250:             } elsif ($scope eq 'guest') {
                   4251:                 $guest = $key;
                   4252:             } elsif ($scope eq 'domains') {
                   4253:                 push(@domains,$key);
                   4254:             } elsif ($scope eq 'users') {
                   4255:                 push(@users,$key);
                   4256:             } elsif ($scope eq 'course') {
                   4257:                 push(@courses,$key);
                   4258:             } elsif ($scope eq 'group') {
                   4259:                 push(@groups,$key);
                   4260:             }
                   4261:         }
                   4262:         if ($public) {
                   4263:             return 'ok';
                   4264:         }
                   4265:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4266:             if ($guest) {
                   4267:                 return $guest;
                   4268:             }
                   4269:         } else {
                   4270:             if (@domains > 0) {
                   4271:                 foreach my $domkey (@domains) {
                   4272:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4273:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4274:                             return 'ok';
                   4275:                         }
                   4276:                     }
                   4277:                 }
                   4278:             }
                   4279:             if (@users > 0) {
                   4280:                 foreach my $userkey (@users) {
1.865     raeburn  4281:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4282:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4283:                             if (ref($item) eq 'HASH') {
                   4284:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4285:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4286:                                     return 'ok';
                   4287:                                 }
                   4288:                             }
                   4289:                         }
                   4290:                     } 
1.765     albertel 4291:                 }
                   4292:             }
                   4293:             my %roleshash;
                   4294:             my @courses_and_groups = @courses;
                   4295:             push(@courses_and_groups,@groups); 
                   4296:             if (@courses_and_groups > 0) {
                   4297:                 my (%allgroups,%allroles); 
                   4298:                 my ($start,$end,$role,$sec,$group);
                   4299:                 foreach my $envkey (%env) {
1.811     albertel 4300:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4301:                         my $cid = $2.'_'.$3; 
                   4302:                         if ($1 eq 'gr') {
                   4303:                             $group = $4;
                   4304:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4305:                         } else {
                   4306:                             if ($4 eq '') {
                   4307:                                 $sec = 'none';
                   4308:                             } else {
                   4309:                                 $sec = $4;
                   4310:                             }
                   4311:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4312:                         }
1.811     albertel 4313:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4314:                         my $cid = $2.'_'.$3;
                   4315:                         if ($4 eq '') {
                   4316:                             $sec = 'none';
                   4317:                         } else {
                   4318:                             $sec = $4;
                   4319:                         }
                   4320:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4321:                     }
                   4322:                 }
                   4323:                 if (keys(%allroles) == 0) {
                   4324:                     return;
                   4325:                 }
                   4326:                 foreach my $key (@courses_and_groups) {
                   4327:                     my %content = %{$$access_hash{$key}};
                   4328:                     my $cnum = $content{'number'};
                   4329:                     my $cdom = $content{'domain'};
                   4330:                     my $cid = $cdom.'_'.$cnum;
                   4331:                     if (!exists($allroles{$cid})) {
                   4332:                         next;
                   4333:                     }    
                   4334:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4335:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4336:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4337:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4338:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4339:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4340:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4341:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4342:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4343:                                         if (grep/^all$/,@sections) {
                   4344:                                             return 'ok';
                   4345:                                         } else {
                   4346:                                             if (grep/^$sec$/,@sections) {
                   4347:                                                 return 'ok';
                   4348:                                             }
                   4349:                                         }
                   4350:                                     }
                   4351:                                 }
                   4352:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4353:                                     if (grep/^none$/,@groups) {
                   4354:                                         return 'ok';
                   4355:                                     }
                   4356:                                 } else {
                   4357:                                     if (grep/^all$/,@groups) {
                   4358:                                         return 'ok';
                   4359:                                     } 
                   4360:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4361:                                         if (grep/^$group$/,@groups) {
                   4362:                                             return 'ok';
                   4363:                                         }
                   4364:                                     }
                   4365:                                 } 
                   4366:                             }
                   4367:                         }
                   4368:                     }
                   4369:                 }
                   4370:             }
                   4371:             if ($guest) {
                   4372:                 return $guest;
                   4373:             }
                   4374:         }
                   4375:     }
                   4376:     return;
                   4377: }
                   4378: 
                   4379: sub course_group_datechecker {
                   4380:     my ($dates,$now,$status) = @_;
                   4381:     my ($start,$end) = split(/\./,$dates);
                   4382:     if (!$start && !$end) {
                   4383:         return 'ok';
                   4384:     }
                   4385:     if (grep/^active$/,@{$status}) {
                   4386:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4387:             return 'ok';
                   4388:         }
                   4389:     }
                   4390:     if (grep/^previous$/,@{$status}) {
                   4391:         if ($end > $now ) {
                   4392:             return 'ok';
                   4393:         }
                   4394:     }
                   4395:     if (grep/^future$/,@{$status}) {
                   4396:         if ($start > $now) {
                   4397:             return 'ok';
                   4398:         }
                   4399:     }
                   4400:     return; 
                   4401: }
                   4402: 
                   4403: sub parse_portfolio_url {
                   4404:     my ($url) = @_;
                   4405: 
                   4406:     my ($type,$udom,$unum,$group,$file_name);
                   4407:     
1.823     albertel 4408:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4409: 	$type = 1;
                   4410:         $udom = $1;
                   4411:         $unum = $2;
                   4412:         $file_name = $3;
1.823     albertel 4413:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4414: 	$type = 2;
                   4415:         $udom = $1;
                   4416:         $unum = $2;
                   4417:         $group = $3;
                   4418:         $file_name = $3.'/'.$4;
                   4419:     }
                   4420:     if (wantarray) {
                   4421: 	return ($type,$udom,$unum,$file_name,$group);
                   4422:     }
                   4423:     return $type;
                   4424: }
                   4425: 
                   4426: sub is_portfolio_url {
                   4427:     my ($url) = @_;
                   4428:     return scalar(&parse_portfolio_url($url));
                   4429: }
                   4430: 
1.798     raeburn  4431: sub is_portfolio_file {
                   4432:     my ($file) = @_;
1.820     raeburn  4433:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4434:         return 1;
                   4435:     }
                   4436:     return;
                   4437: }
                   4438: 
1.976     raeburn  4439: sub usertools_access {
1.976.2.1  raeburn  4440:     my ($uname,$udom,$tool,$action) = @_;
1.976     raeburn  4441:     my $access;
                   4442:     my %tools = (
                   4443:                   aboutme   => 1,
                   4444:                   blog      => 1,
                   4445:                   portfolio => 1,
                   4446:                 );
                   4447:     return if (!defined($tools{$tool}));
                   4448: 
                   4449:     if ((!defined($udom)) || (!defined($uname))) {
                   4450:         $udom = $env{'user.domain'};
                   4451:         $uname = $env{'user.name'};
                   4452:     }
                   4453: 
1.976.2.1  raeburn  4454:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4455:         if ($action ne 'reload') {
                   4456:             return $env{'environment.availabletools.'.$tool};
                   4457:         }
1.976     raeburn  4458:     }
                   4459: 
                   4460:     my ($toolstatus,$inststatus);
                   4461: 
                   4462:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   4463:         $toolstatus = $env{'environment.tools.'.$tool};
                   4464:         $inststatus = $env{'environment.inststatus'};
                   4465:     } else {
                   4466:         my %userenv = &userenvironment($udom,$uname,'tools.'.$tool);
                   4467:         $toolstatus = $userenv{'tools.'.$tool};
                   4468:         $inststatus = $userenv{'inststatus'};
                   4469:     }
                   4470: 
                   4471:     if ($toolstatus ne '') {
                   4472:         if ($toolstatus) {
                   4473:             $access = 1;
                   4474:         } else {
                   4475:             $access = 0;
                   4476:         }
                   4477:         return $access;
                   4478:     }
                   4479: 
                   4480:     my $is_adv = &is_advanced_user($udom,$uname);
                   4481:     my %domdef = &get_domain_defaults($udom);
                   4482:     if (ref($domdef{$tool}) eq 'HASH') {
                   4483:         if ($is_adv) {
                   4484:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   4485:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   4486:                     $access = 1;
                   4487:                 } else {
                   4488:                     $access = 0;
                   4489:                 }
                   4490:                 return $access;
                   4491:             }
                   4492:         }
                   4493:         if ($inststatus ne '') {
                   4494:             my ($hasaccess,$hasnoaccess);
                   4495:             foreach my $affiliation (split(/:/,$inststatus)) {
                   4496:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   4497:                     if ($domdef{$tool}{$affiliation}) {
                   4498:                         $hasaccess = 1;
                   4499:                     } else {
                   4500:                         $hasnoaccess = 1;
                   4501:                     }
                   4502:                 }
                   4503:             }
                   4504:             if ($hasaccess || $hasnoaccess) {
                   4505:                 if ($hasaccess) {
                   4506:                     $access = 1;
                   4507:                 } elsif ($hasnoaccess) {
                   4508:                     $access = 0; 
                   4509:                 }
                   4510:                 return $access;
                   4511:             }
                   4512:         } else {
                   4513:             if ($domdef{$tool}{'default'} ne '') {
                   4514:                 if ($domdef{$tool}{'default'}) {
                   4515:                     $access = 1;
                   4516:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   4517:                     $access = 0;
                   4518:                 }
                   4519:                 return $access;
                   4520:             }
                   4521:         }
                   4522:     } else {
                   4523:         $access = 1;
                   4524:         return $access;
                   4525:     }
                   4526: }
                   4527: 
                   4528: sub is_advanced_user {
                   4529:     my ($udom,$uname) = @_;
                   4530:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   4531:     my %allroles;
                   4532:     my $is_adv;
                   4533:     foreach my $role (keys(%roleshash)) {
                   4534:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   4535:         my $area = '/'.$tdomain.'/'.$trest;
                   4536:         if ($sec ne '') {
                   4537:             $area .= '/'.$sec;
                   4538:         }
                   4539:         if (($area ne '') && ($trole ne '')) {
                   4540:             my $spec=$trole.'.'.$area;
                   4541:             if ($trole =~ /^cr\//) {
                   4542:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4543:             } elsif ($trole ne 'gr') {
                   4544:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4545:             }
                   4546:         }
                   4547:     }
                   4548:     foreach my $role (keys(%allroles)) {
                   4549:         last if ($is_adv);
                   4550:         foreach my $item (split(/:/,$allroles{$role})) {
                   4551:             if ($item ne '') {
                   4552:                 my ($privilege,$restrictions)=split(/&/,$item);
                   4553:                 if ($privilege eq 'adv') {
                   4554:                     $is_adv = 1;
                   4555:                     last;
                   4556:                 }
                   4557:             }
                   4558:         }
                   4559:     }
                   4560:     return $is_adv;
                   4561: }
1.798     raeburn  4562: 
1.341     www      4563: # ---------------------------------------------- Custom access rule evaluation
                   4564: 
                   4565: sub customaccess {
                   4566:     my ($priv,$uri)=@_;
1.807     albertel 4567:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4568:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4569:     $udom = &LONCAPA::clean_domain($udom);
                   4570:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4571:     my $access=0;
1.800     albertel 4572:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4573: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4574: 	if ($type eq 'user') {
                   4575: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4576: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4577: 		if ($tdom) {
                   4578: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4579: 		}
1.896     albertel 4580: 		if ($tuname) {
                   4581: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4582: 		}
                   4583: 		$access=($effect eq 'allow');
                   4584: 		last;
                   4585: 	    }
                   4586: 	} else {
                   4587: 	    if ($role) {
                   4588: 		if ($role ne $urole) { next; }
                   4589: 	    }
                   4590: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4591: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4592: 		if ($tdom) {
                   4593: 		    if ($tdom ne $udom) { next; }
                   4594: 		}
                   4595: 		if ($tcrs) {
                   4596: 		    if ($tcrs ne $ucrs) { next; }
                   4597: 		}
                   4598: 		if ($tsec) {
                   4599: 		    if ($tsec ne $usec) { next; }
                   4600: 		}
                   4601: 		$access=($effect eq 'allow');
                   4602: 		last;
                   4603: 	    }
                   4604: 	    if ($realm eq '' && $role eq '') {
                   4605: 		$access=($effect eq 'allow');
                   4606: 	    }
1.402     bowersj2 4607: 	}
1.341     www      4608:     }
                   4609:     return $access;
                   4610: }
                   4611: 
1.103     harris41 4612: # ------------------------------------------------- Check for a user privilege
1.12      www      4613: 
                   4614: sub allowed {
1.810     raeburn  4615:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4616:     my $ver_orguri=$uri;
1.439     www      4617:     $uri=&deversion($uri);
1.152     www      4618:     my $orguri=$uri;
1.52      www      4619:     $uri=&declutter($uri);
1.809     raeburn  4620: 
1.810     raeburn  4621:     if ($priv eq 'evb') {
                   4622: # Evade communication block restrictions for specified role in a course
                   4623:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4624:             return $1;
                   4625:         } else {
                   4626:             return;
                   4627:         }
                   4628:     }
                   4629: 
1.620     albertel 4630:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4631: # Free bre access to adm and meta resources
1.775     albertel 4632:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4633: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4634: 	&& ($priv eq 'bre')) {
1.14      www      4635: 	return 'F';
1.159     www      4636:     }
                   4637: 
1.545     banghart 4638: # Free bre access to user's own portfolio contents
1.714     raeburn  4639:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4640:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4641: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4642:         my %setters;
                   4643:         my ($startblock,$endblock) = 
                   4644:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4645:         if ($startblock && $endblock) {
                   4646:             return 'B';
                   4647:         } else {
                   4648:             return 'F';
                   4649:         }
1.545     banghart 4650:     }
                   4651: 
1.762     raeburn  4652: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4653:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4654:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4655:         if (exists($env{'request.course.id'})) {
                   4656:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4657:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4658:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4659:                 my $courseprivid=$env{'request.course.id'};
                   4660:                 $courseprivid=~s/\_/\//;
                   4661:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4662:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4663:                     return $1; 
1.762     raeburn  4664:                 } else {
                   4665:                     if ($env{'request.course.sec'}) {
                   4666:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4667:                     }
                   4668:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4669:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4670:                         return $2;
                   4671:                     }
1.714     raeburn  4672:                 }
                   4673:             }
                   4674:         }
                   4675:     }
                   4676: 
1.159     www      4677: # Free bre to public access
                   4678: 
                   4679:     if ($priv eq 'bre') {
1.238     www      4680:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4681: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4682:            return 'F'; 
                   4683:         }
1.238     www      4684:         if ($copyright eq 'priv') {
                   4685:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4686: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4687: 		return '';
                   4688:             }
                   4689:         }
                   4690:         if ($copyright eq 'domain') {
                   4691:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4692: 	    unless (($env{'user.domain'} eq $1) ||
                   4693:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4694: 		return '';
                   4695:             }
1.262     matthew  4696:         }
1.620     albertel 4697:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4698:             # Library role, so allow browsing of resources in this domain.
                   4699:             return 'F';
1.238     www      4700:         }
1.341     www      4701:         if ($copyright eq 'custom') {
                   4702: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4703:         }
1.14      www      4704:     }
1.264     matthew  4705:     # Domain coordinator is trying to create a course
1.620     albertel 4706:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4707:         # uri is the requested domain in this case.
                   4708:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4709:         # a role of dc for the domain in question.
1.620     albertel 4710:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4711:     }
1.29      www      4712: 
1.52      www      4713:     my $thisallowed='';
                   4714:     my $statecond=0;
                   4715:     my $courseprivid='';
                   4716: 
                   4717: # Course
                   4718: 
1.620     albertel 4719:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4720:        $thisallowed.=$1;
                   4721:     }
1.29      www      4722: 
1.52      www      4723: # Domain
                   4724: 
1.620     albertel 4725:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4726:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4727:        $thisallowed.=$1;
                   4728:     }
1.52      www      4729: 
                   4730: # Course: uri itself is a course
1.66      www      4731:     my $courseuri=$uri;
                   4732:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4733:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4734: 
1.620     albertel 4735:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4736:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4737:        $thisallowed.=$1;
                   4738:     }
1.29      www      4739: 
1.665     albertel 4740: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4741: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4742:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4743: 	$thisallowed='';
1.671     raeburn  4744:         my ($match)=&is_on_map($uri);
                   4745:         if ($match) {
                   4746:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4747:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4748:                 $thisallowed.=$1;
                   4749:             }
                   4750:         } else {
1.705     albertel 4751:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4752:             if ($refuri) {
                   4753:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4754:                     $thisallowed='F';
1.671     raeburn  4755:                 } else {
                   4756:                     $refuri=&declutter($refuri);
                   4757:                     my ($match) = &is_on_map($refuri);
                   4758:                     if ($match) {
                   4759:                         $thisallowed='F';
                   4760:                     }
1.669     raeburn  4761:                 }
1.671     raeburn  4762:             }
                   4763:         }
1.314     www      4764:     }
1.492     albertel 4765: 
1.766     albertel 4766:     if ($priv eq 'bre'
                   4767: 	&& $thisallowed ne 'F' 
                   4768: 	&& $thisallowed ne '2'
                   4769: 	&& &is_portfolio_url($uri)) {
                   4770: 	$thisallowed = &portfolio_access($uri);
                   4771:     }
                   4772:     
1.52      www      4773: # Full access at system, domain or course-wide level? Exit.
1.29      www      4774:     if ($thisallowed=~/F/) {
                   4775: 	return 'F';
                   4776:     }
                   4777: 
1.52      www      4778: # If this is generating or modifying users, exit with special codes
1.29      www      4779: 
1.643     www      4780:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4781: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4782: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4783: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4784: 	    unless ($auname) { return $thisallowed; }
                   4785: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4786: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4787: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4788: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4789: 	}
1.52      www      4790: 	return $thisallowed;
                   4791:     }
                   4792: #
1.103     harris41 4793: # Gathered so far: system, domain and course wide privileges
1.52      www      4794: #
                   4795: # Course: See if uri or referer is an individual resource that is part of 
                   4796: # the course
                   4797: 
1.620     albertel 4798:     if ($env{'request.course.id'}) {
1.232     www      4799: 
1.620     albertel 4800:        $courseprivid=$env{'request.course.id'};
                   4801:        if ($env{'request.course.sec'}) {
                   4802:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4803:        }
                   4804:        $courseprivid=~s/\_/\//;
                   4805:        my $checkreferer=1;
1.232     www      4806:        my ($match,$cond)=&is_on_map($uri);
                   4807:        if ($match) {
                   4808:            $statecond=$cond;
1.620     albertel 4809:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4810:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4811:                $thisallowed.=$1;
                   4812:                $checkreferer=0;
                   4813:            }
1.29      www      4814:        }
1.83      www      4815:        
1.148     www      4816:        if ($checkreferer) {
1.620     albertel 4817: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4818:             unless ($refuri) {
1.800     albertel 4819:                 foreach my $key (keys(%env)) {
                   4820: 		    if ($key=~/^httpref\..*\*/) {
                   4821: 			my $pattern=$key;
1.156     www      4822:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4823:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4824:                         $pattern=~s/\//\\\//g;
1.152     www      4825:                         if ($orguri=~/$pattern/) {
1.800     albertel 4826: 			    $refuri=$env{$key};
1.148     www      4827:                         }
                   4828:                     }
1.191     harris41 4829:                 }
1.148     www      4830:             }
1.232     www      4831: 
1.148     www      4832:          if ($refuri) { 
1.152     www      4833: 	  $refuri=&declutter($refuri);
1.232     www      4834:           my ($match,$cond)=&is_on_map($refuri);
                   4835:             if ($match) {
                   4836:               my $refstatecond=$cond;
1.620     albertel 4837:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4838:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4839:                   $thisallowed.=$1;
1.53      www      4840:                   $uri=$refuri;
                   4841:                   $statecond=$refstatecond;
1.52      www      4842:               }
                   4843:           }
1.148     www      4844:         }
1.29      www      4845:        }
1.52      www      4846:    }
1.29      www      4847: 
1.52      www      4848: #
1.103     harris41 4849: # Gathered now: all privileges that could apply, and condition number
1.52      www      4850: # 
                   4851: #
                   4852: # Full or no access?
                   4853: #
1.29      www      4854: 
1.52      www      4855:     if ($thisallowed=~/F/) {
                   4856: 	return 'F';
                   4857:     }
1.29      www      4858: 
1.52      www      4859:     unless ($thisallowed) {
                   4860:         return '';
                   4861:     }
1.29      www      4862: 
1.52      www      4863: # Restrictions exist, deal with them
                   4864: #
                   4865: #   C:according to course preferences
                   4866: #   R:according to resource settings
                   4867: #   L:unless locked
                   4868: #   X:according to user session state
                   4869: #
                   4870: 
                   4871: # Possibly locked functionality, check all courses
1.54      www      4872: # Locks might take effect only after 10 minutes cache expiration for other
                   4873: # courses, and 2 minutes for current course
1.52      www      4874: 
                   4875:     my $envkey;
                   4876:     if ($thisallowed=~/L/) {
1.620     albertel 4877:         foreach $envkey (keys %env) {
1.54      www      4878:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4879:                my $courseid=$2;
                   4880:                my $roleid=$1.'.'.$2;
1.92      www      4881:                $courseid=~s/^\///;
1.54      www      4882:                my $expiretime=600;
1.620     albertel 4883:                if ($env{'request.role'} eq $roleid) {
1.54      www      4884: 		  $expiretime=120;
                   4885:                }
                   4886: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4887:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4888:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4889: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4890:                }
1.620     albertel 4891:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4892:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4893: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4894:                        &log($env{'user.domain'},$env{'user.name'},
                   4895:                             $env{'user.home'},
1.57      www      4896:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4897:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4898:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4899: 		       return '';
                   4900:                    }
                   4901:                }
1.620     albertel 4902:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4903:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4904: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4905:                        &log($env{'user.domain'},$env{'user.name'},
                   4906:                             $env{'user.home'},
1.57      www      4907:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4908:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4909:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4910: 		       return '';
                   4911:                    }
                   4912:                }
                   4913: 	   }
1.29      www      4914:        }
1.52      www      4915:     }
                   4916:    
                   4917: #
                   4918: # Rest of the restrictions depend on selected course
                   4919: #
                   4920: 
1.620     albertel 4921:     unless ($env{'request.course.id'}) {
1.766     albertel 4922: 	if ($thisallowed eq 'A') {
                   4923: 	    return 'A';
1.814     raeburn  4924:         } elsif ($thisallowed eq 'B') {
                   4925:             return 'B';
1.766     albertel 4926: 	} else {
                   4927: 	    return '1';
                   4928: 	}
1.52      www      4929:     }
1.29      www      4930: 
1.52      www      4931: #
                   4932: # Now user is definitely in a course
                   4933: #
1.53      www      4934: 
                   4935: 
                   4936: # Course preferences
                   4937: 
                   4938:    if ($thisallowed=~/C/) {
1.620     albertel 4939:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4940:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4941:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4942: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4943: 	   if ($priv ne 'pch') { 
                   4944: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4945: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4946: 			$env{'request.course.id'});
                   4947: 	   }
1.237     www      4948:            return '';
                   4949:        }
                   4950: 
1.620     albertel 4951:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4952: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4953: 	   if ($priv ne 'pch') { 
                   4954: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4955: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4956: 			$env{'request.course.id'});
                   4957: 	   }
1.54      www      4958:            return '';
                   4959:        }
1.53      www      4960:    }
                   4961: 
                   4962: # Resource preferences
                   4963: 
                   4964:    if ($thisallowed=~/R/) {
1.620     albertel 4965:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4966:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4967: 	   if ($priv ne 'pch') { 
                   4968: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4969: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4970: 	   }
                   4971: 	   return '';
1.54      www      4972:        }
1.53      www      4973:    }
1.30      www      4974: 
1.246     www      4975: # Restricted by state or randomout?
1.30      www      4976: 
1.52      www      4977:    if ($thisallowed=~/X/) {
1.620     albertel 4978:       if ($env{'acc.randomout'}) {
1.579     albertel 4979: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4980:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4981:             return ''; 
                   4982:          }
1.247     www      4983:       }
                   4984:       if (&condval($statecond)) {
1.52      www      4985: 	 return '2';
                   4986:       } else {
                   4987:          return '';
                   4988:       }
                   4989:    }
1.30      www      4990: 
1.766     albertel 4991:     if ($thisallowed eq 'A') {
                   4992: 	return 'A';
1.814     raeburn  4993:     } elsif ($thisallowed eq 'B') {
                   4994:         return 'B';
1.766     albertel 4995:     }
1.52      www      4996:    return 'F';
1.232     www      4997: }
                   4998: 
1.710     albertel 4999: sub split_uri_for_cond {
                   5000:     my $uri=&deversion(&declutter(shift));
                   5001:     my @uriparts=split(/\//,$uri);
                   5002:     my $filename=pop(@uriparts);
                   5003:     my $pathname=join('/',@uriparts);
                   5004:     return ($pathname,$filename);
                   5005: }
1.232     www      5006: # --------------------------------------------------- Is a resource on the map?
                   5007: 
                   5008: sub is_on_map {
1.710     albertel 5009:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 5010:     #Trying to find the conditional for the file
1.620     albertel 5011:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 5012: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      5013:     if ($match) {
1.289     bowersj2 5014: 	return (1,$1);
                   5015:     } else {
1.434     www      5016: 	return (0,0);
1.289     bowersj2 5017:     }
1.12      www      5018: }
                   5019: 
1.427     www      5020: # --------------------------------------------------------- Get symb from alias
                   5021: 
                   5022: sub get_symb_from_alias {
                   5023:     my $symb=shift;
                   5024:     my ($map,$resid,$url)=&decode_symb($symb);
                   5025: # Already is a symb
                   5026:     if ($url) { return $symb; }
                   5027: # Must be an alias
                   5028:     my $aliassymb='';
                   5029:     my %bighash;
1.620     albertel 5030:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      5031:                             &GDBM_READER(),0640)) {
                   5032:         my $rid=$bighash{'mapalias_'.$symb};
                   5033: 	if ($rid) {
                   5034: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 5035: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   5036: 				    $resid,$bighash{'src_'.$rid});
1.427     www      5037: 	}
                   5038:         untie %bighash;
                   5039:     }
                   5040:     return $aliassymb;
                   5041: }
                   5042: 
1.12      www      5043: # ----------------------------------------------------------------- Define Role
                   5044: 
                   5045: sub definerole {
                   5046:   if (allowed('mcr','/')) {
                   5047:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 5048:     foreach my $role (split(':',$sysrole)) {
                   5049: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5050:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   5051:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   5052: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5053:                return "refused:s:$crole&$cqual"; 
                   5054:             }
                   5055:         }
1.191     harris41 5056:     }
1.800     albertel 5057:     foreach my $role (split(':',$domrole)) {
                   5058: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5059:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   5060:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   5061: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      5062:                return "refused:d:$crole&$cqual"; 
                   5063:             }
                   5064:         }
1.191     harris41 5065:     }
1.800     albertel 5066:     foreach my $role (split(':',$courole)) {
                   5067: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 5068:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   5069:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   5070: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      5071:                return "refused:c:$crole&$cqual"; 
                   5072:             }
                   5073:         }
1.191     harris41 5074:     }
1.620     albertel 5075:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   5076:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5077: 	        "rolesdef_$rolename=".
                   5078:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 5079:     return reply($command,$env{'user.home'});
1.12      www      5080:   } else {
                   5081:     return 'refused';
                   5082:   }
1.105     harris41 5083: }
                   5084: 
                   5085: # ---------------- Make a metadata query against the network of library servers
                   5086: 
                   5087: sub metadata_query {
1.244     matthew  5088:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 5089:     my %rhash;
1.845     albertel 5090:     my %libserv = &all_library();
1.244     matthew  5091:     my @server_list = (defined($server_array) ? @$server_array
                   5092:                                               : keys(%libserv) );
                   5093:     for my $server (@server_list) {
1.118     harris41 5094: 	unless ($custom or $customshow) {
                   5095: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   5096: 	    $rhash{$server}=$reply;
                   5097: 	}
                   5098: 	else {
                   5099: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   5100: 			     &escape($custom).':'.&escape($customshow),
                   5101: 			     $server);
                   5102: 	    $rhash{$server}=$reply;
                   5103: 	}
1.112     harris41 5104:     }
1.118     harris41 5105:     return \%rhash;
1.240     www      5106: }
                   5107: 
                   5108: # ----------------------------------------- Send log queries and wait for reply
                   5109: 
                   5110: sub log_query {
                   5111:     my ($uname,$udom,$query,%filters)=@_;
                   5112:     my $uhome=&homeserver($uname,$udom);
                   5113:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 5114:     my $uhost=&hostname($uhome);
1.800     albertel 5115:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      5116:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   5117:                        $uhome);
1.479     albertel 5118:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      5119:     return get_query_reply($queryid);
                   5120: }
                   5121: 
1.818     raeburn  5122: # -------------------------- Update MySQL table for portfolio file
                   5123: 
                   5124: sub update_portfolio_table {
1.821     raeburn  5125:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  5126:     if ($group ne '') {
                   5127:         $file_name =~s /^\Q$group\E//;
                   5128:     }
1.818     raeburn  5129:     my $homeserver = &homeserver($uname,$udom);
                   5130:     my $queryid=
1.821     raeburn  5131:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   5132:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  5133:     my $reply = &get_query_reply($queryid);
                   5134:     return $reply;
                   5135: }
                   5136: 
1.899     raeburn  5137: # -------------------------- Update MySQL allusers table
                   5138: 
                   5139: sub update_allusers_table {
                   5140:     my ($uname,$udom,$names) = @_;
                   5141:     my $homeserver = &homeserver($uname,$udom);
                   5142:     my $queryid=
                   5143:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   5144:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   5145:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   5146:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   5147:                'generation='.&escape($names->{'generation'}).'%%'.
                   5148:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   5149:                'id='.&escape($names->{'id'}),$homeserver);
                   5150:     my $reply = &get_query_reply($queryid);
                   5151:     return $reply;
                   5152: }
                   5153: 
1.508     raeburn  5154: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  5155: 
                   5156: sub fetch_enrollment_query {
1.511     raeburn  5157:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  5158:     my $homeserver;
1.547     raeburn  5159:     my $maxtries = 1;
1.508     raeburn  5160:     if ($context eq 'automated') {
                   5161:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  5162:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  5163:     } else {
                   5164:         $homeserver = &homeserver($cnum,$dom);
                   5165:     }
1.838     albertel 5166:     my $host=&hostname($homeserver);
1.506     raeburn  5167:     my $cmd = '';
1.800     albertel 5168:     foreach my $affiliate (keys %{$affiliatesref}) {
                   5169:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  5170:     }
                   5171:     $cmd =~ s/%%$//;
                   5172:     $cmd = &escape($cmd);
                   5173:     my $query = 'fetchenrollment';
1.620     albertel 5174:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  5175:     unless ($queryid=~/^\Q$host\E\_/) { 
                   5176:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   5177:         return 'error: '.$queryid;
                   5178:     }
1.506     raeburn  5179:     my $reply = &get_query_reply($queryid);
1.547     raeburn  5180:     my $tries = 1;
                   5181:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5182:         $reply = &get_query_reply($queryid);
                   5183:         $tries ++;
                   5184:     }
1.526     raeburn  5185:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 5186:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  5187:     } else {
1.901     albertel 5188:         my @responses = split(/:/,$reply);
1.515     raeburn  5189:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 5190:             foreach my $line (@responses) {
                   5191:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  5192:                 $$replyref{$key} = $value;
                   5193:             }
                   5194:         } else {
1.506     raeburn  5195:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 5196:             foreach my $line (@responses) {
                   5197:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  5198:                 $$replyref{$key} = $value;
                   5199:                 if ($value > 0) {
1.800     albertel 5200:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   5201:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  5202:                         my $destname = $pathname.'/'.$filename;
                   5203:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  5204:                         if ($xml_classlist =~ /^error/) {
                   5205:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   5206:                         } else {
1.506     raeburn  5207:                             if ( open(FILE,">$destname") ) {
                   5208:                                 print FILE &unescape($xml_classlist);
                   5209:                                 close(FILE);
1.526     raeburn  5210:                             } else {
                   5211:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  5212:                             }
                   5213:                         }
                   5214:                     }
                   5215:                 }
                   5216:             }
                   5217:         }
                   5218:         return 'ok';
                   5219:     }
                   5220:     return 'error';
                   5221: }
                   5222: 
1.242     www      5223: sub get_query_reply {
                   5224:     my $queryid=shift;
1.240     www      5225:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   5226:     my $reply='';
                   5227:     for (1..100) {
                   5228: 	sleep 2;
                   5229:         if (-e $replyfile.'.end') {
1.448     albertel 5230: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 5231: 		$reply = join('',<$fh>);
                   5232: 		close($fh);
1.240     www      5233: 	   } else { return 'error: reply_file_error'; }
1.242     www      5234:            return &unescape($reply);
                   5235: 	}
1.240     www      5236:     }
1.242     www      5237:     return 'timeout:'.$queryid;
1.240     www      5238: }
                   5239: 
                   5240: sub courselog_query {
1.241     www      5241: #
                   5242: # possible filters:
                   5243: # url: url or symb
                   5244: # username
                   5245: # domain
                   5246: # action: view, submit, grade
                   5247: # start: timestamp
                   5248: # end: timestamp
                   5249: #
1.240     www      5250:     my (%filters)=@_;
1.620     albertel 5251:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      5252:     if ($filters{'url'}) {
                   5253: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   5254:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   5255:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   5256:     }
1.620     albertel 5257:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5258:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      5259:     return &log_query($cname,$cdom,'courselog',%filters);
                   5260: }
                   5261: 
                   5262: sub userlog_query {
1.858     raeburn  5263: #
                   5264: # possible filters:
                   5265: # action: log check role
                   5266: # start: timestamp
                   5267: # end: timestamp
                   5268: #
1.240     www      5269:     my ($uname,$udom,%filters)=@_;
                   5270:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      5271: }
                   5272: 
1.506     raeburn  5273: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   5274: 
                   5275: sub auto_run {
1.508     raeburn  5276:     my ($cnum,$cdom) = @_;
1.876     raeburn  5277:     my $response = 0;
                   5278:     my $settings;
                   5279:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   5280:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5281:         $settings = $domconfig{'autoenroll'};
                   5282:         if ($settings->{'run'} eq '1') {
                   5283:             $response = 1;
                   5284:         }
                   5285:     } else {
1.934     raeburn  5286:         my $homeserver;
                   5287:         if (&is_course($cdom,$cnum)) {
                   5288:             $homeserver = &homeserver($cnum,$cdom);
                   5289:         } else {
                   5290:             $homeserver = &domain($cdom,'primary');
                   5291:         }
                   5292:         if ($homeserver ne 'no_host') {
                   5293:             $response = &reply('autorun:'.$cdom,$homeserver);
                   5294:         }
1.876     raeburn  5295:     }
1.506     raeburn  5296:     return $response;
                   5297: }
1.776     albertel 5298: 
1.506     raeburn  5299: sub auto_get_sections {
1.508     raeburn  5300:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   5301:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  5302:     my @secs = ();
1.511     raeburn  5303:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  5304:     unless ($response eq 'refused') {
1.901     albertel 5305:         @secs = split(/:/,$response);
1.506     raeburn  5306:     }
                   5307:     return @secs;
                   5308: }
1.776     albertel 5309: 
1.506     raeburn  5310: sub auto_new_course {
1.508     raeburn  5311:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   5312:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  5313:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  5314:     return $response;
                   5315: }
1.776     albertel 5316: 
1.506     raeburn  5317: sub auto_validate_courseID {
1.508     raeburn  5318:     my ($cnum,$cdom,$inst_course_id) = @_;
                   5319:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  5320:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  5321:     return $response;
                   5322: }
1.776     albertel 5323: 
1.506     raeburn  5324: sub auto_create_password {
1.873     raeburn  5325:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   5326:     my ($homeserver,$response);
1.506     raeburn  5327:     my $create_passwd = 0;
                   5328:     my $authchk = '';
1.873     raeburn  5329:     if ($udom =~ /^$match_domain$/) {
                   5330:         $homeserver = &domain($udom,'primary');
                   5331:     }
                   5332:     if ($homeserver eq '') {
                   5333:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   5334:             $homeserver = &homeserver($cnum,$cdom);
                   5335:         }
                   5336:     }
                   5337:     if ($homeserver eq '') {
                   5338:         $authchk = 'nodomain';
1.506     raeburn  5339:     } else {
1.873     raeburn  5340:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   5341:         if ($response eq 'refused') {
                   5342:             $authchk = 'refused';
                   5343:         } else {
1.901     albertel 5344:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  5345:         }
1.506     raeburn  5346:     }
                   5347:     return ($authparam,$create_passwd,$authchk);
                   5348: }
                   5349: 
1.706     raeburn  5350: sub auto_photo_permission {
                   5351:     my ($cnum,$cdom,$students) = @_;
                   5352:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 5353:     my ($outcome,$perm_reqd,$conditions) = 
                   5354: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 5355:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5356: 	return (undef,undef);
                   5357:     }
1.706     raeburn  5358:     return ($outcome,$perm_reqd,$conditions);
                   5359: }
                   5360: 
                   5361: sub auto_checkphotos {
                   5362:     my ($uname,$udom,$pid) = @_;
                   5363:     my $homeserver = &homeserver($uname,$udom);
                   5364:     my ($result,$resulttype);
                   5365:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5366: 				   &escape($uname).':'.&escape($pid),
                   5367: 				   $homeserver));
1.709     albertel 5368:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5369: 	return (undef,undef);
                   5370:     }
1.706     raeburn  5371:     if ($outcome) {
                   5372:         ($result,$resulttype) = split(/:/,$outcome);
                   5373:     } 
                   5374:     return ($result,$resulttype);
                   5375: }
                   5376: 
                   5377: sub auto_photochoice {
                   5378:     my ($cnum,$cdom) = @_;
                   5379:     my $homeserver = &homeserver($cnum,$cdom);
                   5380:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5381: 						       &escape($cdom),
                   5382: 						       $homeserver)));
1.709     albertel 5383:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5384: 	return (undef,undef);
                   5385:     }
1.706     raeburn  5386:     return ($update,$comment);
                   5387: }
                   5388: 
                   5389: sub auto_photoupdate {
                   5390:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5391:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5392:     my $host=&hostname($homeserver);
1.706     raeburn  5393:     my $cmd = '';
                   5394:     my $maxtries = 1;
1.800     albertel 5395:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5396:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5397:     }
                   5398:     $cmd =~ s/%%$//;
                   5399:     $cmd = &escape($cmd);
                   5400:     my $query = 'institutionalphotos';
                   5401:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5402:     unless ($queryid=~/^\Q$host\E\_/) {
                   5403:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5404:         return 'error: '.$queryid;
                   5405:     }
                   5406:     my $reply = &get_query_reply($queryid);
                   5407:     my $tries = 1;
                   5408:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5409:         $reply = &get_query_reply($queryid);
                   5410:         $tries ++;
                   5411:     }
                   5412:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5413:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5414:     } else {
                   5415:         my @responses = split(/:/,$reply);
                   5416:         my $outcome = shift(@responses); 
                   5417:         foreach my $item (@responses) {
                   5418:             my ($key,$value) = split(/=/,$item);
                   5419:             $$photo{$key} = $value;
                   5420:         }
                   5421:         return $outcome;
                   5422:     }
                   5423:     return 'error';
                   5424: }
                   5425: 
1.521     raeburn  5426: sub auto_instcode_format {
1.793     albertel 5427:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5428: 	$cat_order) = @_;
1.521     raeburn  5429:     my $courses = '';
1.772     raeburn  5430:     my @homeservers;
1.521     raeburn  5431:     if ($caller eq 'global') {
1.841     albertel 5432: 	my %servers = &get_servers($codedom,'library');
                   5433: 	foreach my $tryserver (keys(%servers)) {
                   5434: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5435: 		push(@homeservers,$tryserver);
                   5436: 	    }
1.584     raeburn  5437:         }
1.521     raeburn  5438:     } else {
1.772     raeburn  5439:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5440:     }
1.793     albertel 5441:     foreach my $code (keys(%{$instcodes})) {
                   5442:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5443:     }
                   5444:     chop($courses);
1.772     raeburn  5445:     my $ok_response = 0;
                   5446:     my $response;
                   5447:     while (@homeservers > 0 && $ok_response == 0) {
                   5448:         my $server = shift(@homeservers); 
                   5449:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5450:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5451:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5452: 		split(/:/,$response);
1.772     raeburn  5453:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5454:             push(@{$codetitles},&str2array($codetitles_str));
                   5455:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5456:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5457:             $ok_response = 1;
                   5458:         }
                   5459:     }
                   5460:     if ($ok_response) {
1.521     raeburn  5461:         return 'ok';
1.772     raeburn  5462:     } else {
                   5463:         return $response;
1.521     raeburn  5464:     }
                   5465: }
                   5466: 
1.792     raeburn  5467: sub auto_instcode_defaults {
                   5468:     my ($domain,$returnhash,$code_order) = @_;
                   5469:     my @homeservers;
1.841     albertel 5470: 
                   5471:     my %servers = &get_servers($domain,'library');
                   5472:     foreach my $tryserver (keys(%servers)) {
                   5473: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5474: 	    push(@homeservers,$tryserver);
                   5475: 	}
1.792     raeburn  5476:     }
1.841     albertel 5477: 
1.792     raeburn  5478:     my $response;
1.841     albertel 5479:     foreach my $server (@homeservers) {
1.792     raeburn  5480:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5481:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5482: 	
                   5483: 	foreach my $pair (split(/\&/,$response)) {
                   5484: 	    my ($name,$value)=split(/\=/,$pair);
                   5485: 	    if ($name eq 'code_order') {
                   5486: 		@{$code_order} = split(/\&/,&unescape($value));
                   5487: 	    } else {
                   5488: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5489: 	    }
                   5490: 	}
                   5491: 	return 'ok';
1.792     raeburn  5492:     }
1.841     albertel 5493: 
                   5494:     return $response;
1.792     raeburn  5495: } 
                   5496: 
1.777     albertel 5497: sub auto_validate_class_sec {
1.918     raeburn  5498:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5499:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5500:     my $ownerlist;
                   5501:     if (ref($owners) eq 'ARRAY') {
                   5502:         $ownerlist = join(',',@{$owners});
                   5503:     } else {
                   5504:         $ownerlist = $owners;
                   5505:     }
1.773     raeburn  5506:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5507:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5508:     return $response;
                   5509: }
                   5510: 
1.679     raeburn  5511: # ------------------------------------------------------- Course Group routines
                   5512: 
                   5513: sub get_coursegroups {
1.809     raeburn  5514:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5515:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5516: }
                   5517: 
1.679     raeburn  5518: sub modify_coursegroup {
                   5519:     my ($cdom,$cnum,$groupsettings) = @_;
                   5520:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5521: }
                   5522: 
1.809     raeburn  5523: sub toggle_coursegroup_status {
                   5524:     my ($cdom,$cnum,$group,$action) = @_;
                   5525:     my ($from_namespace,$to_namespace);
                   5526:     if ($action eq 'delete') {
                   5527:         $from_namespace = 'coursegroups';
                   5528:         $to_namespace = 'deleted_groups';
                   5529:     } else {
                   5530:         $from_namespace = 'deleted_groups';
                   5531:         $to_namespace = 'coursegroups';
                   5532:     }
                   5533:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5534:     if (my $tmp = &error(%curr_group)) {
                   5535:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5536:         return ('read error',$tmp);
                   5537:     } else {
                   5538:         my %savedsettings = %curr_group; 
1.809     raeburn  5539:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5540:         my $deloutcome;
                   5541:         if ($result eq 'ok') {
1.809     raeburn  5542:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5543:         } else {
                   5544:             return ('write error',$result);
                   5545:         }
                   5546:         if ($deloutcome eq 'ok') {
                   5547:             return 'ok';
                   5548:         } else {
                   5549:             return ('delete error',$deloutcome);
                   5550:         }
                   5551:     }
                   5552: }
                   5553: 
1.679     raeburn  5554: sub modify_group_roles {
1.957     raeburn  5555:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  5556:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5557:     my $role = 'gr/'.&escape($userprivs);
                   5558:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  5559:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  5560:     if ($result eq 'ok') {
                   5561:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5562:     }
1.679     raeburn  5563:     return $result;
                   5564: }
                   5565: 
                   5566: sub modify_coursegroup_membership {
                   5567:     my ($cdom,$cnum,$membership) = @_;
                   5568:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5569:     return $result;
                   5570: }
                   5571: 
1.682     raeburn  5572: sub get_active_groups {
                   5573:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5574:     my $now = time;
                   5575:     my %groups = ();
                   5576:     foreach my $key (keys(%env)) {
1.811     albertel 5577:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5578:             my ($start,$end) = split(/\./,$env{$key});
                   5579:             if (($end!=0) && ($end<$now)) { next; }
                   5580:             if (($start!=0) && ($start>$now)) { next; }
                   5581:             if ($1 eq $cdom && $2 eq $cnum) {
                   5582:                 $groups{$3} = $env{$key} ;
                   5583:             }
                   5584:         }
                   5585:     }
                   5586:     return %groups;
                   5587: }
                   5588: 
1.683     raeburn  5589: sub get_group_membership {
                   5590:     my ($cdom,$cnum,$group) = @_;
                   5591:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5592: }
                   5593: 
                   5594: sub get_users_groups {
                   5595:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5596:     my @usersgroups;
1.683     raeburn  5597:     my $cachetime=1800;
                   5598: 
                   5599:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5600:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5601:     if (defined($cached)) {
1.734     albertel 5602:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5603:     } else {  
                   5604:         $grouplist = '';
1.816     raeburn  5605:         my $courseurl = &courseid_to_courseurl($courseid);
                   5606:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5607:         my $access_end = $env{'course.'.$courseid.
                   5608:                               '.default_enrollment_end_date'};
                   5609:         my $now = time;
                   5610:         foreach my $key (keys(%roleshash)) {
                   5611:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5612:                 my $group = $1;
                   5613:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5614:                     my $start = $2;
                   5615:                     my $end = $1;
                   5616:                     if ($start == -1) { next; } # deleted from group
                   5617:                     if (($start!=0) && ($start>$now)) { next; }
                   5618:                     if (($end!=0) && ($end<$now)) {
                   5619:                         if ($access_end && $access_end < $now) {
                   5620:                             if ($access_end - $end < 86400) {
                   5621:                                 push(@usersgroups,$group);
1.733     raeburn  5622:                             }
                   5623:                         }
1.817     raeburn  5624:                         next;
1.733     raeburn  5625:                     }
1.817     raeburn  5626:                     push(@usersgroups,$group);
1.683     raeburn  5627:                 }
                   5628:             }
                   5629:         }
1.817     raeburn  5630:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5631:         $grouplist = join(':',@usersgroups);
                   5632:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5633:     }
1.733     raeburn  5634:     return @usersgroups;
1.683     raeburn  5635: }
                   5636: 
                   5637: sub devalidate_getgroups_cache {
                   5638:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5639:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5640: 
1.683     raeburn  5641:     my $hashid="$udom:$uname:$courseid";
                   5642:     &devalidate_cache_new('getgroups',$hashid);
                   5643: }
                   5644: 
1.12      www      5645: # ------------------------------------------------------------------ Plain Text
                   5646: 
                   5647: sub plaintext {
1.742     raeburn  5648:     my ($short,$type,$cid) = @_;
1.758     albertel 5649:     if ($short =~ /^cr/) {
                   5650: 	return (split('/',$short))[-1];
                   5651:     }
1.742     raeburn  5652:     if (!defined($cid)) {
                   5653:         $cid = $env{'request.course.id'};
                   5654:     }
                   5655:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5656:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5657:                                           '.plaintext'});
                   5658:     }
                   5659:     my %rolenames = (
                   5660:                       Course => 'std',
                   5661:                       Group => 'alt1',
                   5662:                     );
                   5663:     if (defined($type) && 
                   5664:          defined($rolenames{$type}) && 
                   5665:          defined($prp{$short}{$rolenames{$type}})) {
                   5666:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5667:     } else {
                   5668:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5669:     }
1.12      www      5670: }
                   5671: 
                   5672: # ----------------------------------------------------------------- Assign Role
                   5673: 
                   5674: sub assignrole {
1.957     raeburn  5675:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   5676:         $context)=@_;
1.21      www      5677:     my $mrole;
                   5678:     if ($role =~ /^cr\//) {
1.393     www      5679:         my $cwosec=$url;
1.811     albertel 5680:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5681: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5682:            &logthis('Refused custom assignrole: '.
                   5683:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5684: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5685:            return 'refused'; 
                   5686:         }
1.21      www      5687:         $mrole='cr';
1.678     raeburn  5688:     } elsif ($role =~ /^gr\//) {
                   5689:         my $cwogrp=$url;
1.811     albertel 5690:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5691:         unless (&allowed('mdg',$cwogrp)) {
                   5692:             &logthis('Refused group assignrole: '.
                   5693:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5694:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5695:             return 'refused';
                   5696:         }
                   5697:         $mrole='gr';
1.21      www      5698:     } else {
1.82      www      5699:         my $cwosec=$url;
1.811     albertel 5700:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5701:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5702:             my $refused;
                   5703:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5704:                 if (!(&allowed('c'.$role,$url))) {
                   5705:                     $refused = 1;
                   5706:                 }
                   5707:             } else {
                   5708:                 $refused = 1;
                   5709:             }
1.947     raeburn  5710:             if ($refused) {
                   5711:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5712:                     $refused = '';
                   5713:                 } else {
                   5714:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5715:                              ' '.$role.' '.$end.' '.$start.' by '.
                   5716: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   5717:                     return 'refused';
                   5718:                 }
1.932     raeburn  5719:             }
1.104     www      5720:         }
1.21      www      5721:         $mrole=$role;
                   5722:     }
1.620     albertel 5723:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5724:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5725:     if ($end) { $command.='_'.$end; }
1.21      www      5726:     if ($start) {
                   5727: 	if ($end) { 
1.81      www      5728:            $command.='_'.$start; 
1.21      www      5729:         } else {
1.81      www      5730:            $command.='_0_'.$start;
1.21      www      5731:         }
                   5732:     }
1.739     raeburn  5733:     my $origstart = $start;
                   5734:     my $origend = $end;
1.957     raeburn  5735:     my $delflag;
1.357     www      5736: # actually delete
                   5737:     if ($deleteflag) {
1.373     www      5738: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5739: # modify command to delete the role
1.620     albertel 5740:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5741:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5742: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5743: # set start and finish to negative values for userrolelog
                   5744:            $start=-1;
                   5745:            $end=-1;
1.957     raeburn  5746:            $delflag = 1;
1.357     www      5747:         }
                   5748:     }
                   5749: # send command
1.349     www      5750:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5751: # log new user role if status is ok
1.349     www      5752:     if ($answer eq 'ok') {
1.663     raeburn  5753: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5754: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  5755:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  5756:         unless ($role =~ /^gr/) {
                   5757:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  5758:                                              $origstart,$selfenroll,$context);
1.739     raeburn  5759:         }
1.349     www      5760:     }
                   5761:     return $answer;
1.169     harris41 5762: }
                   5763: 
                   5764: # -------------------------------------------------- Modify user authentication
1.197     www      5765: # Overrides without validation
                   5766: 
1.169     harris41 5767: sub modifyuserauth {
                   5768:     my ($udom,$uname,$umode,$upass)=@_;
                   5769:     my $uhome=&homeserver($uname,$udom);
1.197     www      5770:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5771:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5772:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5773:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5774:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5775: 		     &escape($upass),$uhome);
1.620     albertel 5776:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5777:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5778:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5779:     &log($udom,,$uname,$uhome,
1.620     albertel 5780:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5781:                                      $env{'user.name'}.', '.$umode.
1.197     www      5782:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5783:     unless ($reply eq 'ok') {
1.197     www      5784:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5785: 	return 'error: '.$reply;
                   5786:     }   
1.170     harris41 5787:     return 'ok';
1.80      www      5788: }
                   5789: 
1.81      www      5790: # --------------------------------------------------------------- Modify a user
1.80      www      5791: 
1.81      www      5792: sub modifyuser {
1.206     matthew  5793:     my ($udom,    $uname, $uid,
                   5794:         $umode,   $upass, $first,
                   5795:         $middle,  $last,  $gene,
1.963     raeburn  5796:         $forceid, $desiredhome, $email, $inststatus)=@_;
1.807     albertel 5797:     $udom= &LONCAPA::clean_domain($udom);
                   5798:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5799:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5800:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5801: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5802:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5803:                                      ' desiredhome not specified'). 
1.620     albertel 5804:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5805:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5806:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5807: # ----------------------------------------------------------------- Create User
1.406     albertel 5808:     if (($uhome eq 'no_host') && 
                   5809: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5810:         my $unhome='';
1.844     albertel 5811:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5812:             $unhome = $desiredhome;
1.620     albertel 5813: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5814: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5815:         } else { # load balancing routine for determining $unhome
1.81      www      5816:             my $loadm=10000000;
1.841     albertel 5817: 	    my %servers = &get_servers($udom,'library');
                   5818: 	    foreach my $tryserver (keys(%servers)) {
                   5819: 		my $answer=reply('load',$tryserver);
                   5820: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5821: 		    $loadm=$answer;
                   5822: 		    $unhome=$tryserver;
                   5823: 		}
1.80      www      5824: 	    }
                   5825:         }
                   5826:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5827: 	    return 'error: unable to find a home server for '.$uname.
                   5828:                    ' in domain '.$udom;
1.80      www      5829:         }
                   5830:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5831:                          &escape($upass),$unhome);
                   5832: 	unless ($reply eq 'ok') {
                   5833:             return 'error: '.$reply;
                   5834:         }   
1.230     stredwic 5835:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5836:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5837: 	    return 'error: unable verify users home machine.';
1.80      www      5838:         }
1.209     matthew  5839:     }   # End of creation of new user
1.80      www      5840: # ---------------------------------------------------------------------- Add ID
                   5841:     if ($uid) {
                   5842:        $uid=~tr/A-Z/a-z/;
                   5843:        my %uidhash=&idrget($udom,$uname);
1.196     www      5844:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5845:          && (!$forceid)) {
1.80      www      5846: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5847: 	      return 'error: user id "'.$uid.'" does not match '.
                   5848:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5849:           }
                   5850:        } else {
                   5851: 	  &idput($udom,($uname => $uid));
                   5852:        }
                   5853:     }
                   5854: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5855:     my @tmp=&get('environment',
1.899     raeburn  5856: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  5857:                     'permanentemail','inststatus'],
1.134     albertel 5858: 		   $udom,$uname);
1.313     matthew  5859:     my %names;
                   5860:     if ($tmp[0] =~ m/^error:.*/) { 
                   5861:         %names=(); 
                   5862:     } else {
                   5863:         %names = @tmp;
                   5864:     }
1.388     www      5865: #
                   5866: # Make sure to not trash student environment if instructor does not bother
                   5867: # to supply name and email information
                   5868: #
                   5869:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5870:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5871:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5872:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5873:     if ($email) {
                   5874:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  5875:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      5876:     }
1.899     raeburn  5877:     if ($uid) { $names{'id'}  = $uid; }
1.963     raeburn  5878:     if (defined($inststatus)) { $names{'inststatus'} = $inststatus; } 
1.134     albertel 5879:     my $reply = &put('environment', \%names, $udom,$uname);
                   5880:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5881:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5882:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.963     raeburn  5883:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
                   5884:                  $umode.', '.$first.', '.$middle.', '.
                   5885: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
                   5886:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   5887:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   5888:     } else {
                   5889:         $logmsg .= ' during self creation';
                   5890:     }
                   5891:     &logthis($logmsg);
1.134     albertel 5892:     return 'ok';
1.80      www      5893: }
                   5894: 
1.81      www      5895: # -------------------------------------------------------------- Modify student
1.80      www      5896: 
1.81      www      5897: sub modifystudent {
                   5898:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  5899:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
                   5900:         $selfenroll,$context)=@_;
1.455     albertel 5901:     if (!$cid) {
1.620     albertel 5902: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5903: 	    return 'not_in_class';
                   5904: 	}
1.80      www      5905:     }
                   5906: # --------------------------------------------------------------- Make the user
1.81      www      5907:     my $reply=&modifyuser
1.209     matthew  5908: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5909:          $desiredhome,$email);
1.80      www      5910:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5911:     # This will cause &modify_student_enrollment to get the uid from the
                   5912:     # students environment
                   5913:     $uid = undef if (!$forceid);
1.455     albertel 5914:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  5915: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  5916:     return $reply;
                   5917: }
                   5918: 
                   5919: sub modify_student_enrollment {
1.957     raeburn  5920:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 5921:     my ($cdom,$cnum,$chome);
                   5922:     if (!$cid) {
1.620     albertel 5923: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5924: 	    return 'not_in_class';
                   5925: 	}
1.620     albertel 5926: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5927: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5928:     } else {
                   5929: 	($cdom,$cnum)=split(/_/,$cid);
                   5930:     }
1.620     albertel 5931:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5932:     if (!$chome) {
1.457     raeburn  5933: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5934:     }
1.455     albertel 5935:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5936:     # Make sure the user exists
1.81      www      5937:     my $uhome=&homeserver($uname,$udom);
                   5938:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5939: 	return 'error: no such user';
                   5940:     }
1.297     matthew  5941:     # Get student data if we were not given enough information
                   5942:     if (!defined($first)  || $first  eq '' || 
                   5943:         !defined($last)   || $last   eq '' || 
                   5944:         !defined($uid)    || $uid    eq '' || 
                   5945:         !defined($middle) || $middle eq '' || 
                   5946:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5947:         # They did not supply us with enough data to enroll the student, so
                   5948:         # we need to pick up more information.
1.297     matthew  5949:         my %tmp = &get('environment',
1.294     matthew  5950:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5951:                        ,$udom,$uname);
                   5952: 
1.800     albertel 5953:         #foreach my $key (keys(%tmp)) {
                   5954:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5955:         #}
1.294     matthew  5956:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5957:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5958:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5959:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5960:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5961:     }
1.556     albertel 5962:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5963:     my $reply=cput('classlist',
                   5964: 		   {"$uname:$udom" => 
1.515     raeburn  5965: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5966: 		   $cdom,$cnum);
1.81      www      5967:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5968: 	return 'error: '.$reply;
1.652     albertel 5969:     } else {
                   5970: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5971:     }
1.297     matthew  5972:     # Add student role to user
1.83      www      5973:     my $uurl='/'.$cid;
1.81      www      5974:     $uurl=~s/\_/\//g;
                   5975:     if ($usec) {
                   5976: 	$uurl.='/'.$usec;
                   5977:     }
1.957     raeburn  5978:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      5979: }
                   5980: 
1.556     albertel 5981: sub format_name {
                   5982:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5983:     my $name;
                   5984:     if ($first ne 'lastname') {
                   5985: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5986:     } else {
                   5987: 	if ($lastname=~/\S/) {
                   5988: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5989: 	    $name=~s/\s+,/,/;
                   5990: 	} else {
                   5991: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5992: 	}
                   5993:     }
                   5994:     $name=~s/^\s+//;
                   5995:     $name=~s/\s+$//;
                   5996:     $name=~s/\s+/ /g;
                   5997:     return $name;
                   5998: }
                   5999: 
1.84      www      6000: # ------------------------------------------------- Write to course preferences
                   6001: 
                   6002: sub writecoursepref {
                   6003:     my ($courseid,%prefs)=@_;
                   6004:     $courseid=~s/^\///;
                   6005:     $courseid=~s/\_/\//g;
                   6006:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   6007:     my $chome=homeserver($cnum,$cdomain);
                   6008:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   6009: 	return 'error: no such course';
                   6010:     }
                   6011:     my $cstring='';
1.800     albertel 6012:     foreach my $pref (keys(%prefs)) {
                   6013: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 6014:     }
1.84      www      6015:     $cstring=~s/\&$//;
                   6016:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   6017: }
                   6018: 
                   6019: # ---------------------------------------------------------- Make/modify course
                   6020: 
                   6021: sub createcourse {
1.741     raeburn  6022:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   6023:         $course_owner,$crstype)=@_;
1.84      www      6024:     $url=&declutter($url);
                   6025:     my $cid='';
1.264     matthew  6026:     unless (&allowed('ccc',$udom)) {
1.84      www      6027:         return 'refused';
                   6028:     }
                   6029: # ------------------------------------------------------------------- Create ID
1.674     www      6030:    my $uname=int(1+rand(9)).
                   6031:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   6032:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      6033:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   6034: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 6035:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      6036:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6037:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   6038:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 6039:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      6040:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   6041:            return 'error: unable to generate unique course-ID';
                   6042:        } 
                   6043:    }
1.264     matthew  6044: # ------------------------------------------------ Check supplied server name
1.620     albertel 6045:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 6046:     if (! &is_library($course_server)) {
1.264     matthew  6047:         return 'error:bad server name '.$course_server;
                   6048:     }
1.84      www      6049: # ------------------------------------------------------------- Make the course
                   6050:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  6051:                       $course_server);
1.84      www      6052:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 6053:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      6054:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   6055: 	return 'error: no such course';
                   6056:     }
1.271     www      6057: # ----------------------------------------------------------------- Course made
1.516     raeburn  6058: # log existence
1.918     raeburn  6059:     my $newcourse = {
                   6060:                     $udom.'_'.$uname => {
1.921     raeburn  6061:                                      description => $description,
                   6062:                                      inst_code   => $inst_code,
                   6063:                                      owner       => $course_owner,
                   6064:                                      type        => $crstype,
1.918     raeburn  6065:                                                 },
                   6066:                     };
1.921     raeburn  6067:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      6068: # set toplevel url
1.271     www      6069:     my $topurl=$url;
                   6070:     unless ($nonstandard) {
                   6071: # ------------------------------------------ For standard courses, make top url
                   6072:         my $mapurl=&clutter($url);
1.278     www      6073:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 6074:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      6075: <map>
                   6076: <resource id="1" type="start"></resource>
                   6077: <resource id="2" src="$mapurl"></resource>
                   6078: <resource id="3" type="finish"></resource>
                   6079: <link index="1" from="1" to="2"></link>
                   6080: <link index="2" from="2" to="3"></link>
                   6081: </map>
                   6082: ENDINITMAP
                   6083:         $topurl=&declutter(
1.638     albertel 6084:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      6085:                           );
                   6086:     }
                   6087: # ----------------------------------------------------------- Write preferences
1.84      www      6088:     &writecoursepref($udom.'_'.$uname,
                   6089:                      ('description' => $description,
1.271     www      6090:                       'url'         => $topurl));
1.84      www      6091:     return '/'.$udom.'/'.$uname;
                   6092: }
                   6093: 
1.813     albertel 6094: sub is_course {
                   6095:     my ($cdom,$cnum) = @_;
                   6096:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  6097: 				undef,'.');
1.813     albertel 6098:     if (exists($courses{$cdom.'_'.$cnum})) {
                   6099:         return 1;
                   6100:     }
                   6101:     return 0;
                   6102: }
                   6103: 
1.21      www      6104: # ---------------------------------------------------------- Assign Custom Role
                   6105: 
                   6106: sub assigncustomrole {
1.957     raeburn  6107:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6108:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  6109:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      6110: }
                   6111: 
                   6112: # ----------------------------------------------------------------- Revoke Role
                   6113: 
                   6114: sub revokerole {
1.957     raeburn  6115:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6116:     my $now=time;
1.965     raeburn  6117:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      6118: }
                   6119: 
                   6120: # ---------------------------------------------------------- Revoke Custom Role
                   6121: 
                   6122: sub revokecustomrole {
1.957     raeburn  6123:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      6124:     my $now=time;
1.357     www      6125:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  6126:            $deleteflag,$selfenroll,$context);
1.17      www      6127: }
                   6128: 
1.533     banghart 6129: # ------------------------------------------------------------ Disk usage
1.535     albertel 6130: sub diskusage {
1.955     raeburn  6131:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   6132:     $directorypath =~ s/\/$//;
                   6133:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   6134:                        .&escape($getpropath).':'.&escape($uname).':'
                   6135:                        .&escape($udom),homeserver($uname,$udom));
                   6136:     if ($listing eq 'unknown_cmd') {
                   6137:         if ($getpropath) {
                   6138:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   6139:         }
                   6140:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   6141:     }
1.514     albertel 6142:     return $listing;
1.512     banghart 6143: }
                   6144: 
1.566     banghart 6145: sub is_locked {
                   6146:     my ($file_name, $domain, $user) = @_;
                   6147:     my @check;
                   6148:     my $is_locked;
                   6149:     push @check, $file_name;
1.613     albertel 6150:     my %locked = &get('file_permissions',\@check,
1.620     albertel 6151: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 6152:     my ($tmp)=keys(%locked);
                   6153:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  6154:     
1.566     banghart 6155:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  6156:         $is_locked = 'false';
                   6157:         foreach my $entry (@{$locked{$file_name}}) {
                   6158:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  6159:                $is_locked = 'true';
                   6160:                last;
1.745     raeburn  6161:            }
                   6162:        }
1.566     banghart 6163:     } else {
                   6164:         $is_locked = 'false';
                   6165:     }
                   6166: }
                   6167: 
1.759     albertel 6168: sub declutter_portfile {
                   6169:     my ($file) = @_;
1.833     albertel 6170:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 6171:     return $file;
                   6172: }
                   6173: 
1.559     banghart 6174: # ------------------------------------------------------------- Mark as Read Only
                   6175: 
                   6176: sub mark_as_readonly {
                   6177:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 6178:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6179:     my ($tmp)=keys(%current_permissions);
                   6180:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 6181:     foreach my $file (@{$files}) {
1.759     albertel 6182: 	$file = &declutter_portfile($file);
1.561     banghart 6183:         push(@{$current_permissions{$file}},$what);
1.559     banghart 6184:     }
1.613     albertel 6185:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6186:     return;
                   6187: }
                   6188: 
1.572     banghart 6189: # ------------------------------------------------------------Save Selected Files
                   6190: 
                   6191: sub save_selected_files {
                   6192:     my ($user, $path, @files) = @_;
                   6193:     my $filename = $user."savedfiles";
1.573     banghart 6194:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 6195:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 6196:     foreach my $file (@files) {
1.620     albertel 6197:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 6198:     }
                   6199:     foreach my $file (@other_files) {
1.574     banghart 6200:         print (OUT $file."\n");
1.572     banghart 6201:     }
1.574     banghart 6202:     close (OUT);
1.572     banghart 6203:     return 'ok';
                   6204: }
                   6205: 
1.574     banghart 6206: sub clear_selected_files {
                   6207:     my ($user) = @_;
                   6208:     my $filename = $user."savedfiles";
                   6209:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6210:     print (OUT undef);
                   6211:     close (OUT);
                   6212:     return ("ok");    
                   6213: }
                   6214: 
1.572     banghart 6215: sub files_in_path {
                   6216:     my ($user, $path) = @_;
                   6217:     my $filename = $user."savedfiles";
                   6218:     my %return_files;
1.574     banghart 6219:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 6220:     while (my $line_in = <IN>) {
1.574     banghart 6221:         chomp ($line_in);
                   6222:         my @paths_and_file = split (m!/!, $line_in);
                   6223:         my $file_part = pop (@paths_and_file);
                   6224:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 6225:         $path_part.='/';
                   6226:         my $path_and_file = $path_part.$file_part;
                   6227:         if ($path_part eq $path) {
                   6228:             $return_files{$file_part}= 'selected';
                   6229:         }
                   6230:     }
1.574     banghart 6231:     close (IN);
                   6232:     return (\%return_files);
1.572     banghart 6233: }
                   6234: 
                   6235: # called in portfolio select mode, to show files selected NOT in current directory
                   6236: sub files_not_in_path {
                   6237:     my ($user, $path) = @_;
                   6238:     my $filename = $user."savedfiles";
                   6239:     my @return_files;
                   6240:     my $path_part;
1.800     albertel 6241:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   6242:     while (my $line = <IN>) {
1.572     banghart 6243:         #ok, I know it's clunky, but I want it to work
1.800     albertel 6244:         my @paths_and_file = split(m|/|, $line);
                   6245:         my $file_part = pop(@paths_and_file);
                   6246:         chomp($file_part);
                   6247:         my $path_part = join('/', @paths_and_file);
1.572     banghart 6248:         $path_part .= '/';
                   6249:         my $path_and_file = $path_part.$file_part;
                   6250:         if ($path_part ne $path) {
1.800     albertel 6251:             push(@return_files, ($path_and_file));
1.572     banghart 6252:         }
                   6253:     }
1.800     albertel 6254:     close(OUT);
1.574     banghart 6255:     return (@return_files);
1.572     banghart 6256: }
                   6257: 
1.745     raeburn  6258: #----------------------------------------------Get portfolio file permissions
1.629     banghart 6259: 
1.745     raeburn  6260: sub get_portfile_permissions {
                   6261:     my ($domain,$user) = @_;
1.613     albertel 6262:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 6263:     my ($tmp)=keys(%current_permissions);
                   6264:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6265:     return \%current_permissions;
                   6266: }
                   6267: 
                   6268: #---------------------------------------------Get portfolio file access controls
                   6269: 
1.749     raeburn  6270: sub get_access_controls {
1.745     raeburn  6271:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 6272:     my %access;
                   6273:     my $real_file = $file;
                   6274:     $file =~ s/\.meta$//;
1.745     raeburn  6275:     if (defined($file)) {
1.749     raeburn  6276:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   6277:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 6278:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  6279:             }
                   6280:         }
1.745     raeburn  6281:     } else {
1.749     raeburn  6282:         foreach my $key (keys(%{$current_permissions})) {
                   6283:             if ($key =~ /\0accesscontrol$/) {
                   6284:                 if (defined($group)) {
                   6285:                     if ($key !~ m-^\Q$group\E/-) {
                   6286:                         next;
                   6287:                     }
                   6288:                 }
                   6289:                 my ($fullpath) = split(/\0/,$key);
                   6290:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   6291:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   6292:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   6293:                     }
                   6294:                 }
                   6295:             }
                   6296:         }
                   6297:     }
                   6298:     return %access;
                   6299: }
                   6300: 
                   6301: sub modify_access_controls {
                   6302:     my ($file_name,$changes,$domain,$user)=@_;
                   6303:     my ($outcome,$deloutcome);
                   6304:     my %store_permissions;
                   6305:     my %new_values;
                   6306:     my %new_control;
                   6307:     my %translation;
                   6308:     my @deletions = ();
                   6309:     my $now = time;
                   6310:     if (exists($$changes{'activate'})) {
                   6311:         if (ref($$changes{'activate'}) eq 'HASH') {
                   6312:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   6313:             my $numnew = scalar(@newitems);
                   6314:             for (my $i=0; $i<$numnew; $i++) {
                   6315:                 my $newkey = $newitems[$i];
                   6316:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  6317:                 if ($newkey =~ /^\d+:/) { 
                   6318:                     $newkey =~ s/^(\d+)/$newid/;
                   6319:                     $translation{$1} = $newid;
                   6320:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   6321:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   6322:                     $translation{$1} = $newid;
                   6323:                 }
1.749     raeburn  6324:                 $new_values{$file_name."\0".$newkey} = 
                   6325:                                           $$changes{'activate'}{$newitems[$i]};
                   6326:                 $new_control{$newkey} = $now;
                   6327:             }
                   6328:         }
                   6329:     }
                   6330:     my %todelete;
                   6331:     my %changed_items;
                   6332:     foreach my $action ('delete','update') {
                   6333:         if (exists($$changes{$action})) {
                   6334:             if (ref($$changes{$action}) eq 'HASH') {
                   6335:                 foreach my $key (keys(%{$$changes{$action}})) {
                   6336:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   6337:                     if ($action eq 'delete') { 
                   6338:                         $todelete{$itemnum} = 1;
                   6339:                     } else {
                   6340:                         $changed_items{$itemnum} = $key;
                   6341:                     }
                   6342:                 }
1.745     raeburn  6343:             }
                   6344:         }
1.749     raeburn  6345:     }
                   6346:     # get lock on access controls for file.
                   6347:     my $lockhash = {
                   6348:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   6349:                                                        ':'.$env{'user.domain'},
                   6350:                    }; 
                   6351:     my $tries = 0;
                   6352:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6353:    
                   6354:     while (($gotlock ne 'ok') && $tries <3) {
                   6355:         $tries ++;
                   6356:         sleep 1;
                   6357:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   6358:     }
                   6359:     if ($gotlock eq 'ok') {
                   6360:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   6361:         my ($tmp)=keys(%curr_permissions);
                   6362:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   6363:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   6364:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   6365:             if (ref($curr_controls) eq 'HASH') {
                   6366:                 foreach my $control_item (keys(%{$curr_controls})) {
                   6367:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   6368:                     if (defined($todelete{$itemnum})) {
                   6369:                         push(@deletions,$file_name."\0".$control_item);
                   6370:                     } else {
                   6371:                         if (defined($changed_items{$itemnum})) {
                   6372:                             $new_control{$changed_items{$itemnum}} = $now;
                   6373:                             push(@deletions,$file_name."\0".$control_item);
                   6374:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   6375:                         } else {
                   6376:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   6377:                         }
                   6378:                     }
1.745     raeburn  6379:                 }
                   6380:             }
                   6381:         }
1.970     raeburn  6382:         my ($group);
                   6383:         if (&is_course($domain,$user)) {
                   6384:             ($group,my $file) = split(/\//,$file_name,2);
                   6385:         }
1.749     raeburn  6386:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6387:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6388:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6389:         #  remove lock
                   6390:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6391:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6392:         my $sqlresult =
1.970     raeburn  6393:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  6394:                                     $group);
1.749     raeburn  6395:     } else {
                   6396:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6397:     }
1.749     raeburn  6398:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6399: }
                   6400: 
1.827     raeburn  6401: sub make_public_indefinitely {
                   6402:     my ($requrl) = @_;
                   6403:     my $now = time;
                   6404:     my $action = 'activate';
                   6405:     my $aclnum = 0;
                   6406:     if (&is_portfolio_url($requrl)) {
                   6407:         my (undef,$udom,$unum,$file_name,$group) =
                   6408:             &parse_portfolio_url($requrl);
                   6409:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6410:         my %access_controls = &get_access_controls($current_perms,
                   6411:                                                    $group,$file_name);
                   6412:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6413:             my ($num,$scope,$end,$start) = 
                   6414:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6415:             if ($scope eq 'public') {
                   6416:                 if ($start <= $now && $end == 0) {
                   6417:                     $action = 'none';
                   6418:                 } else {
                   6419:                     $action = 'update';
                   6420:                     $aclnum = $num;
                   6421:                 }
                   6422:                 last;
                   6423:             }
                   6424:         }
                   6425:         if ($action eq 'none') {
                   6426:              return 'ok';
                   6427:         } else {
                   6428:             my %changes;
                   6429:             my $newend = 0;
                   6430:             my $newstart = $now;
                   6431:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6432:             $changes{$action}{$newkey} = {
                   6433:                 type => 'public',
                   6434:                 time => {
                   6435:                     start => $newstart,
                   6436:                     end   => $newend,
                   6437:                 },
                   6438:             };
                   6439:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6440:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6441:             return $outcome;
                   6442:         }
                   6443:     } else {
                   6444:         return 'invalid';
                   6445:     }
                   6446: }
                   6447: 
1.745     raeburn  6448: #------------------------------------------------------Get Marked as Read Only
                   6449: 
                   6450: sub get_marked_as_readonly {
                   6451:     my ($domain,$user,$what,$group) = @_;
                   6452:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6453:     my @readonly_files;
1.629     banghart 6454:     my $cmp1=$what;
                   6455:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6456:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6457:         if (defined($group)) {
                   6458:             if ($file_name !~ m-^\Q$group\E/-) {
                   6459:                 next;
                   6460:             }
                   6461:         }
1.561     banghart 6462:         if (ref($value) eq "ARRAY"){
                   6463:             foreach my $stored_what (@{$value}) {
1.629     banghart 6464:                 my $cmp2=$stored_what;
1.759     albertel 6465:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6466:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6467:                 }
1.629     banghart 6468:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6469:                     push(@readonly_files, $file_name);
1.745     raeburn  6470:                     last;
1.563     banghart 6471:                 } elsif (!defined($what)) {
                   6472:                     push(@readonly_files, $file_name);
1.745     raeburn  6473:                     last;
1.561     banghart 6474:                 }
                   6475:             }
1.745     raeburn  6476:         }
1.561     banghart 6477:     }
                   6478:     return @readonly_files;
                   6479: }
1.577     banghart 6480: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6481: 
1.577     banghart 6482: sub get_marked_as_readonly_hash {
1.745     raeburn  6483:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6484:     my %readonly_files;
1.745     raeburn  6485:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6486:         if (defined($group)) {
                   6487:             if ($file_name !~ m-^\Q$group\E/-) {
                   6488:                 next;
                   6489:             }
                   6490:         }
1.577     banghart 6491:         if (ref($value) eq "ARRAY"){
                   6492:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6493:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6494:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6495:                         if ($lock_descriptor eq 'graded') {
                   6496:                             $readonly_files{$file_name} = 'graded';
                   6497:                         } elsif ($lock_descriptor eq 'handback') {
                   6498:                             $readonly_files{$file_name} = 'handback';
                   6499:                         } else {
                   6500:                             if (!exists($readonly_files{$file_name})) {
                   6501:                                 $readonly_files{$file_name} = 'locked';
                   6502:                             }
                   6503:                         }
1.745     raeburn  6504:                     }
1.750     banghart 6505:                 } 
1.577     banghart 6506:             }
                   6507:         } 
                   6508:     }
                   6509:     return %readonly_files;
                   6510: }
1.559     banghart 6511: # ------------------------------------------------------------ Unmark as Read Only
                   6512: 
                   6513: sub unmark_as_readonly {
1.629     banghart 6514:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6515:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6516:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6517:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6518:     my $symb_crs = $what;
                   6519:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6520:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6521:     my ($tmp)=keys(%current_permissions);
                   6522:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6523:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6524:     foreach my $file (@readonly_files) {
1.759     albertel 6525: 	my $clean_file = &declutter_portfile($file);
                   6526: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6527: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6528:         my @new_locks;
                   6529:         my @del_keys;
                   6530:         if (ref($current_locks) eq "ARRAY"){
                   6531:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6532:                 my $compare=$locker;
1.749     raeburn  6533:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6534:                     $compare=join('',@{$locker});
1.746     raeburn  6535:                     if ($compare ne $symb_crs) {
                   6536:                         push(@new_locks, $locker);
                   6537:                     }
1.563     banghart 6538:                 }
                   6539:             }
1.650     albertel 6540:             if (scalar(@new_locks) > 0) {
1.563     banghart 6541:                 $current_permissions{$file} = \@new_locks;
                   6542:             } else {
                   6543:                 push(@del_keys, $file);
1.613     albertel 6544:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6545:                 delete($current_permissions{$file});
1.563     banghart 6546:             }
                   6547:         }
1.561     banghart 6548:     }
1.613     albertel 6549:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6550:     return;
                   6551: }
1.512     banghart 6552: 
1.17      www      6553: # ------------------------------------------------------------ Directory lister
                   6554: 
                   6555: sub dirlist {
1.955     raeburn  6556:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      6557:     $uri=~s/^\///;
                   6558:     $uri=~s/\/$//;
1.253     stredwic 6559:     my ($udom, $uname);
1.955     raeburn  6560:     if ($getuserdir) {
1.253     stredwic 6561:         $udom = $userdomain;
                   6562:         $uname = $username;
1.955     raeburn  6563:     } else {
                   6564:         (undef,$udom,$uname)=split(/\//,$uri);
                   6565:         if(defined($userdomain)) {
                   6566:             $udom = $userdomain;
                   6567:         }
                   6568:         if(defined($username)) {
                   6569:             $uname = $username;
                   6570:         }
1.253     stredwic 6571:     }
1.955     raeburn  6572:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 6573: 
1.955     raeburn  6574:     $dirRoot = $perlvar{'lonDocRoot'};
                   6575:     if (defined($getpropath)) {
                   6576:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 6577:         $dirRoot =~ s/\/$//;
1.955     raeburn  6578:     } elsif (defined($getuserdir)) {
                   6579:         my $subdir=$uname.'__';
                   6580:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6581:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   6582:                    ."/$udom/$subdir/$uname";
                   6583:     } elsif (defined($alternateRoot)) {
                   6584:         $dirRoot = $alternateRoot;
1.751     banghart 6585:     }
1.253     stredwic 6586: 
                   6587:     if($udom) {
                   6588:         if($uname) {
1.955     raeburn  6589:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  6590:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  6591:                               .':'.&escape($uname).':'.&escape($udom),
                   6592:                               &homeserver($uname,$udom));
                   6593:             if ($listing eq 'unknown_cmd') {
                   6594:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6595:                                   &homeserver($uname,$udom));
                   6596:             } else {
                   6597:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6598:             }
1.605     matthew  6599:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6600:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6601: 				  &homeserver($uname,$udom));
1.605     matthew  6602:                 @listing_results = split(/:/,$listing);
                   6603:             } else {
                   6604:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6605:             }
                   6606:             return @listing_results;
1.955     raeburn  6607:         } elsif(!$alternateRoot) {
1.800     albertel 6608:             my %allusers;
1.841     albertel 6609: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  6610:  	    foreach my $tryserver (keys(%servers)) {
                   6611:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   6612:                                   &escape($udom),$tryserver);
                   6613:                 if ($listing eq 'unknown_cmd') {
                   6614: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6615: 				      $udom, $tryserver);
                   6616:                 } else {
                   6617:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6618:                 }
1.841     albertel 6619: 		if ($listing eq 'unknown_cmd') {
                   6620: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6621: 				      $udom, $tryserver);
                   6622: 		    @listing_results = split(/:/,$listing);
                   6623: 		} else {
                   6624: 		    @listing_results =
                   6625: 			map { &unescape($_); } split(/:/,$listing);
                   6626: 		}
                   6627: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6628: 		    $listing_results[0] ne 'empty'       &&
                   6629: 		    $listing_results[0] ne 'con_lost') {
                   6630: 		    foreach my $line (@listing_results) {
                   6631: 			my ($entry) = split(/&/,$line,2);
                   6632: 			$allusers{$entry} = 1;
                   6633: 		    }
                   6634: 		}
1.253     stredwic 6635:             }
                   6636:             my $alluserstr='';
1.800     albertel 6637:             foreach my $user (sort(keys(%allusers))) {
                   6638:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6639:             }
                   6640:             $alluserstr=~s/:$//;
                   6641:             return split(/:/,$alluserstr);
                   6642:         } else {
1.800     albertel 6643:             return ('missing user name');
1.253     stredwic 6644:         }
1.955     raeburn  6645:     } elsif(!defined($getpropath)) {
1.841     albertel 6646:         my @all_domains = sort(&all_domains());
1.955     raeburn  6647:         foreach my $domain (@all_domains) {
                   6648:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6649:         }
                   6650:         return @all_domains;
                   6651:     } else {
1.800     albertel 6652:         return ('missing domain');
1.275     stredwic 6653:     }
                   6654: }
                   6655: 
                   6656: # --------------------------------------------- GetFileTimestamp
                   6657: # This function utilizes dirlist and returns the date stamp for
                   6658: # when it was last modified.  It will also return an error of -1
                   6659: # if an error occurs
                   6660: 
                   6661: sub GetFileTimestamp {
1.955     raeburn  6662:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 6663:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6664:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  6665:     my ($fileStat) = 
                   6666:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   6667:                                  undef,$getuserdir);
1.275     stredwic 6668:     my @stats = split('&', $fileStat);
                   6669:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6670:         # @stats contains first the filename, then the stat output
                   6671:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6672:     } else {
                   6673:         return -1;
1.253     stredwic 6674:     }
1.26      www      6675: }
                   6676: 
1.712     albertel 6677: sub stat_file {
                   6678:     my ($uri) = @_;
1.787     albertel 6679:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6680: 
1.955     raeburn  6681:     my ($udom,$uname,$file);
1.712     albertel 6682:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6683: 	($udom,$uname,$file) =
1.811     albertel 6684: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6685: 	$file = 'userfiles/'.$file;
                   6686:     }
                   6687:     if ($uri =~ m-^/res/-) {
                   6688: 	($udom,$uname) = 
1.807     albertel 6689: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6690: 	$file = $uri;
                   6691:     }
                   6692: 
                   6693:     if (!$udom || !$uname || !$file) {
                   6694: 	# unable to handle the uri
                   6695: 	return ();
                   6696:     }
1.956     raeburn  6697:     my $getpropath;
                   6698:     if ($file =~ /^userfiles\//) {
                   6699:         $getpropath = 1;
                   6700:     }
1.955     raeburn  6701:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 6702:     my @stats = split('&', $result);
1.721     banghart 6703:     
1.712     albertel 6704:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6705: 	shift(@stats); #filename is first
                   6706: 	return @stats;
                   6707:     }
                   6708:     return ();
                   6709: }
                   6710: 
1.26      www      6711: # -------------------------------------------------------- Value of a Condition
                   6712: 
1.713     albertel 6713: # gets the value of a specific preevaluated condition
                   6714: #    stored in the string  $env{user.state.<cid>}
                   6715: # or looks up a condition reference in the bighash and if if hasn't
                   6716: # already been evaluated recurses into docondval to get the value of
                   6717: # the condition, then memoizing it to 
                   6718: #   $env{user.state.<cid>.<condition>}
1.40      www      6719: sub directcondval {
                   6720:     my $number=shift;
1.620     albertel 6721:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6722: 	&Apache::lonuserstate::evalstate();
                   6723:     }
1.713     albertel 6724:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6725: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6726:     } elsif ($number =~ /^_/) {
                   6727: 	my $sub_condition;
                   6728: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6729: 		&GDBM_READER(),0640)) {
                   6730: 	    $sub_condition=$bighash{'conditions'.$number};
                   6731: 	    untie(%bighash);
                   6732: 	}
                   6733: 	my $value = &docondval($sub_condition);
1.949     raeburn  6734: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 6735: 	return $value;
                   6736:     }
1.620     albertel 6737:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6738:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6739:     } else {
                   6740:        return 2;
                   6741:     }
                   6742: }
                   6743: 
1.713     albertel 6744: # get the collection of conditions for this resource
1.26      www      6745: sub condval {
                   6746:     my $condidx=shift;
1.54      www      6747:     my $allpathcond='';
1.713     albertel 6748:     foreach my $cond (split(/\|/,$condidx)) {
                   6749: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6750: 	    $allpathcond.=
                   6751: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6752: 	}
1.191     harris41 6753:     }
1.54      www      6754:     $allpathcond=~s/\|$//;
1.713     albertel 6755:     return &docondval($allpathcond);
                   6756: }
                   6757: 
                   6758: #evaluates an expression of conditions
                   6759: sub docondval {
                   6760:     my ($allpathcond) = @_;
                   6761:     my $result=0;
                   6762:     if ($env{'request.course.id'}
                   6763: 	&& defined($allpathcond)) {
                   6764: 	my $operand='|';
                   6765: 	my @stack;
                   6766: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6767: 	    if ($chunk eq '(') {
                   6768: 		push @stack,($operand,$result);
                   6769: 	    } elsif ($chunk eq ')') {
                   6770: 		my $before=pop @stack;
                   6771: 		if (pop @stack eq '&') {
                   6772: 		    $result=$result>$before?$before:$result;
                   6773: 		} else {
                   6774: 		    $result=$result>$before?$result:$before;
                   6775: 		}
                   6776: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6777: 		$operand=$chunk;
                   6778: 	    } else {
                   6779: 		my $new=directcondval($chunk);
                   6780: 		if ($operand eq '&') {
                   6781: 		    $result=$result>$new?$new:$result;
                   6782: 		} else {
                   6783: 		    $result=$result>$new?$result:$new;
                   6784: 		}
                   6785: 	    }
                   6786: 	}
1.26      www      6787:     }
                   6788:     return $result;
1.421     albertel 6789: }
                   6790: 
                   6791: # ---------------------------------------------------- Devalidate courseresdata
                   6792: 
                   6793: sub devalidatecourseresdata {
                   6794:     my ($coursenum,$coursedomain)=@_;
                   6795:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6796:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6797: }
                   6798: 
1.763     www      6799: 
1.200     www      6800: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6801: #
                   6802: #  Parameters:
                   6803: #      $coursenum    - Number of the course.
                   6804: #      $coursedomain - Domain at which the course was created.
                   6805: #  Returns:
                   6806: #     A hash of the course parameters along (I think) with timestamps
                   6807: #     and version info.
1.877     foxr     6808: 
1.624     albertel 6809: sub get_courseresdata {
                   6810:     my ($coursenum,$coursedomain)=@_;
1.200     www      6811:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6812:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6813:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6814:     my %dumpreply;
1.417     albertel 6815:     unless (defined($cached)) {
1.624     albertel 6816: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6817: 	$result=\%dumpreply;
1.251     albertel 6818: 	my ($tmp) = keys(%dumpreply);
                   6819: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6820: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6821: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6822: 	    return $tmp;
1.416     albertel 6823: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6824: 	    $result=undef;
1.599     albertel 6825: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6826: 	}
                   6827:     }
1.624     albertel 6828:     return $result;
                   6829: }
                   6830: 
1.633     albertel 6831: sub devalidateuserresdata {
                   6832:     my ($uname,$udom)=@_;
                   6833:     my $hashid="$udom:$uname";
                   6834:     &devalidate_cache_new('userres',$hashid);
                   6835: }
                   6836: 
1.624     albertel 6837: sub get_userresdata {
                   6838:     my ($uname,$udom)=@_;
                   6839:     #most student don\'t have any data set, check if there is some data
                   6840:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6841: 
                   6842:     my $hashid="$udom:$uname";
                   6843:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6844:     if (!defined($cached)) {
                   6845: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6846: 	$result=\%resourcedata;
                   6847: 	&do_cache_new('userres',$hashid,$result,600);
                   6848:     }
                   6849:     my ($tmp)=keys(%$result);
                   6850:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6851: 	return $result;
                   6852:     }
                   6853:     #error 2 occurs when the .db doesn't exist
                   6854:     if ($tmp!~/error: 2 /) {
1.672     albertel 6855: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6856: 		 " Trying to get resource data for ".
                   6857: 		 $uname." at ".$udom.": ".
                   6858: 		 $tmp."</font>");
                   6859:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6860: 	#&EXT_cache_set($udom,$uname);
                   6861: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6862: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6863:     }
                   6864:     return $tmp;
                   6865: }
1.879     foxr     6866: #----------------------------------------------- resdata - return resource data
                   6867: #  Purpose:
                   6868: #    Return resource data for either users or for a course.
                   6869: #  Parameters:
                   6870: #     $name      - Course/user name.
                   6871: #     $domain    - Name of the domain the user/course is registered on.
                   6872: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6873: #     @which     - Array of names of resources desired.
                   6874: #  Returns:
                   6875: #     The value of the first reasource in @which that is found in the
                   6876: #     resource hash.
                   6877: #  Exceptional Conditions:
                   6878: #     If the $type passed in is not valid (not the string 'course' or 
                   6879: #     'user', an undefined  reference is returned.
                   6880: #     If none of the resources are found, an undef is returned
1.624     albertel 6881: sub resdata {
                   6882:     my ($name,$domain,$type,@which)=@_;
                   6883:     my $result;
                   6884:     if ($type eq 'course') {
                   6885: 	$result=&get_courseresdata($name,$domain);
                   6886:     } elsif ($type eq 'user') {
                   6887: 	$result=&get_userresdata($name,$domain);
                   6888:     }
                   6889:     if (!ref($result)) { return $result; }    
1.251     albertel 6890:     foreach my $item (@which) {
1.927     albertel 6891: 	if (defined($result->{$item->[0]})) {
                   6892: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 6893: 	}
1.250     albertel 6894:     }
1.291     albertel 6895:     return undef;
1.200     www      6896: }
                   6897: 
1.379     matthew  6898: #
                   6899: # EXT resource caching routines
                   6900: #
                   6901: 
                   6902: sub clear_EXT_cache_status {
1.383     albertel 6903:     &delenv('cache.EXT.');
1.379     matthew  6904: }
                   6905: 
                   6906: sub EXT_cache_status {
                   6907:     my ($target_domain,$target_user) = @_;
1.383     albertel 6908:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6909:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6910:         # We know already the user has no data
                   6911:         return 1;
                   6912:     } else {
                   6913:         return 0;
                   6914:     }
                   6915: }
                   6916: 
                   6917: sub EXT_cache_set {
                   6918:     my ($target_domain,$target_user) = @_;
1.383     albertel 6919:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  6920:     #&appenv({$cachename => time});
1.379     matthew  6921: }
                   6922: 
1.28      www      6923: # --------------------------------------------------------- Value of a Variable
1.58      www      6924: sub EXT {
1.715     albertel 6925: 
1.395     albertel 6926:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6927:     unless ($varname) { return ''; }
1.218     albertel 6928:     #get real user name/domain, courseid and symb
                   6929:     my $courseid;
1.359     albertel 6930:     my $publicuser;
1.427     www      6931:     if ($symbparm) {
                   6932: 	$symbparm=&get_symb_from_alias($symbparm);
                   6933:     }
1.218     albertel 6934:     if (!($uname && $udom)) {
1.790     albertel 6935:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6936:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6937:     } else {
1.620     albertel 6938: 	$courseid=$env{'request.course.id'};
1.218     albertel 6939:     }
1.48      www      6940:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6941:     my $rest;
1.320     albertel 6942:     if (defined($therest[0])) {
1.48      www      6943:        $rest=join('.',@therest);
                   6944:     } else {
                   6945:        $rest='';
                   6946:     }
1.320     albertel 6947: 
1.57      www      6948:     my $qualifierrest=$qualifier;
                   6949:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6950:     my $spacequalifierrest=$space;
                   6951:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6952:     if ($realm eq 'user') {
1.48      www      6953: # --------------------------------------------------------------- user.resource
                   6954: 	if ($space eq 'resource') {
1.651     albertel 6955: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6956: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6957: 		 &&
1.744     albertel 6958: 		 ($symbparm eq &symbread()) ) {	
                   6959: 		# if we are in the middle of processing the resource the
                   6960: 		# get the value we are planning on committing
                   6961:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6962:                     return $Apache::lonhomework::results{$qualifierrest};
                   6963:                 } else {
                   6964:                     return $Apache::lonhomework::history{$qualifierrest};
                   6965:                 }
1.335     albertel 6966: 	    } else {
1.359     albertel 6967: 		my %restored;
1.620     albertel 6968: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6969: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6970: 		} else {
                   6971: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6972: 		}
1.335     albertel 6973: 		return $restored{$qualifierrest};
                   6974: 	    }
1.48      www      6975: # ----------------------------------------------------------------- user.access
                   6976:         } elsif ($space eq 'access') {
1.218     albertel 6977: 	    # FIXME - not supporting calls for a specific user
1.48      www      6978:             return &allowed($qualifier,$rest);
                   6979: # ------------------------------------------ user.preferences, user.environment
                   6980:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6981: 	    if (($uname eq $env{'user.name'}) &&
                   6982: 		($udom eq $env{'user.domain'})) {
                   6983: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6984: 	    } else {
1.359     albertel 6985: 		my %returnhash;
                   6986: 		if (!$publicuser) {
                   6987: 		    %returnhash=&userenvironment($udom,$uname,
                   6988: 						 $qualifierrest);
                   6989: 		}
1.218     albertel 6990: 		return $returnhash{$qualifierrest};
                   6991: 	    }
1.48      www      6992: # ----------------------------------------------------------------- user.course
                   6993:         } elsif ($space eq 'course') {
1.218     albertel 6994: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6995:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6996: # ------------------------------------------------------------------- user.role
                   6997:         } elsif ($space eq 'role') {
1.218     albertel 6998: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6999:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      7000:             if ($qualifier eq 'value') {
                   7001: 		return $role;
                   7002:             } elsif ($qualifier eq 'extent') {
                   7003:                 return $where;
                   7004:             }
                   7005: # ----------------------------------------------------------------- user.domain
                   7006:         } elsif ($space eq 'domain') {
1.218     albertel 7007:             return $udom;
1.48      www      7008: # ------------------------------------------------------------------- user.name
                   7009:         } elsif ($space eq 'name') {
1.218     albertel 7010:             return $uname;
1.48      www      7011: # ---------------------------------------------------- Any other user namespace
1.29      www      7012:         } else {
1.359     albertel 7013: 	    my %reply;
                   7014: 	    if (!$publicuser) {
                   7015: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   7016: 	    }
                   7017: 	    return $reply{$qualifierrest};
1.48      www      7018:         }
1.236     www      7019:     } elsif ($realm eq 'query') {
                   7020: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 7021:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   7022: 						[$spacequalifierrest]);
1.620     albertel 7023: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      7024:    } elsif ($realm eq 'request') {
1.48      www      7025: # ------------------------------------------------------------- request.browser
                   7026:         if ($space eq 'browser') {
1.430     www      7027: 	    if ($qualifier eq 'textremote') {
1.676     albertel 7028: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      7029: 		    return 1;
                   7030: 		} else {
                   7031: 		    return 0;
                   7032: 		}
                   7033: 	    } else {
1.620     albertel 7034: 		return $env{'browser.'.$qualifier};
1.430     www      7035: 	    }
1.57      www      7036: # ------------------------------------------------------------ request.filename
                   7037:         } else {
1.620     albertel 7038:             return $env{'request.'.$spacequalifierrest};
1.29      www      7039:         }
1.28      www      7040:     } elsif ($realm eq 'course') {
1.48      www      7041: # ---------------------------------------------------------- course.description
1.620     albertel 7042:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      7043:     } elsif ($realm eq 'resource') {
1.165     www      7044: 
1.620     albertel 7045: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 7046: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   7047: 	}
1.693     albertel 7048: 
                   7049: 	if ($space eq 'title') {
                   7050: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   7051: 	    return &gettitle($symbparm);
                   7052: 	}
                   7053: 	
                   7054: 	if ($space eq 'map') {
                   7055: 	    my ($map) = &decode_symb($symbparm);
                   7056: 	    return &symbread($map);
                   7057: 	}
1.905     albertel 7058: 	if ($space eq 'filename') {
                   7059: 	    if ($symbparm) {
                   7060: 		return &clutter((&decode_symb($symbparm))[2]);
                   7061: 	    }
                   7062: 	    return &hreflocation('',$env{'request.filename'});
                   7063: 	}
1.693     albertel 7064: 
                   7065: 	my ($section, $group, @groups);
1.593     albertel 7066: 	my ($courselevelm,$courselevel);
1.539     albertel 7067: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7068: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      7069: 
1.218     albertel 7070: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      7071: 
1.60      www      7072: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 7073: 	    my $symbp=$symbparm;
1.735     albertel 7074: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 7075: 
                   7076: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   7077: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   7078: 
1.620     albertel 7079: 	    if (($env{'user.name'} eq $uname) &&
                   7080: 		($env{'user.domain'} eq $udom)) {
                   7081: 		$section=$env{'request.course.sec'};
1.733     raeburn  7082:                 @groups = split(/:/,$env{'request.course.groups'});  
                   7083:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 7084: 	    } else {
1.539     albertel 7085: 		if (! defined($usection)) {
1.551     albertel 7086: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 7087: 		} else {
                   7088: 		    $section = $usection;
                   7089: 		}
1.733     raeburn  7090:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 7091: 	    }
                   7092: 
                   7093: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   7094: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   7095: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   7096: 
1.593     albertel 7097: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 7098: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 7099: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      7100: 
1.60      www      7101: # ----------------------------------------------------------- first, check user
1.624     albertel 7102: 
                   7103: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 7104: 				       ([$courselevelr,'resource'],
                   7105: 					[$courselevelm,'map'     ],
                   7106: 					[$courselevel, 'course'  ]));
1.931     albertel 7107: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      7108: 
1.594     albertel 7109: # ------------------------------------------------ second, check some of course
1.684     raeburn  7110:             my $coursereply;
1.691     raeburn  7111:             if (@groups > 0) {
                   7112:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   7113:                                        $mapparm,$spacequalifierrest);
1.927     albertel 7114:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  7115:             }
1.96      www      7116: 
1.684     raeburn  7117: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 7118: 				  $env{'course.'.$courseid.'.domain'},
                   7119: 				  'course',
                   7120: 				  ([$seclevelr,   'resource'],
                   7121: 				   [$seclevelm,   'map'     ],
                   7122: 				   [$seclevel,    'course'  ],
                   7123: 				   [$courselevelr,'resource']));
                   7124: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      7125: 
1.60      www      7126: # ------------------------------------------------------ third, check map parms
1.218     albertel 7127: 	    my %parmhash=();
                   7128: 	    my $thisparm='';
                   7129: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 7130: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 7131: 		    &GDBM_READER(),0640)) {
1.218     albertel 7132: 		$thisparm=$parmhash{$symbparm};
                   7133: 		untie(%parmhash);
                   7134: 	    }
1.927     albertel 7135: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 7136: 	}
1.594     albertel 7137: # ------------------------------------------ fourth, look in resource metadata
1.71      www      7138: 
1.218     albertel 7139: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 7140: 	my $filename;
                   7141: 	if (!$symbparm) { $symbparm=&symbread(); }
                   7142: 	if ($symbparm) {
1.409     www      7143: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 7144: 	} else {
1.620     albertel 7145: 	    $filename=$env{'request.filename'};
1.282     albertel 7146: 	}
                   7147: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 7148: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 7149: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 7150: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      7151: 
1.927     albertel 7152: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 7153: 	if ($symbparm && defined($courseid) && 
1.620     albertel 7154: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 7155: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   7156: 				     $env{'course.'.$courseid.'.domain'},
                   7157: 				     'course',
1.927     albertel 7158: 				     ([$courselevelm,'map'   ],
                   7159: 				      [$courselevel, 'course']));
                   7160: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 7161: 	}
1.145     www      7162: # ------------------------------------------------------------------ Cascade up
1.218     albertel 7163: 	unless ($space eq '0') {
1.336     albertel 7164: 	    my @parts=split(/_/,$space);
                   7165: 	    my $id=pop(@parts);
                   7166: 	    my $part=join('_',@parts);
                   7167: 	    if ($part eq '') { $part='0'; }
1.927     albertel 7168: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 7169: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  7170: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 7171: 	}
1.395     albertel 7172: 	if ($recurse) { return undef; }
                   7173: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 7174: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      7175: # ---------------------------------------------------- Any other user namespace
                   7176:     } elsif ($realm eq 'environment') {
                   7177: # ----------------------------------------------------------------- environment
1.620     albertel 7178: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   7179: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 7180: 	} else {
1.770     albertel 7181: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   7182: 		return '';
                   7183: 	    }
1.219     albertel 7184: 	    my %returnhash=&userenvironment($udom,$uname,
                   7185: 					    $spacequalifierrest);
                   7186: 	    return $returnhash{$spacequalifierrest};
                   7187: 	}
1.28      www      7188:     } elsif ($realm eq 'system') {
1.48      www      7189: # ----------------------------------------------------------------- system.time
                   7190: 	if ($space eq 'time') {
                   7191: 	    return time;
                   7192:         }
1.696     albertel 7193:     } elsif ($realm eq 'server') {
                   7194: # ----------------------------------------------------------------- system.time
                   7195: 	if ($space eq 'name') {
                   7196: 	    return $ENV{'SERVER_NAME'};
                   7197:         }
1.28      www      7198:     }
1.48      www      7199:     return '';
1.61      www      7200: }
                   7201: 
1.927     albertel 7202: sub get_reply {
                   7203:     my ($reply_value) = @_;
1.940     raeburn  7204:     if (ref($reply_value) eq 'ARRAY') {
                   7205:         if (wantarray) {
                   7206: 	    return @$reply_value;
                   7207:         }
                   7208:         return $reply_value->[0];
                   7209:     } else {
                   7210:         return $reply_value;
1.927     albertel 7211:     }
                   7212: }
                   7213: 
1.691     raeburn  7214: sub check_group_parms {
                   7215:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   7216:     my @groupitems = ();
                   7217:     my $resultitem;
1.927     albertel 7218:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  7219:     foreach my $group (@{$groups}) {
                   7220:         foreach my $level (@levels) {
1.927     albertel 7221:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   7222:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  7223:         }
                   7224:     }
                   7225:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   7226:                             $env{'course.'.$courseid.'.domain'},
                   7227:                                      'course',@groupitems);
                   7228:     return $coursereply;
                   7229: }
                   7230: 
                   7231: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  7232:     my ($courseid,@groups) = @_;
                   7233:     @groups = sort(@groups);
1.691     raeburn  7234:     return @groups;
                   7235: }
                   7236: 
1.395     albertel 7237: sub packages_tab_default {
                   7238:     my ($uri,$varname)=@_;
                   7239:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 7240: 
                   7241:     my (@extension,@specifics,$do_default);
                   7242:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 7243: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 7244: 	if ($pack_type eq 'default') {
                   7245: 	    $do_default=1;
                   7246: 	} elsif ($pack_type eq 'extension') {
                   7247: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 7248: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 7249: 	    # only look at packages defaults for packages that this id is
1.738     albertel 7250: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   7251: 	}
                   7252:     }
                   7253:     # first look for a package that matches the requested part id
                   7254:     foreach my $package (@specifics) {
                   7255: 	my (undef,$pack_type,$pack_part)=@{$package};
                   7256: 	next if ($pack_part ne $part);
                   7257: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7258: 	    return $packagetab{"$pack_type&$name&default"};
                   7259: 	}
                   7260:     }
                   7261:     # look for any possible matching non extension_ package
                   7262:     foreach my $package (@specifics) {
                   7263: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 7264: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7265: 	    return $packagetab{"$pack_type&$name&default"};
                   7266: 	}
1.585     albertel 7267: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 7268: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   7269: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 7270: 	}
                   7271:     }
1.738     albertel 7272:     # look for any posible extension_ match
                   7273:     foreach my $package (@extension) {
                   7274: 	my ($package,$pack_type)=@{$package};
                   7275: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   7276: 	    return $packagetab{"$pack_type&$name&default"};
                   7277: 	}
                   7278: 	if (defined($packagetab{$package."&$name&default"})) {
                   7279: 	    return $packagetab{$package."&$name&default"};
                   7280: 	}
                   7281:     }
                   7282:     # look for a global default setting
                   7283:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   7284: 	return $packagetab{"default&$name&default"};
                   7285:     }
1.395     albertel 7286:     return undef;
                   7287: }
                   7288: 
1.334     albertel 7289: sub add_prefix_and_part {
                   7290:     my ($prefix,$part)=@_;
                   7291:     my $keyroot;
                   7292:     if (defined($prefix) && $prefix !~ /^__/) {
                   7293: 	# prefix that has a part already
                   7294: 	$keyroot=$prefix;
                   7295:     } elsif (defined($prefix)) {
                   7296: 	# prefix that is missing a part
                   7297: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   7298:     } else {
                   7299: 	# no prefix at all
                   7300: 	if (defined($part)) { $keyroot='_'.$part; }
                   7301:     }
                   7302:     return $keyroot;
                   7303: }
                   7304: 
1.71      www      7305: # ---------------------------------------------------------------- Get metadata
                   7306: 
1.599     albertel 7307: my %metaentry;
1.71      www      7308: sub metadata {
1.176     www      7309:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      7310:     $uri=&declutter($uri);
1.288     albertel 7311:     # if it is a non metadata possible uri return quickly
1.529     albertel 7312:     if (($uri eq '') || 
                   7313: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 7314: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 7315:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   7316: 	return undef;
                   7317:     }
                   7318:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   7319: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 7320: 	return undef;
1.288     albertel 7321:     }
1.73      www      7322:     my $filename=$uri;
                   7323:     $uri=~s/\.meta$//;
1.172     www      7324: #
                   7325: # Is the metadata already cached?
1.177     www      7326: # Look at timestamp of caching
1.172     www      7327: # Everything is cached by the main uri, libraries are never directly cached
                   7328: #
1.428     albertel 7329:     if (!defined($liburi)) {
1.599     albertel 7330: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 7331: 	if (defined($cached)) { return $result->{':'.$what}; }
                   7332:     }
                   7333:     {
1.172     www      7334: #
                   7335: # Is this a recursive call for a library?
                   7336: #
1.599     albertel 7337: #	if (! exists($metacache{$uri})) {
                   7338: #	    $metacache{$uri}={};
                   7339: #	}
1.924     albertel 7340: 	my $cachetime = 60*60;
1.171     www      7341:         if ($liburi) {
                   7342: 	    $liburi=&declutter($liburi);
                   7343:             $filename=$liburi;
1.401     bowersj2 7344:         } else {
1.599     albertel 7345: 	    &devalidate_cache_new('meta',$uri);
                   7346: 	    undef(%metaentry);
1.401     bowersj2 7347: 	}
1.140     www      7348:         my %metathesekeys=();
1.73      www      7349:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 7350: 	my $metastring;
1.924     albertel 7351: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 7352: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 7353: 	    $metastring = 
1.929     albertel 7354: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 7355: 					  ('grade_target' => 'meta'));
                   7356: 	    $cachetime = 1; # only want this cached in the child not long term
                   7357: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 7358: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 7359: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 7360: 	    $metastring=&getfile($file);
1.489     albertel 7361: 	}
1.208     albertel 7362:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      7363:         my $token;
1.140     www      7364:         undef %metathesekeys;
1.71      www      7365:         while ($token=$parser->get_token) {
1.339     albertel 7366: 	    if ($token->[0] eq 'S') {
                   7367: 		if (defined($token->[2]->{'package'})) {
1.172     www      7368: #
                   7369: # This is a package - get package info
                   7370: #
1.339     albertel 7371: 		    my $package=$token->[2]->{'package'};
                   7372: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7373: 		    if (defined($token->[2]->{'id'})) { 
                   7374: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   7375: 		    }
1.599     albertel 7376: 		    if ($metaentry{':packages'}) {
                   7377: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 7378: 		    } else {
1.599     albertel 7379: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 7380: 		    }
1.736     albertel 7381: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 7382: 			my $part=$keyroot;
                   7383: 			$part=~s/^\_//;
1.736     albertel 7384: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   7385: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   7386: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 7387: 			    # ignore package.tab specified default values
                   7388:                             # here &package_tab_default() will fetch those
                   7389: 			    if ($subp eq 'default') { next; }
1.736     albertel 7390: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 7391: 			    my $unikey;
                   7392: 			    if ($pack =~ /_0$/) {
                   7393: 				$unikey='parameter_0_'.$name;
                   7394: 				$part=0;
                   7395: 			    } else {
                   7396: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7397: 			    }
1.339     albertel 7398: 			    if ($subp eq 'display') {
                   7399: 				$value.=' [Part: '.$part.']';
                   7400: 			    }
1.599     albertel 7401: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7402: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7403: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7404: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7405: 			    }
1.599     albertel 7406: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7407: 				$metaentry{':'.$unikey}=
                   7408: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7409: 			    }
1.339     albertel 7410: 			}
                   7411: 		    }
                   7412: 		} else {
1.172     www      7413: #
                   7414: # This is not a package - some other kind of start tag
1.339     albertel 7415: #
                   7416: 		    my $entry=$token->[1];
                   7417: 		    my $unikey;
                   7418: 		    if ($entry eq 'import') {
                   7419: 			$unikey='';
                   7420: 		    } else {
                   7421: 			$unikey=$entry;
                   7422: 		    }
                   7423: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7424: 
                   7425: 		    if (defined($token->[2]->{'id'})) { 
                   7426: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7427: 		    }
1.175     www      7428: 
1.339     albertel 7429: 		    if ($entry eq 'import') {
1.175     www      7430: #
                   7431: # Importing a library here
1.339     albertel 7432: #
                   7433: 			if ($depthcount<20) {
                   7434: 			    my $location=$parser->get_text('/import');
                   7435: 			    my $dir=$filename;
                   7436: 			    $dir=~s|[^/]*$||;
                   7437: 			    $location=&filelocation($dir,$location);
1.736     albertel 7438: 			    my $metadata = 
                   7439: 				&metadata($uri,'keys', $location,$unikey,
                   7440: 					  $depthcount+1);
                   7441: 			    foreach my $meta (split(',',$metadata)) {
                   7442: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7443: 				$metathesekeys{$meta}=1;
1.339     albertel 7444: 			    }
                   7445: 			}
                   7446: 		    } else { 
                   7447: 			
                   7448: 			if (defined($token->[2]->{'name'})) { 
                   7449: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7450: 			}
                   7451: 			$metathesekeys{$unikey}=1;
1.736     albertel 7452: 			foreach my $param (@{$token->[3]}) {
                   7453: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7454: 				$token->[2]->{$param};
1.339     albertel 7455: 			}
                   7456: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7457: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7458: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7459: 		 # only ws inside the tag, and not in default, so use default
                   7460: 		 # as value
1.599     albertel 7461: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7462: 			} elsif ( $internaltext =~ /\S/ ) {
                   7463: 		  # something interesting inside the tag
                   7464: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7465: 			} else {
1.908     albertel 7466: 		  # no interesting values, don't set a default
1.339     albertel 7467: 			}
1.172     www      7468: # end of not-a-package not-a-library import
1.339     albertel 7469: 		    }
1.172     www      7470: # end of not-a-package start tag
1.339     albertel 7471: 		}
1.172     www      7472: # the next is the end of "start tag"
1.339     albertel 7473: 	    }
                   7474: 	}
1.483     albertel 7475: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7476: 	$extension = lc($extension);
                   7477: 	if ($extension eq 'htm') { $extension='html'; }
                   7478: 
1.737     albertel 7479: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7480: 	    #no specific packages #how's our extension
                   7481: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7482: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7483: 					 \%metathesekeys);
                   7484: 	}
1.883     albertel 7485: 
                   7486: 	if (!exists($metaentry{':packages'})
                   7487: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7488: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7489: 		#no specific packages well let's get default then
                   7490: 		if ($key!~/^default&/) { next; }
1.488     albertel 7491: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7492: 					     \%metathesekeys);
                   7493: 	    }
                   7494: 	}
1.338     www      7495: # are there custom rights to evaluate
1.599     albertel 7496: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7497: 
1.338     www      7498:     #
                   7499:     # Importing a rights file here
1.339     albertel 7500:     #
                   7501: 	    unless ($depthcount) {
1.599     albertel 7502: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7503: 		my $dir=$filename;
                   7504: 		$dir=~s|[^/]*$||;
                   7505: 		$location=&filelocation($dir,$location);
1.736     albertel 7506: 		my $rights_metadata =
                   7507: 		    &metadata($uri,'keys',$location,'_rights',
                   7508: 			      $depthcount+1);
                   7509: 		foreach my $rights (split(',',$rights_metadata)) {
                   7510: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7511: 		    $metathesekeys{$rights}=1;
1.339     albertel 7512: 		}
                   7513: 	    }
                   7514: 	}
1.737     albertel 7515: 	# uniqifiy package listing
                   7516: 	my %seen;
                   7517: 	my @uniq_packages =
                   7518: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7519: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7520: 
                   7521: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7522: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7523: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7524: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7525: # this is the end of "was not already recently cached
1.71      www      7526:     }
1.599     albertel 7527:     return $metaentry{':'.$what};
1.261     albertel 7528: }
                   7529: 
1.488     albertel 7530: sub metadata_create_package_def {
1.483     albertel 7531:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7532:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7533:     if ($subp eq 'default') { next; }
                   7534:     
1.599     albertel 7535:     if (defined($metaentry{':packages'})) {
                   7536: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7537:     } else {
1.599     albertel 7538: 	$metaentry{':packages'}=$package;
1.483     albertel 7539:     }
                   7540:     my $value=$packagetab{$key};
                   7541:     my $unikey;
                   7542:     $unikey='parameter_0_'.$name;
1.599     albertel 7543:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7544:     $$metathesekeys{$unikey}=1;
1.599     albertel 7545:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7546: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7547:     }
1.599     albertel 7548:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7549: 	$metaentry{':'.$unikey}=
                   7550: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7551:     }
                   7552: }
                   7553: 
1.261     albertel 7554: sub metadata_generate_part0 {
                   7555:     my ($metadata,$metacache,$uri) = @_;
                   7556:     my %allnames;
1.737     albertel 7557:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7558: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7559: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7560: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7561: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7562: 	    $allnames{$name}=$part;
                   7563: 	  }
                   7564: 	}
                   7565:     }
                   7566:     foreach my $name (keys(%allnames)) {
                   7567:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7568:       my $key=":parameter_0_$name";
1.261     albertel 7569:       $$metacache{"$key.part"}='0';
                   7570:       $$metacache{"$key.name"}=$name;
1.428     albertel 7571:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7572: 					   $allnames{$name}.'_'.$name.
                   7573: 					   '.type'};
1.428     albertel 7574:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7575: 			     '.display'};
1.644     www      7576:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7577:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7578:       $$metacache{"$key.display"}=$olddis;
                   7579:     }
1.71      www      7580: }
                   7581: 
1.764     albertel 7582: # ------------------------------------------------------ Devalidate title cache
                   7583: 
                   7584: sub devalidate_title_cache {
                   7585:     my ($url)=@_;
                   7586:     if (!$env{'request.course.id'}) { return; }
                   7587:     my $symb=&symbread($url);
                   7588:     if (!$symb) { return; }
                   7589:     my $key=$env{'request.course.id'}."\0".$symb;
                   7590:     &devalidate_cache_new('title',$key);
                   7591: }
                   7592: 
1.301     www      7593: # ------------------------------------------------- Get the title of a resource
                   7594: 
                   7595: sub gettitle {
                   7596:     my $urlsymb=shift;
                   7597:     my $symb=&symbread($urlsymb);
1.534     albertel 7598:     if ($symb) {
1.620     albertel 7599: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7600: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7601: 	if (defined($cached)) { 
                   7602: 	    return $result;
                   7603: 	}
1.534     albertel 7604: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7605: 	my $title='';
1.907     albertel 7606: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7607: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7608: 	} else {
                   7609: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7610: 		    &GDBM_READER(),0640)) {
                   7611: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7612: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7613: 		untie(%bighash);
                   7614: 	    }
1.534     albertel 7615: 	}
                   7616: 	$title=~s/\&colon\;/\:/gs;
                   7617: 	if ($title) {
1.599     albertel 7618: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7619: 	}
                   7620: 	$urlsymb=$url;
                   7621:     }
                   7622:     my $title=&metadata($urlsymb,'title');
                   7623:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7624:     return $title;
1.301     www      7625: }
1.613     albertel 7626: 
1.614     albertel 7627: sub get_slot {
                   7628:     my ($which,$cnum,$cdom)=@_;
                   7629:     if (!$cnum || !$cdom) {
1.790     albertel 7630: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7631: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7632: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7633:     }
1.703     albertel 7634:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7635:     my %slotinfo;
                   7636:     if (exists($remembered{$key})) {
                   7637: 	$slotinfo{$which} = $remembered{$key};
                   7638:     } else {
                   7639: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7640: 	&Apache::lonhomework::showhash(%slotinfo);
                   7641: 	my ($tmp)=keys(%slotinfo);
                   7642: 	if ($tmp=~/^error:/) { return (); }
                   7643: 	$remembered{$key} = $slotinfo{$which};
                   7644:     }
1.616     albertel 7645:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7646: 	return %{$slotinfo{$which}};
                   7647:     }
                   7648:     return $slotinfo{$which};
1.614     albertel 7649: }
1.31      www      7650: # ------------------------------------------------- Update symbolic store links
                   7651: 
                   7652: sub symblist {
                   7653:     my ($mapname,%newhash)=@_;
1.438     www      7654:     $mapname=&deversion(&declutter($mapname));
1.31      www      7655:     my %hash;
1.620     albertel 7656:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7657:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7658:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7659: 	    foreach my $url (keys %newhash) {
                   7660: 		next if ($url eq 'last_known'
                   7661: 			 && $env{'form.no_update_last_known'});
                   7662: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7663: 						    $newhash{$url}->[1],
                   7664: 						    $newhash{$url}->[0]);
1.191     harris41 7665:             }
1.31      www      7666:             if (untie(%hash)) {
                   7667: 		return 'ok';
                   7668:             }
                   7669:         }
                   7670:     }
                   7671:     return 'error';
1.212     www      7672: }
                   7673: 
                   7674: # --------------------------------------------------------------- Verify a symb
                   7675: 
                   7676: sub symbverify {
1.510     www      7677:     my ($symb,$thisurl)=@_;
                   7678:     my $thisfn=$thisurl;
1.439     www      7679:     $thisfn=&declutter($thisfn);
1.215     www      7680: # direct jump to resource in page or to a sequence - will construct own symbs
                   7681:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7682: # check URL part
1.409     www      7683:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7684: 
1.431     www      7685:     unless ($url eq $thisfn) { return 0; }
1.213     www      7686: 
1.216     www      7687:     $symb=&symbclean($symb);
1.510     www      7688:     $thisurl=&deversion($thisurl);
1.439     www      7689:     $thisfn=&deversion($thisfn);
1.213     www      7690: 
                   7691:     my %bighash;
                   7692:     my $okay=0;
1.431     www      7693: 
1.620     albertel 7694:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7695:                             &GDBM_READER(),0640)) {
1.510     www      7696:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7697:         unless ($ids) { 
1.510     www      7698:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7699:         }
                   7700:         if ($ids) {
                   7701: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7702: 	    foreach my $id (split(/\,/,$ids)) {
                   7703: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7704:                if (
                   7705:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7706:    eq $symb) { 
1.620     albertel 7707: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7708: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7709: 		       $okay=1; 
                   7710: 		   }
                   7711: 	       }
1.216     www      7712: 	   }
                   7713:         }
1.213     www      7714: 	untie(%bighash);
                   7715:     }
                   7716:     return $okay;
1.31      www      7717: }
                   7718: 
1.210     www      7719: # --------------------------------------------------------------- Clean-up symb
                   7720: 
                   7721: sub symbclean {
                   7722:     my $symb=shift;
1.568     albertel 7723:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7724: # remove version from map
                   7725:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7726: 
1.210     www      7727: # remove version from URL
                   7728:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7729: 
1.507     www      7730: # remove wrapper
                   7731: 
1.510     www      7732:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7733:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7734:     return $symb;
1.409     www      7735: }
                   7736: 
                   7737: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7738: 
                   7739: sub encode_symb {
                   7740:     my ($map,$resid,$url)=@_;
                   7741:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7742: }
1.409     www      7743: 
                   7744: sub decode_symb {
1.568     albertel 7745:     my $symb=shift;
                   7746:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7747:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7748:     return (&fixversion($map),$resid,&fixversion($url));
                   7749: }
                   7750: 
                   7751: sub fixversion {
                   7752:     my $fn=shift;
1.609     banghart 7753:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7754:     my %bighash;
                   7755:     my $uri=&clutter($fn);
1.620     albertel 7756:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7757: # is this cached?
1.599     albertel 7758:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7759:     if (defined($cached)) { return $result; }
                   7760: # unfortunately not cached, or expired
1.620     albertel 7761:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7762: 	    &GDBM_READER(),0640)) {
                   7763:  	if ($bighash{'version_'.$uri}) {
                   7764:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7765:  	    unless (($version eq 'mostrecent') || 
                   7766: 		    ($version==&getversion($uri))) {
1.440     www      7767:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7768:  	    }
                   7769:  	}
                   7770:  	untie %bighash;
1.413     www      7771:     }
1.599     albertel 7772:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7773: }
                   7774: 
                   7775: sub deversion {
                   7776:     my $url=shift;
                   7777:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7778:     return $url;
1.210     www      7779: }
                   7780: 
1.31      www      7781: # ------------------------------------------------------ Return symb list entry
                   7782: 
                   7783: sub symbread {
1.249     www      7784:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7785:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7786:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7787: # no filename provided? try from environment
1.44      www      7788:     unless ($thisfn) {
1.620     albertel 7789:         if ($env{'request.symb'}) {
                   7790: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7791: 	}
1.620     albertel 7792: 	$thisfn=$env{'request.filename'};
1.44      www      7793:     }
1.569     albertel 7794:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7795: # is that filename actually a symb? Verify, clean, and return
                   7796:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7797: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7798: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7799: 	}
1.242     www      7800:     }
1.44      www      7801:     $thisfn=declutter($thisfn);
1.31      www      7802:     my %hash;
1.37      www      7803:     my %bighash;
                   7804:     my $syval='';
1.620     albertel 7805:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7806:         my $targetfn = $thisfn;
1.609     banghart 7807:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7808:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7809:         }
1.687     albertel 7810: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7811: 	    $targetfn=$1;
                   7812: 	}
1.620     albertel 7813:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7814:                       &GDBM_READER(),0640)) {
1.481     raeburn  7815: 	    $syval=$hash{$targetfn};
1.37      www      7816:             untie(%hash);
                   7817:         }
                   7818: # ---------------------------------------------------------- There was an entry
                   7819:         if ($syval) {
1.601     albertel 7820: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7821: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  7822: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7823: 		    #return $env{$cache_str}='';
1.601     albertel 7824: 		#}    
                   7825: 		#$syval.=$1;
                   7826: 	    #}
1.37      www      7827:         } else {
                   7828: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7829:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7830:                             &GDBM_READER(),0640)) {
1.37      www      7831: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7832:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7833:               unless ($ids) { 
                   7834:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7835:               }
                   7836:               unless ($ids) {
                   7837: # alias?
                   7838: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7839:               }
1.37      www      7840:               if ($ids) {
                   7841: # ------------------------------------------------------------------- Has ID(s)
                   7842:                  my @possibilities=split(/\,/,$ids);
1.39      www      7843:                  if ($#possibilities==0) {
                   7844: # ----------------------------------------------- There is only one possibility
1.37      www      7845: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7846: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7847: 						    $resid,$thisfn);
1.249     www      7848:                  } elsif (!$donotrecurse) {
1.39      www      7849: # ------------------------------------------ There is more than one possibility
                   7850:                      my $realpossible=0;
1.800     albertel 7851:                      foreach my $id (@possibilities) {
                   7852: 			 my $file=$bighash{'src_'.$id};
1.39      www      7853:                          if (&allowed('bre',$file)) {
1.800     albertel 7854:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7855:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7856: 				$realpossible++;
1.626     albertel 7857:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7858: 						    $resid,$thisfn);
1.39      www      7859:                             }
                   7860: 			 }
1.191     harris41 7861:                      }
1.39      www      7862: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7863:                  } else {
                   7864:                      $syval='';
1.37      www      7865:                  }
                   7866: 	      }
                   7867:               untie(%bighash)
1.481     raeburn  7868:            }
1.31      www      7869:         }
1.62      www      7870:         if ($syval) {
1.620     albertel 7871: 	    return $env{$cache_str}=$syval;
1.62      www      7872:         }
1.31      www      7873:     }
1.949     raeburn  7874:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 7875:     return $env{$cache_str}='';
1.31      www      7876: }
                   7877: 
                   7878: # ---------------------------------------------------------- Return random seed
                   7879: 
1.32      www      7880: sub numval {
                   7881:     my $txt=shift;
                   7882:     $txt=~tr/A-J/0-9/;
                   7883:     $txt=~tr/a-j/0-9/;
                   7884:     $txt=~tr/K-T/0-9/;
                   7885:     $txt=~tr/k-t/0-9/;
                   7886:     $txt=~tr/U-Z/0-5/;
                   7887:     $txt=~tr/u-z/0-5/;
                   7888:     $txt=~s/\D//g;
1.564     albertel 7889:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7890:     return int($txt);
1.368     albertel 7891: }
                   7892: 
1.484     albertel 7893: sub numval2 {
                   7894:     my $txt=shift;
                   7895:     $txt=~tr/A-J/0-9/;
                   7896:     $txt=~tr/a-j/0-9/;
                   7897:     $txt=~tr/K-T/0-9/;
                   7898:     $txt=~tr/k-t/0-9/;
                   7899:     $txt=~tr/U-Z/0-5/;
                   7900:     $txt=~tr/u-z/0-5/;
                   7901:     $txt=~s/\D//g;
                   7902:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7903:     my $total;
                   7904:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7905:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7906:     return int($total);
                   7907: }
                   7908: 
1.575     albertel 7909: sub numval3 {
                   7910:     use integer;
                   7911:     my $txt=shift;
                   7912:     $txt=~tr/A-J/0-9/;
                   7913:     $txt=~tr/a-j/0-9/;
                   7914:     $txt=~tr/K-T/0-9/;
                   7915:     $txt=~tr/k-t/0-9/;
                   7916:     $txt=~tr/U-Z/0-5/;
                   7917:     $txt=~tr/u-z/0-5/;
                   7918:     $txt=~s/\D//g;
                   7919:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7920:     my $total;
                   7921:     foreach my $val (@txts) { $total+=$val; }
                   7922:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7923:     return $total;
                   7924: }
                   7925: 
1.675     albertel 7926: sub digest {
                   7927:     my ($data)=@_;
                   7928:     my $digest=&Digest::MD5::md5($data);
                   7929:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7930:     my ($e,$f);
                   7931:     {
                   7932:         use integer;
                   7933:         $e=($a+$b);
                   7934:         $f=($c+$d);
                   7935:         if ($_64bit) {
                   7936:             $e=(($e<<32)>>32);
                   7937:             $f=(($f<<32)>>32);
                   7938:         }
                   7939:     }
                   7940:     if (wantarray) {
                   7941: 	return ($e,$f);
                   7942:     } else {
                   7943: 	my $g;
                   7944: 	{
                   7945: 	    use integer;
                   7946: 	    $g=($e+$f);
                   7947: 	    if ($_64bit) {
                   7948: 		$g=(($g<<32)>>32);
                   7949: 	    }
                   7950: 	}
                   7951: 	return $g;
                   7952:     }
                   7953: }
                   7954: 
1.368     albertel 7955: sub latest_rnd_algorithm_id {
1.675     albertel 7956:     return '64bit5';
1.366     albertel 7957: }
1.32      www      7958: 
1.503     albertel 7959: sub get_rand_alg {
                   7960:     my ($courseid)=@_;
1.790     albertel 7961:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7962:     if ($courseid) {
1.620     albertel 7963: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7964:     }
                   7965:     return &latest_rnd_algorithm_id();
                   7966: }
                   7967: 
1.562     albertel 7968: sub validCODE {
                   7969:     my ($CODE)=@_;
                   7970:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7971:     return 0;
                   7972: }
                   7973: 
1.491     albertel 7974: sub getCODE {
1.620     albertel 7975:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7976:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7977: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7978: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7979: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7980:     }
                   7981:     return undef;
                   7982: }
                   7983: 
1.31      www      7984: sub rndseed {
1.155     albertel 7985:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7986:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7987:     if (!defined($symb)) {
1.366     albertel 7988: 	unless ($symb=$wsymb) { return time; }
                   7989:     }
                   7990:     if (!$courseid) { $courseid=$wcourseid; }
                   7991:     if (!$domain) { $domain=$wdomain; }
                   7992:     if (!$username) { $username=$wusername }
1.503     albertel 7993:     my $which=&get_rand_alg();
1.803     albertel 7994: 
1.491     albertel 7995:     if (defined(&getCODE())) {
1.675     albertel 7996: 	if ($which eq '64bit5') {
                   7997: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7998: 	} elsif ($which eq '64bit4') {
1.575     albertel 7999: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   8000: 	} else {
                   8001: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   8002: 	}
1.675     albertel 8003:     } elsif ($which eq '64bit5') {
                   8004: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 8005:     } elsif ($which eq '64bit4') {
                   8006: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 8007:     } elsif ($which eq '64bit3') {
                   8008: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 8009:     } elsif ($which eq '64bit2') {
                   8010: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 8011:     } elsif ($which eq '64bit') {
                   8012: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   8013:     }
                   8014:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   8015: }
                   8016: 
                   8017: sub rndseed_32bit {
                   8018:     my ($symb,$courseid,$domain,$username)=@_;
                   8019:     {
                   8020: 	use integer;
                   8021: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   8022: 	my $symbseed=numval($symb) << 22;
                   8023: 	my $namechck=unpack("%32C*",$username) << 17;
                   8024: 	my $nameseed=numval($username) << 12;
                   8025: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   8026: 	my $courseseed=unpack("%32C*",$courseid);
                   8027: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 8028: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8029: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8030: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 8031: 	return $num;
                   8032:     }
                   8033: }
                   8034: 
                   8035: sub rndseed_64bit {
                   8036:     my ($symb,$courseid,$domain,$username)=@_;
                   8037:     {
                   8038: 	use integer;
                   8039: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   8040: 	my $symbseed=numval($symb) << 10;
                   8041: 	my $namechck=unpack("%32S*",$username);
                   8042: 	
                   8043: 	my $nameseed=numval($username) << 21;
                   8044: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   8045: 	my $courseseed=unpack("%32S*",$courseid);
                   8046: 	
                   8047: 	my $num1=$symbchck+$symbseed+$namechck;
                   8048: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8049: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8050: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 8051: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 8052: 	return "$num1,$num2";
1.155     albertel 8053:     }
1.366     albertel 8054: }
                   8055: 
1.443     albertel 8056: sub rndseed_64bit2 {
                   8057:     my ($symb,$courseid,$domain,$username)=@_;
                   8058:     {
                   8059: 	use integer;
                   8060: 	# strings need to be an even # of cahracters long, it it is odd the
                   8061:         # last characters gets thrown away
                   8062: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8063: 	my $symbseed=numval($symb) << 10;
                   8064: 	my $namechck=unpack("%32S*",$username.' ');
                   8065: 	
                   8066: 	my $nameseed=numval($username) << 21;
1.501     albertel 8067: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8068: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8069: 	
                   8070: 	my $num1=$symbchck+$symbseed+$namechck;
                   8071: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8072: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8073: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 8074: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 8075: 	return "$num1,$num2";
                   8076:     }
                   8077: }
                   8078: 
                   8079: sub rndseed_64bit3 {
                   8080:     my ($symb,$courseid,$domain,$username)=@_;
                   8081:     {
                   8082: 	use integer;
                   8083: 	# strings need to be an even # of cahracters long, it it is odd the
                   8084:         # last characters gets thrown away
                   8085: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8086: 	my $symbseed=numval2($symb) << 10;
                   8087: 	my $namechck=unpack("%32S*",$username.' ');
                   8088: 	
                   8089: 	my $nameseed=numval2($username) << 21;
1.443     albertel 8090: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8091: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8092: 	
                   8093: 	my $num1=$symbchck+$symbseed+$namechck;
                   8094: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8095: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8096: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 8097: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8098: 	
1.503     albertel 8099: 	return "$num1:$num2";
1.443     albertel 8100:     }
                   8101: }
                   8102: 
1.575     albertel 8103: sub rndseed_64bit4 {
                   8104:     my ($symb,$courseid,$domain,$username)=@_;
                   8105:     {
                   8106: 	use integer;
                   8107: 	# strings need to be an even # of cahracters long, it it is odd the
                   8108:         # last characters gets thrown away
                   8109: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   8110: 	my $symbseed=numval3($symb) << 10;
                   8111: 	my $namechck=unpack("%32S*",$username.' ');
                   8112: 	
                   8113: 	my $nameseed=numval3($username) << 21;
                   8114: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   8115: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8116: 	
                   8117: 	my $num1=$symbchck+$symbseed+$namechck;
                   8118: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 8119: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   8120: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 8121: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   8122: 	
                   8123: 	return "$num1:$num2";
                   8124:     }
                   8125: }
                   8126: 
1.675     albertel 8127: sub rndseed_64bit5 {
                   8128:     my ($symb,$courseid,$domain,$username)=@_;
                   8129:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   8130:     return "$num1:$num2";
                   8131: }
                   8132: 
1.366     albertel 8133: sub rndseed_CODE_64bit {
                   8134:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 8135:     {
1.366     albertel 8136: 	use integer;
1.443     albertel 8137: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 8138: 	my $symbseed=numval2($symb);
1.491     albertel 8139: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8140: 	my $CODEseed=numval(&getCODE());
1.443     albertel 8141: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 8142: 	my $num1=$symbseed+$CODEchck;
                   8143: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8144: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8145: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 8146: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8147: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 8148: 	return "$num1:$num2";
1.366     albertel 8149:     }
                   8150: }
                   8151: 
1.575     albertel 8152: sub rndseed_CODE_64bit4 {
                   8153:     my ($symb,$courseid,$domain,$username)=@_;
                   8154:     {
                   8155: 	use integer;
                   8156: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   8157: 	my $symbseed=numval3($symb);
                   8158: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   8159: 	my $CODEseed=numval3(&getCODE());
                   8160: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   8161: 	my $num1=$symbseed+$CODEchck;
                   8162: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 8163: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   8164: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 8165: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   8166: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   8167: 	return "$num1:$num2";
                   8168:     }
                   8169: }
                   8170: 
1.675     albertel 8171: sub rndseed_CODE_64bit5 {
                   8172:     my ($symb,$courseid,$domain,$username)=@_;
                   8173:     my $code = &getCODE();
                   8174:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   8175:     return "$num1:$num2";
                   8176: }
                   8177: 
1.366     albertel 8178: sub setup_random_from_rndseed {
                   8179:     my ($rndseed)=@_;
1.503     albertel 8180:     if ($rndseed =~/([,:])/) {
                   8181: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 8182: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   8183:     } else {
                   8184: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 8185:     }
1.36      albertel 8186: }
                   8187: 
1.474     albertel 8188: sub latest_receipt_algorithm_id {
1.835     albertel 8189:     return 'receipt3';
1.474     albertel 8190: }
                   8191: 
1.480     www      8192: sub recunique {
                   8193:     my $fucourseid=shift;
                   8194:     my $unique;
1.835     albertel 8195:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   8196: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8197: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      8198:     } else {
                   8199: 	$unique=$perlvar{'lonReceipt'};
                   8200:     }
                   8201:     return unpack("%32C*",$unique);
                   8202: }
                   8203: 
                   8204: sub recprefix {
                   8205:     my $fucourseid=shift;
                   8206:     my $prefix;
1.835     albertel 8207:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   8208: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 8209: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      8210:     } else {
                   8211: 	$prefix=$perlvar{'lonHostID'};
                   8212:     }
                   8213:     return unpack("%32C*",$prefix);
                   8214: }
                   8215: 
1.76      www      8216: sub ireceipt {
1.474     albertel 8217:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 8218: 
                   8219:     my $return =&recprefix($fucourseid).'-';
                   8220: 
                   8221:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   8222: 	$env{'request.state'} eq 'construct') {
                   8223: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   8224: 	return $return;
                   8225:     }
                   8226: 
1.76      www      8227:     my $cuname=unpack("%32C*",$funame);
                   8228:     my $cudom=unpack("%32C*",$fudom);
                   8229:     my $cucourseid=unpack("%32C*",$fucourseid);
                   8230:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      8231:     my $cunique=&recunique($fucourseid);
1.474     albertel 8232:     my $cpart=unpack("%32S*",$part);
1.835     albertel 8233:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   8234: 
1.790     albertel 8235: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 8236: 			       
                   8237: 	$return.= ($cunique%$cuname+
                   8238: 		   $cunique%$cudom+
                   8239: 		   $cusymb%$cuname+
                   8240: 		   $cusymb%$cudom+
                   8241: 		   $cucourseid%$cuname+
                   8242: 		   $cucourseid%$cudom+
                   8243: 		   $cpart%$cuname+
                   8244: 		   $cpart%$cudom);
                   8245:     } else {
                   8246: 	$return.= ($cunique%$cuname+
                   8247: 		   $cunique%$cudom+
                   8248: 		   $cusymb%$cuname+
                   8249: 		   $cusymb%$cudom+
                   8250: 		   $cucourseid%$cuname+
                   8251: 		   $cucourseid%$cudom);
                   8252:     }
                   8253:     return $return;
1.76      www      8254: }
                   8255: 
                   8256: sub receipt {
1.474     albertel 8257:     my ($part)=@_;
1.790     albertel 8258:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 8259:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      8260: }
1.260     ng       8261: 
1.790     albertel 8262: sub whichuser {
                   8263:     my ($passedsymb)=@_;
                   8264:     my ($symb,$courseid,$domain,$name,$publicuser);
                   8265:     if (defined($env{'form.grade_symb'})) {
                   8266: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   8267: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   8268: 	if (!$allowed &&
                   8269: 	    exists($env{'request.course.sec'}) &&
                   8270: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   8271: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   8272: 			      '/'.$env{'request.course.sec'});
                   8273: 	}
                   8274: 	if ($allowed) {
                   8275: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   8276: 	    $courseid=$tmp_courseid;
                   8277: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   8278: 	    ($name)=&get_env_multiple('form.grade_username');
                   8279: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   8280: 	}
                   8281:     }
                   8282:     if (!$passedsymb) {
                   8283: 	$symb=&symbread();
                   8284:     } else {
                   8285: 	$symb=$passedsymb;
                   8286:     }
                   8287:     $courseid=$env{'request.course.id'};
                   8288:     $domain=$env{'user.domain'};
                   8289:     $name=$env{'user.name'};
                   8290:     if ($name eq 'public' && $domain eq 'public') {
                   8291: 	if (!defined($env{'form.username'})) {
                   8292: 	    $env{'form.username'}.=time.rand(10000000);
                   8293: 	}
                   8294: 	$name.=$env{'form.username'};
                   8295:     }
                   8296:     return ($symb,$courseid,$domain,$name,$publicuser);
                   8297: 
                   8298: }
                   8299: 
1.36      albertel 8300: # ------------------------------------------------------------ Serves up a file
1.472     albertel 8301: # returns either the contents of the file or 
                   8302: # -1 if the file doesn't exist
1.481     raeburn  8303: #
                   8304: # if the target is a file that was uploaded via DOCS, 
                   8305: # a check will be made to see if a current copy exists on the local server,
                   8306: # if it does this will be served, otherwise a copy will be retrieved from
                   8307: # the home server for the course and stored in /home/httpd/html/userfiles on
                   8308: # the local server.   
1.472     albertel 8309: 
1.36      albertel 8310: sub getfile {
1.538     albertel 8311:     my ($file) = @_;
1.609     banghart 8312:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 8313:     &repcopy($file);
                   8314:     return &readfile($file);
                   8315: }
                   8316: 
                   8317: sub repcopy_userfile {
                   8318:     my ($file)=@_;
1.609     banghart 8319:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 8320:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 8321:     my ($cdom,$cnum,$filename) = 
1.811     albertel 8322: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 8323:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   8324:     if (-e "$file") {
1.828     www      8325: # we already have a local copy, check it out
1.538     albertel 8326: 	my @fileinfo = stat($file);
1.828     www      8327: 	my $rtncode;
                   8328: 	my $info;
1.538     albertel 8329: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 8330: 	if ($lwpresp ne 'ok') {
1.828     www      8331: # there is no such file anymore, even though we had a local copy
1.482     albertel 8332: 	    if ($rtncode eq '404') {
1.538     albertel 8333: 		unlink($file);
1.482     albertel 8334: 	    }
                   8335: 	    return -1;
                   8336: 	}
                   8337: 	if ($info < $fileinfo[9]) {
1.828     www      8338: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  8339: 	    return 'ok';
1.828     www      8340: 	} else {
                   8341: # the file is outdated, get rid of it
                   8342: 	    unlink($file);
1.482     albertel 8343: 	}
1.828     www      8344:     }
                   8345: # one way or the other, at this point, we don't have the file
                   8346: # construct the correct path for the file
                   8347:     my @parts = ($cdom,$cnum); 
                   8348:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   8349: 	push @parts, split(/\//,$1);
                   8350:     }
                   8351:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   8352:     foreach my $part (@parts) {
                   8353: 	$path .= '/'.$part;
                   8354: 	if (!-e $path) {
                   8355: 	    mkdir($path,0770);
1.482     albertel 8356: 	}
                   8357:     }
1.828     www      8358: # now the path exists for sure
                   8359: # get a user agent
                   8360:     my $ua=new LWP::UserAgent;
                   8361:     my $transferfile=$file.'.in.transfer';
                   8362: # FIXME: this should flock
                   8363:     if (-e $transferfile) { return 'ok'; }
                   8364:     my $request;
                   8365:     $uri=~s/^\///;
1.976.2.3  raeburn  8366:     my $homeserver = &homeserver($cnum,$cdom);
                   8367:     my $protocol = $protocol{$homeserver};
                   8368:     $protocol = 'http' if ($protocol ne 'https');
                   8369:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      8370:     my $response=$ua->request($request,$transferfile);
                   8371: # did it work?
                   8372:     if ($response->is_error()) {
                   8373: 	unlink($transferfile);
                   8374: 	&logthis("Userfile repcopy failed for $uri");
                   8375: 	return -1;
                   8376:     }
                   8377: # worked, rename the transfer file
                   8378:     rename($transferfile,$file);
1.607     raeburn  8379:     return 'ok';
1.481     raeburn  8380: }
                   8381: 
1.517     albertel 8382: sub tokenwrapper {
                   8383:     my $uri=shift;
1.976.2.3  raeburn  8384:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 8385:     $uri=~s|^/||;
1.620     albertel 8386:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 8387:     my $token=$1;
1.552     albertel 8388:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   8389:     if ($udom && $uname && $file) {
                   8390: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  8391:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.976.2.3  raeburn  8392:         my $homeserver = &homeserver($uname,$udom);
                   8393:         my $protocol = $protocol{$homeserver};
                   8394:         $protocol = 'http' if ($protocol ne 'https');
                   8395:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 8396:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   8397:                                '&tokenissued='.$perlvar{'lonHostID'};
                   8398:     } else {
                   8399:         return '/adm/notfound.html';
                   8400:     }
                   8401: }
                   8402: 
1.828     www      8403: # call with reqtype HEAD: get last modification time
                   8404: # call with reqtype GET: get the file contents
                   8405: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8406: #
1.481     raeburn  8407: sub getuploaded {
                   8408:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8409:     $uri=~s/^\///;
1.976.2.3  raeburn  8410:     my $homeserver = &homeserver($cnum,$cdom);
                   8411:     my $protocol = $protocol{$homeserver};
                   8412:     $protocol = 'http' if ($protocol ne 'https');
                   8413:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  8414:     my $ua=new LWP::UserAgent;
                   8415:     my $request=new HTTP::Request($reqtype,$uri);
                   8416:     my $response=$ua->request($request);
                   8417:     $$rtncode = $response->code;
1.482     albertel 8418:     if (! $response->is_success()) {
                   8419: 	return 'failed';
                   8420:     }      
                   8421:     if ($reqtype eq 'HEAD') {
1.486     www      8422: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8423:     } elsif ($reqtype eq 'GET') {
                   8424: 	$$info = $response->content;
1.472     albertel 8425:     }
1.482     albertel 8426:     return 'ok';
1.36      albertel 8427: }
                   8428: 
1.481     raeburn  8429: sub readfile {
                   8430:     my $file = shift;
                   8431:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8432:     my $fh;
                   8433:     open($fh,"<$file");
                   8434:     my $a='';
1.800     albertel 8435:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8436:     return $a;
                   8437: }
                   8438: 
1.36      albertel 8439: sub filelocation {
1.590     banghart 8440:     my ($dir,$file) = @_;
                   8441:     my $location;
                   8442:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8443: 
                   8444:     if ($file =~ m-^/adm/-) {
                   8445: 	$file=~s-^/adm/wrapper/-/-;
                   8446: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8447:     }
1.882     albertel 8448: 
1.590     banghart 8449:     if ($file=~m:^/~:) { # is a contruction space reference
                   8450:         $location = $file;
                   8451:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8452:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8453: 	# is a correct contruction space reference
                   8454:         $location = $file;
1.956     raeburn  8455:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   8456:         $location = $file;
1.609     banghart 8457:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8458:         my ($udom,$uname,$filename)=
1.811     albertel 8459:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8460:         my $home=&homeserver($uname,$udom);
                   8461:         my $is_me=0;
                   8462:         my @ids=&current_machine_ids();
                   8463:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8464:         if ($is_me) {
1.955     raeburn  8465:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 8466:         } else {
                   8467:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8468:   	      $udom.'/'.$uname.'/'.$filename;
                   8469:         }
1.882     albertel 8470:     } elsif ($file =~ m-^/adm/-) {
                   8471: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8472:     } else {
                   8473:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8474:         $file=~s:^/res/:/:;
                   8475:         if ( !( $file =~ m:^/:) ) {
                   8476:             $location = $dir. '/'.$file;
                   8477:         } else {
                   8478:             $location = '/home/httpd/html/res'.$file;
                   8479:         }
1.59      albertel 8480:     }
1.590     banghart 8481:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8482:     while ($location=~m{/\.\./}) {
                   8483: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8484: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8485: 	} else {
                   8486: 	    $location=~ s{/\.\./}{/}g;
                   8487: 	}
                   8488:     } #remove dir/..
1.590     banghart 8489:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8490:     return $location;
1.46      www      8491: }
1.36      albertel 8492: 
1.46      www      8493: sub hreflocation {
                   8494:     my ($dir,$file)=@_;
1.976.2.3  raeburn  8495:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 8496: 	$file=filelocation($dir,$file);
1.700     albertel 8497:     } elsif ($file=~m-^/adm/-) {
                   8498: 	$file=~s-^/adm/wrapper/-/-;
                   8499: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8500:     }
                   8501:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8502: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8503:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8504: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8505:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8506: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8507: 	    -/uploaded/$1/$2/-x;
1.46      www      8508:     }
1.913     albertel 8509:     if ($file=~ m{^/userfiles/}) {
                   8510: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8511:     }
1.462     albertel 8512:     return $file;
1.465     albertel 8513: }
                   8514: 
                   8515: sub current_machine_domains {
1.853     albertel 8516:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8517: }
                   8518: 
                   8519: sub machine_domains {
                   8520:     my ($hostname) = @_;
1.465     albertel 8521:     my @domains;
1.838     albertel 8522:     my %hostname = &all_hostnames();
1.465     albertel 8523:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8524: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8525: 	if ($hostname eq $name) {
1.844     albertel 8526: 	    push(@domains,&host_domain($id));
1.465     albertel 8527: 	}
                   8528:     }
                   8529:     return @domains;
                   8530: }
                   8531: 
                   8532: sub current_machine_ids {
1.853     albertel 8533:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8534: }
                   8535: 
                   8536: sub machine_ids {
                   8537:     my ($hostname) = @_;
                   8538:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8539:     my @ids;
1.888     albertel 8540:     my %name_to_host = &all_names();
1.889     albertel 8541:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8542: 	return @{ $name_to_host{$hostname} };
                   8543:     }
                   8544:     return;
1.31      www      8545: }
                   8546: 
1.824     raeburn  8547: sub additional_machine_domains {
                   8548:     my @domains;
                   8549:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8550:     while( my $line = <$fh>) {
                   8551:         $line =~ s/\s//g;
                   8552:         push(@domains,$line);
                   8553:     }
                   8554:     return @domains;
                   8555: }
                   8556: 
                   8557: sub default_login_domain {
                   8558:     my $domain = $perlvar{'lonDefDomain'};
                   8559:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8560:     foreach my $posdom (&current_machine_domains(),
                   8561:                         &additional_machine_domains()) {
                   8562:         if (lc($posdom) eq lc($testdomain)) {
                   8563:             $domain=$posdom;
                   8564:             last;
                   8565:         }
                   8566:     }
                   8567:     return $domain;
                   8568: }
                   8569: 
1.31      www      8570: # ------------------------------------------------------------- Declutters URLs
                   8571: 
                   8572: sub declutter {
                   8573:     my $thisfn=shift;
1.569     albertel 8574:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8575:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8576:     $thisfn=~s/^\///;
1.697     albertel 8577:     $thisfn=~s|^adm/wrapper/||;
                   8578:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8579:     $thisfn=~s/^res\///;
1.235     www      8580:     $thisfn=~s/\?.+$//;
1.268     www      8581:     return $thisfn;
                   8582: }
                   8583: 
                   8584: # ------------------------------------------------------------- Clutter up URLs
                   8585: 
                   8586: sub clutter {
                   8587:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8588:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8589: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8590:        $thisfn='/res'.$thisfn; 
                   8591:     }
1.694     albertel 8592:     if ($thisfn !~m|/adm|) {
1.695     albertel 8593: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8594: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8595: 	} else {
                   8596: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8597: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8598: 	    if ($embstyle eq 'ssi'
                   8599: 		|| ($embstyle eq 'hdn')
                   8600: 		|| ($embstyle eq 'rat')
                   8601: 		|| ($embstyle eq 'prv')
                   8602: 		|| ($embstyle eq 'ign')) {
                   8603: 		#do nothing with these
                   8604: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8605: 		|| ($embstyle eq 'emb')
                   8606: 		|| ($embstyle eq 'wrp')) {
                   8607: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8608: 	    } elsif ($embstyle eq 'unk'
                   8609: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8610: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8611: 	    } else {
1.718     www      8612: #		&logthis("Got a blank emb style");
1.695     albertel 8613: 	    }
1.694     albertel 8614: 	}
                   8615:     }
1.31      www      8616:     return $thisfn;
1.12      www      8617: }
                   8618: 
1.787     albertel 8619: sub clutter_with_no_wrapper {
                   8620:     my $uri = &clutter(shift);
                   8621:     if ($uri =~ m-^/adm/-) {
                   8622: 	$uri =~ s-^/adm/wrapper/-/-;
                   8623: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8624:     }
                   8625:     return $uri;
                   8626: }
                   8627: 
1.557     albertel 8628: sub freeze_escape {
                   8629:     my ($value)=@_;
                   8630:     if (ref($value)) {
                   8631: 	$value=&nfreeze($value);
                   8632: 	return '__FROZEN__'.&escape($value);
                   8633:     }
                   8634:     return &escape($value);
                   8635: }
                   8636: 
1.11      www      8637: 
1.557     albertel 8638: sub thaw_unescape {
                   8639:     my ($value)=@_;
                   8640:     if ($value =~ /^__FROZEN__/) {
                   8641: 	substr($value,0,10,undef);
                   8642: 	$value=&unescape($value);
                   8643: 	return &thaw($value);
                   8644:     }
                   8645:     return &unescape($value);
                   8646: }
                   8647: 
1.436     albertel 8648: sub correct_line_ends {
                   8649:     my ($result)=@_;
                   8650:     $$result =~s/\r\n/\n/mg;
                   8651:     $$result =~s/\r/\n/mg;
1.415     albertel 8652: }
1.1       albertel 8653: # ================================================================ Main Program
                   8654: 
1.184     www      8655: sub goodbye {
1.204     albertel 8656:    &logthis("Starting Shut down");
1.443     albertel 8657: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8658:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8659: #converted
1.599     albertel 8660: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8661:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8662: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8663: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8664: #1.1 only
1.870     albertel 8665: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8666: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8667: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8668: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8669:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8670:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8671:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8672:    &flushcourselogs();
                   8673:    &logthis("Shutting down");
                   8674: }
                   8675: 
1.852     albertel 8676: sub get_dns {
1.869     albertel 8677:     my ($url,$func,$ignore_cache) = @_;
                   8678:     if (!$ignore_cache) {
                   8679: 	my ($content,$cached)=
                   8680: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8681: 	if ($cached) {
                   8682: 	    &$func($content);
                   8683: 	    return;
                   8684: 	}
                   8685:     }
                   8686: 
                   8687:     my %alldns;
1.852     albertel 8688:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8689:     foreach my $dns (<$config>) {
                   8690: 	next if ($dns !~ /^\^(\S*)/x);
1.976.2.2  raeburn  8691:         my $line = $1;
                   8692:         my ($host,$protocol) = split(/:/,$line);
                   8693:         if ($protocol ne 'https') {
                   8694:             $protocol = 'http';
                   8695:         }
                   8696: 	$alldns{$host} = $protocol;
1.869     albertel 8697:     }
                   8698:     while (%alldns) {
                   8699: 	my ($dns) = keys(%alldns);
1.852     albertel 8700: 	my $ua=new LWP::UserAgent;
1.976.2.2  raeburn  8701: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 8702: 	my $response=$ua->request($request);
1.976.2.2  raeburn  8703:         delete($alldns{$dns});
1.852     albertel 8704: 	next if ($response->is_error());
                   8705: 	my @content = split("\n",$response->content);
1.869     albertel 8706: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8707: 	&$func(\@content);
1.869     albertel 8708: 	return;
1.852     albertel 8709:     }
                   8710:     close($config);
1.871     albertel 8711:     my $which = (split('/',$url))[3];
                   8712:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8713:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8714:     my @content = <$config>;
                   8715:     &$func(\@content);
                   8716:     return;
1.852     albertel 8717: }
1.327     albertel 8718: # ------------------------------------------------------------ Read domain file
                   8719: {
1.852     albertel 8720:     my $loaded;
1.846     albertel 8721:     my %domain;
                   8722: 
1.852     albertel 8723:     sub parse_domain_tab {
                   8724: 	my ($lines) = @_;
                   8725: 	foreach my $line (@$lines) {
                   8726: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8727: 
1.846     albertel 8728: 	    chomp($line);
1.852     albertel 8729: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8730: 	    my %this_domain;
                   8731: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8732: 			       'lang_def', 'city', 'longi', 'lati',
                   8733: 			       'primary') {
                   8734: 		$this_domain{$field} = shift(@elements);
                   8735: 	    }
                   8736: 	    $domain{$name} = \%this_domain;
1.852     albertel 8737: 	}
                   8738:     }
1.864     albertel 8739: 
                   8740:     sub reset_domain_info {
                   8741: 	undef($loaded);
                   8742: 	undef(%domain);
                   8743:     }
                   8744: 
1.852     albertel 8745:     sub load_domain_tab {
1.869     albertel 8746: 	my ($ignore_cache) = @_;
                   8747: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8748: 	my $fh;
                   8749: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8750: 	    my @lines = <$fh>;
                   8751: 	    &parse_domain_tab(\@lines);
1.448     albertel 8752: 	}
1.852     albertel 8753: 	close($fh);
                   8754: 	$loaded = 1;
1.327     albertel 8755:     }
1.846     albertel 8756: 
                   8757:     sub domain {
1.852     albertel 8758: 	&load_domain_tab() if (!$loaded);
                   8759: 
1.846     albertel 8760: 	my ($name,$what) = @_;
                   8761: 	return if ( !exists($domain{$name}) );
                   8762: 
                   8763: 	if (!$what) {
                   8764: 	    return $domain{$name}{'description'};
                   8765: 	}
                   8766: 	return $domain{$name}{$what};
                   8767:     }
1.974     raeburn  8768: 
                   8769:     sub domain_info {
                   8770:         &load_domain_tab() if (!$loaded);
                   8771:         return %domain;
                   8772:     }
                   8773: 
1.327     albertel 8774: }
                   8775: 
                   8776: 
1.1       albertel 8777: # ------------------------------------------------------------- Read hosts file
                   8778: {
1.838     albertel 8779:     my %hostname;
1.844     albertel 8780:     my %hostdom;
1.845     albertel 8781:     my %libserv;
1.852     albertel 8782:     my $loaded;
1.888     albertel 8783:     my %name_to_host;
1.852     albertel 8784: 
                   8785:     sub parse_hosts_tab {
                   8786: 	my ($file) = @_;
                   8787: 	foreach my $configline (@$file) {
                   8788: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8789: 	    next if ($configline =~ /^\^/);
                   8790: 	    chomp($configline);
1.968     raeburn  8791: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
1.852     albertel 8792: 	    $name=~s/\s//g;
                   8793: 	    if ($id && $domain && $role && $name) {
                   8794: 		$hostname{$id}=$name;
1.888     albertel 8795: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8796: 		$hostdom{$id}=$domain;
                   8797: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  8798:                 if (defined($protocol)) {
                   8799:                     if ($protocol eq 'https') {
                   8800:                         $protocol{$id} = $protocol;
                   8801:                     } else {
                   8802:                         $protocol{$id} = 'http'; 
                   8803:                     }
1.968     raeburn  8804:                 } else {
1.969     raeburn  8805:                     $protocol{$id} = 'http';
1.968     raeburn  8806:                 }
1.852     albertel 8807: 	    }
                   8808: 	}
                   8809:     }
1.864     albertel 8810:     
                   8811:     sub reset_hosts_info {
1.897     albertel 8812: 	&purge_remembered();
1.864     albertel 8813: 	&reset_domain_info();
                   8814: 	&reset_hosts_ip_info();
1.892     albertel 8815: 	undef(%name_to_host);
1.864     albertel 8816: 	undef(%hostname);
                   8817: 	undef(%hostdom);
                   8818: 	undef(%libserv);
                   8819: 	undef($loaded);
                   8820:     }
1.1       albertel 8821: 
1.852     albertel 8822:     sub load_hosts_tab {
1.869     albertel 8823: 	my ($ignore_cache) = @_;
                   8824: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8825: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8826: 	my @config = <$config>;
                   8827: 	&parse_hosts_tab(\@config);
                   8828: 	close($config);
                   8829: 	$loaded=1;
1.1       albertel 8830:     }
1.852     albertel 8831: 
1.838     albertel 8832:     sub hostname {
1.852     albertel 8833: 	&load_hosts_tab() if (!$loaded);
                   8834: 
1.838     albertel 8835: 	my ($lonid) = @_;
                   8836: 	return $hostname{$lonid};
                   8837:     }
1.845     albertel 8838: 
1.838     albertel 8839:     sub all_hostnames {
1.852     albertel 8840: 	&load_hosts_tab() if (!$loaded);
                   8841: 
1.838     albertel 8842: 	return %hostname;
                   8843:     }
1.845     albertel 8844: 
1.888     albertel 8845:     sub all_names {
                   8846: 	&load_hosts_tab() if (!$loaded);
                   8847: 
                   8848: 	return %name_to_host;
                   8849:     }
                   8850: 
1.974     raeburn  8851:     sub all_host_domain {
                   8852:         &load_hosts_tab() if (!$loaded);
                   8853:         return %hostdom;
                   8854:     }
                   8855: 
1.845     albertel 8856:     sub is_library {
1.852     albertel 8857: 	&load_hosts_tab() if (!$loaded);
                   8858: 
1.845     albertel 8859: 	return exists($libserv{$_[0]});
                   8860:     }
                   8861: 
                   8862:     sub all_library {
1.852     albertel 8863: 	&load_hosts_tab() if (!$loaded);
                   8864: 
1.845     albertel 8865: 	return %libserv;
                   8866:     }
                   8867: 
1.841     albertel 8868:     sub get_servers {
1.852     albertel 8869: 	&load_hosts_tab() if (!$loaded);
                   8870: 
1.841     albertel 8871: 	my ($domain,$type) = @_;
                   8872: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8873: 	                                          : %hostname;
                   8874: 	my %result;
1.842     albertel 8875: 	if (ref($domain) eq 'ARRAY') {
                   8876: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8877: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8878: 		    $result{$host} = $hostname;
                   8879: 		}
                   8880: 	    }
                   8881: 	} else {
                   8882: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8883: 		if ($hostdom{$host} eq $domain) {
                   8884: 		    $result{$host} = $hostname;
                   8885: 		}
1.841     albertel 8886: 	    }
                   8887: 	}
                   8888: 	return %result;
                   8889:     }
1.845     albertel 8890: 
1.844     albertel 8891:     sub host_domain {
1.852     albertel 8892: 	&load_hosts_tab() if (!$loaded);
                   8893: 
1.844     albertel 8894: 	my ($lonid) = @_;
                   8895: 	return $hostdom{$lonid};
                   8896:     }
                   8897: 
1.841     albertel 8898:     sub all_domains {
1.852     albertel 8899: 	&load_hosts_tab() if (!$loaded);
                   8900: 
1.841     albertel 8901: 	my %seen;
                   8902: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8903: 	return @uniq;
                   8904:     }
1.1       albertel 8905: }
                   8906: 
1.847     albertel 8907: { 
                   8908:     my %iphost;
1.856     albertel 8909:     my %name_to_ip;
                   8910:     my %lonid_to_ip;
1.869     albertel 8911: 
1.847     albertel 8912:     sub get_hosts_from_ip {
                   8913: 	my ($ip) = @_;
                   8914: 	my %iphosts = &get_iphost();
                   8915: 	if (ref($iphosts{$ip})) {
                   8916: 	    return @{$iphosts{$ip}};
                   8917: 	}
                   8918: 	return;
1.839     albertel 8919:     }
1.864     albertel 8920:     
                   8921:     sub reset_hosts_ip_info {
                   8922: 	undef(%iphost);
                   8923: 	undef(%name_to_ip);
                   8924: 	undef(%lonid_to_ip);
                   8925:     }
1.856     albertel 8926: 
                   8927:     sub get_host_ip {
                   8928: 	my ($lonid) = @_;
                   8929: 	if (exists($lonid_to_ip{$lonid})) {
                   8930: 	    return $lonid_to_ip{$lonid};
                   8931: 	}
                   8932: 	my $name=&hostname($lonid);
                   8933:    	my $ip = gethostbyname($name);
                   8934: 	return if (!$ip || length($ip) ne 4);
                   8935: 	$ip=inet_ntoa($ip);
                   8936: 	$name_to_ip{$name}   = $ip;
                   8937: 	$lonid_to_ip{$lonid} = $ip;
                   8938: 	return $ip;
                   8939:     }
1.847     albertel 8940:     
                   8941:     sub get_iphost {
1.869     albertel 8942: 	my ($ignore_cache) = @_;
1.894     albertel 8943: 
1.869     albertel 8944: 	if (!$ignore_cache) {
                   8945: 	    if (%iphost) {
                   8946: 		return %iphost;
                   8947: 	    }
                   8948: 	    my ($ip_info,$cached)=
                   8949: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8950: 	    if ($cached) {
                   8951: 		%iphost      = %{$ip_info->[0]};
                   8952: 		%name_to_ip  = %{$ip_info->[1]};
                   8953: 		%lonid_to_ip = %{$ip_info->[2]};
                   8954: 		return %iphost;
                   8955: 	    }
                   8956: 	}
1.894     albertel 8957: 
                   8958: 	# get yesterday's info for fallback
                   8959: 	my %old_name_to_ip;
                   8960: 	my ($ip_info,$cached)=
                   8961: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8962: 	if ($cached) {
                   8963: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8964: 	}
                   8965: 
1.888     albertel 8966: 	my %name_to_host = &all_names();
                   8967: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8968: 	    my $ip;
                   8969: 	    if (!exists($name_to_ip{$name})) {
                   8970: 		$ip = gethostbyname($name);
                   8971: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8972: 		    if (defined($old_name_to_ip{$name})) {
                   8973: 			$ip = $old_name_to_ip{$name};
                   8974: 			&logthis("Can't find $name defaulting to old $ip");
                   8975: 		    } else {
                   8976: 			&logthis("Name $name no IP found");
                   8977: 			next;
                   8978: 		    }
                   8979: 		} else {
                   8980: 		    $ip=inet_ntoa($ip);
1.847     albertel 8981: 		}
                   8982: 		$name_to_ip{$name} = $ip;
                   8983: 	    } else {
                   8984: 		$ip = $name_to_ip{$name};
1.653     albertel 8985: 	    }
1.888     albertel 8986: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8987: 		$lonid_to_ip{$id} = $ip;
                   8988: 	    }
                   8989: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8990: 	}
1.869     albertel 8991: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8992: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8993: 				      48*60*60);
1.869     albertel 8994: 
1.847     albertel 8995: 	return %iphost;
1.598     albertel 8996:     }
                   8997: }
                   8998: 
1.862     albertel 8999: BEGIN {
                   9000: 
                   9001: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   9002:     unless ($readit) {
                   9003: {
                   9004:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   9005:     %perlvar = (%perlvar,%{$configvars});
                   9006: }
                   9007: 
                   9008: 
1.1       albertel 9009: # ------------------------------------------------------ Read spare server file
                   9010: {
1.448     albertel 9011:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 9012: 
                   9013:     while (my $configline=<$config>) {
                   9014:        chomp($configline);
1.284     matthew  9015:        if ($configline) {
1.784     albertel 9016: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 9017: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 9018: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 9019:        }
                   9020:     }
1.448     albertel 9021:     close($config);
1.1       albertel 9022: }
1.11      www      9023: # ------------------------------------------------------------ Read permissions
                   9024: {
1.448     albertel 9025:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      9026: 
                   9027:     while (my $configline=<$config>) {
1.448     albertel 9028: 	chomp($configline);
                   9029: 	if ($configline) {
                   9030: 	    my ($role,$perm)=split(/ /,$configline);
                   9031: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   9032: 	}
1.11      www      9033:     }
1.448     albertel 9034:     close($config);
1.11      www      9035: }
                   9036: 
                   9037: # -------------------------------------------- Read plain texts for permissions
                   9038: {
1.448     albertel 9039:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      9040: 
                   9041:     while (my $configline=<$config>) {
1.448     albertel 9042: 	chomp($configline);
                   9043: 	if ($configline) {
1.742     raeburn  9044: 	    my ($short,@plain)=split(/:/,$configline);
                   9045:             %{$prp{$short}} = ();
                   9046: 	    if (@plain > 0) {
                   9047:                 $prp{$short}{'std'} = $plain[0];
                   9048:                 for (my $i=1; $i<@plain; $i++) {
                   9049:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   9050:                 }
                   9051:             }
1.448     albertel 9052: 	}
1.135     www      9053:     }
1.448     albertel 9054:     close($config);
1.135     www      9055: }
                   9056: 
                   9057: # ---------------------------------------------------------- Read package table
                   9058: {
1.448     albertel 9059:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      9060: 
                   9061:     while (my $configline=<$config>) {
1.483     albertel 9062: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 9063: 	chomp($configline);
                   9064: 	my ($short,$plain)=split(/:/,$configline);
                   9065: 	my ($pack,$name)=split(/\&/,$short);
                   9066: 	if ($plain ne '') {
                   9067: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   9068: 	    $packagetab{$short}=$plain; 
                   9069: 	}
1.11      www      9070:     }
1.448     albertel 9071:     close($config);
1.329     matthew  9072: }
                   9073: 
                   9074: # ------------- set up temporary directory
                   9075: {
                   9076:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   9077: 
1.11      www      9078: }
                   9079: 
1.794     albertel 9080: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   9081: 				'compress_threshold'=> 20_000,
                   9082:  			        });
1.185     www      9083: 
1.281     www      9084: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      9085: $dumpcount=0;
1.958     www      9086: $locknum=0;
1.22      www      9087: 
1.163     harris41 9088: &logtouch();
1.672     albertel 9089: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      9090: $readit=1;
1.564     albertel 9091:     {
                   9092: 	use integer;
                   9093: 	my $test=(2**32)+1;
1.568     albertel 9094: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 9095: 	&logthis(" Detected 64bit platform ($_64bit)");
                   9096:     }
1.195     www      9097: }
1.1       albertel 9098: }
1.179     www      9099: 
1.1       albertel 9100: 1;
1.191     harris41 9101: __END__
                   9102: 
1.243     albertel 9103: =pod
                   9104: 
1.191     harris41 9105: =head1 NAME
                   9106: 
1.243     albertel 9107: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 9108: 
                   9109: =head1 SYNOPSIS
                   9110: 
1.243     albertel 9111: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 9112: 
                   9113:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   9114: 
1.243     albertel 9115: Common parameters:
                   9116: 
                   9117: =over 4
                   9118: 
                   9119: =item *
                   9120: 
                   9121: $uname : an internal username (if $cname expecting a course Id specifically)
                   9122: 
                   9123: =item *
                   9124: 
                   9125: $udom : a domain (if $cdom expecting a course's domain specifically)
                   9126: 
                   9127: =item *
                   9128: 
                   9129: $symb : a resource instance identifier
                   9130: 
                   9131: =item *
                   9132: 
                   9133: $namespace : the name of a .db file that contains the data needed or
                   9134: being set.
                   9135: 
                   9136: =back
                   9137: 
1.394     bowersj2 9138: =head1 OVERVIEW
1.191     harris41 9139: 
1.394     bowersj2 9140: lonnet provides subroutines which interact with the
                   9141: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   9142: about classes, users, and resources.
1.243     albertel 9143: 
                   9144: For many of these objects you can also use this to store data about
                   9145: them or modify them in various ways.
1.191     harris41 9146: 
1.394     bowersj2 9147: =head2 Symbs
1.191     harris41 9148: 
1.394     bowersj2 9149: To identify a specific instance of a resource, LON-CAPA uses symbols
                   9150: or "symbs"X<symb>. These identifiers are built from the URL of the
                   9151: map, the resource number of the resource in the map, and the URL of
                   9152: the resource itself. The latter is somewhat redundant, but might help
                   9153: if maps change.
                   9154: 
                   9155: An example is
                   9156: 
                   9157:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   9158: 
                   9159: The respective map entry is
                   9160: 
                   9161:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   9162:   title="Problem 2">
                   9163:  </resource>
                   9164: 
                   9165: Symbs are used by the random number generator, as well as to store and
                   9166: restore data specific to a certain instance of for example a problem.
                   9167: 
                   9168: =head2 Storing And Retrieving Data
                   9169: 
                   9170: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   9171: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   9172: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   9173: is is the non-critical message twin of cstore. These functions are for
                   9174: handlers to store a perl hash to a user's permanent data space in an
                   9175: easy manner, and to retrieve it again on another call. It is expected
                   9176: that a handler would use this once at the beginning to retrieve data,
                   9177: and then again once at the end to send only the new data back.
                   9178: 
                   9179: The data is stored in the user's data directory on the user's
                   9180: homeserver under the ID of the course.
                   9181: 
                   9182: The hash that is returned by restore will have all of the previous
                   9183: value for all of the elements of the hash.
                   9184: 
                   9185: Example:
                   9186: 
                   9187:  #creating a hash
                   9188:  my %hash;
                   9189:  $hash{'foo'}='bar';
                   9190: 
                   9191:  #storing it
                   9192:  &Apache::lonnet::cstore(\%hash);
                   9193: 
                   9194:  #changing a value
                   9195:  $hash{'foo'}='notbar';
                   9196: 
                   9197:  #adding a new value
                   9198:  $hash{'bar'}='foo';
                   9199:  &Apache::lonnet::cstore(\%hash);
                   9200: 
                   9201:  #retrieving the hash
                   9202:  my %history=&Apache::lonnet::restore();
                   9203: 
                   9204:  #print the hash
                   9205:  foreach my $key (sort(keys(%history))) {
                   9206:    print("\%history{$key} = $history{$key}");
                   9207:  }
                   9208: 
                   9209: Will print out:
1.191     harris41 9210: 
1.394     bowersj2 9211:  %history{1:foo} = bar
                   9212:  %history{1:keys} = foo:timestamp
                   9213:  %history{1:timestamp} = 990455579
                   9214:  %history{2:bar} = foo
                   9215:  %history{2:foo} = notbar
                   9216:  %history{2:keys} = foo:bar:timestamp
                   9217:  %history{2:timestamp} = 990455580
                   9218:  %history{bar} = foo
                   9219:  %history{foo} = notbar
                   9220:  %history{timestamp} = 990455580
                   9221:  %history{version} = 2
                   9222: 
                   9223: Note that the special hash entries C<keys>, C<version> and
                   9224: C<timestamp> were added to the hash. C<version> will be equal to the
                   9225: total number of versions of the data that have been stored. The
                   9226: C<timestamp> attribute will be the UNIX time the hash was
                   9227: stored. C<keys> is available in every historical section to list which
                   9228: keys were added or changed at a specific historical revision of a
                   9229: hash.
                   9230: 
                   9231: B<Warning>: do not store the hash that restore returns directly. This
                   9232: will cause a mess since it will restore the historical keys as if the
                   9233: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 9234: 
1.394     bowersj2 9235: Calling convention:
1.191     harris41 9236: 
1.394     bowersj2 9237:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   9238:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 9239: 
1.394     bowersj2 9240: For more detailed information, see lonnet specific documentation.
1.191     harris41 9241: 
1.394     bowersj2 9242: =head1 RETURN MESSAGES
1.191     harris41 9243: 
1.394     bowersj2 9244: =over 4
1.191     harris41 9245: 
1.394     bowersj2 9246: =item * B<con_lost>: unable to contact remote host
1.191     harris41 9247: 
1.394     bowersj2 9248: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   9249: when the connection is brought back up
1.191     harris41 9250: 
1.394     bowersj2 9251: =item * B<con_failed>: unable to contact remote host and unable to save message
                   9252: for later delivery
1.191     harris41 9253: 
1.967     bisitz   9254: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 9255: 
1.394     bowersj2 9256: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 9257: that was requested
1.191     harris41 9258: 
1.243     albertel 9259: =back
1.191     harris41 9260: 
1.243     albertel 9261: =head1 PUBLIC SUBROUTINES
1.191     harris41 9262: 
1.243     albertel 9263: =head2 Session Environment Functions
1.191     harris41 9264: 
1.243     albertel 9265: =over 4
1.191     harris41 9266: 
1.394     bowersj2 9267: =item * 
                   9268: X<appenv()>
1.949     raeburn  9269: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 9270: the user envirnoment file, and will be restored for each access this
1.620     albertel 9271: user makes during this session, also modifies the %env for the current
1.949     raeburn  9272: process. Optional rolesarrayref - if defined contains a reference to an array
                   9273: of roles which are exempt from the restriction on modifying user.role entries 
                   9274: in the user's environment.db and in %env.    
1.191     harris41 9275: 
                   9276: =item *
1.394     bowersj2 9277: X<delenv()>
1.976.2.7  raeburn  9278: B<delenv($delthis,$regexp)>: removes all items from the session
                   9279: environment file that begin with $delthis. If the
                   9280: optional second arg - $regexp - is true, $delthis is treated as a
                   9281: regular expression, otherwise \Q$delthis\E is used.
                   9282: The values are also deleted from the current processes %env.
1.191     harris41 9283: 
1.795     albertel 9284: =item * get_env_multiple($name) 
                   9285: 
                   9286: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   9287: values may be defined and end up as an array ref.
                   9288: 
                   9289: returns an array of values
                   9290: 
1.243     albertel 9291: =back
                   9292: 
                   9293: =head2 User Information
1.191     harris41 9294: 
1.243     albertel 9295: =over 4
1.191     harris41 9296: 
                   9297: =item *
1.394     bowersj2 9298: X<queryauthenticate()>
                   9299: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 9300: authentication scheme
                   9301: 
                   9302: =item *
1.394     bowersj2 9303: X<authenticate()>
                   9304: B<authenticate($uname,$upass,$udom)>: try to
                   9305: authenticate user from domain's lib servers (first use the current
                   9306: one). C<$upass> should be the users password.
1.191     harris41 9307: 
                   9308: =item *
1.394     bowersj2 9309: X<homeserver()>
                   9310: B<homeserver($uname,$udom)>: find the server which has
                   9311: the user's directory and files (there must be only one), this caches
                   9312: the answer, and also caches if there is a borken connection.
1.191     harris41 9313: 
                   9314: =item *
1.394     bowersj2 9315: X<idget()>
                   9316: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   9317: (IDs are a unique resource in a domain, there must be only 1 ID per
                   9318: username, and only 1 username per ID in a specific domain) (returns
                   9319: hash: id=>name,id=>name)
1.191     harris41 9320: 
                   9321: =item *
1.394     bowersj2 9322: X<idrget()>
                   9323: B<idrget($udom,@unames)>: find the IDs behind a list of
                   9324: usernames (returns hash: name=>id,name=>id)
1.191     harris41 9325: 
                   9326: =item *
1.394     bowersj2 9327: X<idput()>
                   9328: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 9329: 
                   9330: =item *
1.394     bowersj2 9331: X<rolesinit()>
                   9332: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 9333: 
                   9334: =item *
1.551     albertel 9335: X<getsection()>
                   9336: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 9337: course $cname, return section name/number or '' for "not in course"
                   9338: and '-1' for "no section"
                   9339: 
                   9340: =item *
1.394     bowersj2 9341: X<userenvironment()>
                   9342: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 9343: passed in @what from the requested user's environment, returns a hash
                   9344: 
1.858     raeburn  9345: =item * 
                   9346: X<userlog_query()>
1.859     albertel 9347: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   9348: activity.log file. %filters defines filters applied when parsing the
                   9349: log file. These can be start or end timestamps, or the type of action
                   9350: - log to look for Login or Logout events, check for Checkin or
                   9351: Checkout, role for role selection. The response is in the form
                   9352: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   9353: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  9354: 
1.243     albertel 9355: =back
                   9356: 
                   9357: =head2 User Roles
                   9358: 
                   9359: =over 4
                   9360: 
                   9361: =item *
                   9362: 
1.810     raeburn  9363: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 9364:  F: full access
                   9365:  U,I,K: authentication modes (cxx only)
                   9366:  '': forbidden
                   9367:  1: user needs to choose course
                   9368:  2: browse allowed
1.766     albertel 9369:  A: passphrase authentication needed
1.243     albertel 9370: 
                   9371: =item *
                   9372: 
                   9373: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   9374: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   9375: and course level
                   9376: 
                   9377: =item *
                   9378: 
                   9379: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   9380: explanation of a user role term
                   9381: 
1.832     raeburn  9382: =item *
                   9383: 
1.935     raeburn  9384: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  9385: All arguments are optional. Returns a hash of a roles, either for
                   9386: co-author/assistant author roles for a user's Construction Space
1.906     albertel 9387: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  9388: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   9389: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   9390: For each key, value is set to colon-separated start and end times for
                   9391: the role.  If no username and domain are specified, will default to
1.934     raeburn  9392: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  9393: of role statuses (active, future or previous), roles 
                   9394: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   9395: to restrict the list of roles reported. If no array ref is 
                   9396: provided for types, will default to return only active roles.
1.834     albertel 9397: 
1.243     albertel 9398: =back
                   9399: 
                   9400: =head2 User Modification
                   9401: 
                   9402: =over 4
                   9403: 
                   9404: =item *
                   9405: 
1.957     raeburn  9406: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 9407: user for the level given by URL.  Optional start and end dates (leave empty
                   9408: string or zero for "no date")
1.191     harris41 9409: 
                   9410: =item *
                   9411: 
1.243     albertel 9412: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   9413: change a users, password, possible return values are: ok,
                   9414: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   9415: refused
1.191     harris41 9416: 
                   9417: =item *
                   9418: 
1.243     albertel 9419: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 9420: 
                   9421: =item *
                   9422: 
1.963     raeburn  9423: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
                   9424:            $forceid,$desiredhome,$email,$inststatus) : 
1.243     albertel 9425: modify user
1.191     harris41 9426: 
                   9427: =item *
                   9428: 
1.286     matthew  9429: modifystudent
                   9430: 
1.957     raeburn  9431: modify a student's enrollment and identification information.
1.286     matthew  9432: The course id is resolved based on the current users environment.  
                   9433: This means the envoking user must be a course coordinator or otherwise
                   9434: associated with a course.
                   9435: 
1.297     matthew  9436: This call is essentially a wrapper for lonnet::modifyuser and
                   9437: lonnet::modify_student_enrollment
1.286     matthew  9438: 
                   9439: Inputs: 
                   9440: 
                   9441: =over 4
                   9442: 
1.957     raeburn  9443: =item B<$udom> Student's loncapa domain
1.286     matthew  9444: 
1.957     raeburn  9445: =item B<$uname> Student's loncapa login name
1.286     matthew  9446: 
1.964     bisitz   9447: =item B<$uid> Student/Employee ID
1.286     matthew  9448: 
1.957     raeburn  9449: =item B<$umode> Student's authentication mode
1.286     matthew  9450: 
1.957     raeburn  9451: =item B<$upass> Student's password
1.286     matthew  9452: 
1.957     raeburn  9453: =item B<$first> Student's first name
1.286     matthew  9454: 
1.957     raeburn  9455: =item B<$middle> Student's middle name
1.286     matthew  9456: 
1.957     raeburn  9457: =item B<$last> Student's last name
1.286     matthew  9458: 
1.957     raeburn  9459: =item B<$gene> Student's generation
1.286     matthew  9460: 
1.957     raeburn  9461: =item B<$usec> Student's section in course
1.286     matthew  9462: 
                   9463: =item B<$end> Unix time of the roles expiration
                   9464: 
                   9465: =item B<$start> Unix time of the roles start date
                   9466: 
                   9467: =item B<$forceid> If defined, allow $uid to be changed
                   9468: 
                   9469: =item B<$desiredhome> server to use as home server for student
                   9470: 
1.957     raeburn  9471: =item B<$email> Student's permanent e-mail address
                   9472: 
                   9473: =item B<$type> Type of enrollment (auto or manual)
                   9474: 
1.963     raeburn  9475: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   9476: 
                   9477: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  9478: 
1.963     raeburn  9479: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  9480: 
1.963     raeburn  9481: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  9482: 
1.963     raeburn  9483: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  9484: 
1.286     matthew  9485: =back
1.297     matthew  9486: 
                   9487: =item *
                   9488: 
                   9489: modify_student_enrollment
                   9490: 
                   9491: Change a students enrollment status in a class.  The environment variable
                   9492: 'role.request.course' must be defined for this function to proceed.
                   9493: 
                   9494: Inputs:
                   9495: 
                   9496: =over 4
                   9497: 
                   9498: =item $udom, students domain
                   9499: 
                   9500: =item $uname, students name
                   9501: 
                   9502: =item $uid, students user id
                   9503: 
                   9504: =item $first, students first name
                   9505: 
                   9506: =item $middle
                   9507: 
                   9508: =item $last
                   9509: 
                   9510: =item $gene
                   9511: 
                   9512: =item $usec
                   9513: 
                   9514: =item $end
                   9515: 
                   9516: =item $start
                   9517: 
1.957     raeburn  9518: =item $type
                   9519: 
                   9520: =item $locktype
                   9521: 
                   9522: =item $cid
                   9523: 
                   9524: =item $selfenroll
                   9525: 
                   9526: =item $context
                   9527: 
1.297     matthew  9528: =back
                   9529: 
1.191     harris41 9530: 
                   9531: =item *
                   9532: 
1.243     albertel 9533: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9534: custom role; give a custom role to a user for the level given by URL.  Specify
                   9535: name and domain of role author, and role name
1.191     harris41 9536: 
                   9537: =item *
                   9538: 
1.243     albertel 9539: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9540: 
                   9541: =item *
                   9542: 
1.243     albertel 9543: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9544: 
                   9545: =back
                   9546: 
                   9547: =head2 Course Infomation
                   9548: 
                   9549: =over 4
1.191     harris41 9550: 
                   9551: =item *
                   9552: 
1.631     albertel 9553: coursedescription($courseid) : returns a hash of information about the
                   9554: specified course id, including all environment settings for the
                   9555: course, the description of the course will be in the hash under the
                   9556: key 'description'
1.191     harris41 9557: 
                   9558: =item *
                   9559: 
1.624     albertel 9560: resdata($name,$domain,$type,@which) : request for current parameter
                   9561: setting for a specific $type, where $type is either 'course' or 'user',
                   9562: @what should be a list of parameters to ask about. This routine caches
                   9563: answers for 5 minutes.
1.243     albertel 9564: 
1.877     foxr     9565: =item *
                   9566: 
                   9567: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9568: data base, returning a hash that is keyed by the resource name and has
                   9569: values that are the resource value.  I believe that the timestamps and
                   9570: versions are also returned.
                   9571: 
                   9572: 
1.243     albertel 9573: =back
                   9574: 
                   9575: =head2 Course Modification
                   9576: 
                   9577: =over 4
1.191     harris41 9578: 
                   9579: =item *
                   9580: 
1.243     albertel 9581: writecoursepref($courseid,%prefs) : write preferences (environment
                   9582: database) for a course
1.191     harris41 9583: 
                   9584: =item *
                   9585: 
1.243     albertel 9586: createcourse($udom,$description,$url) : make/modify course
                   9587: 
                   9588: =back
                   9589: 
                   9590: =head2 Resource Subroutines
                   9591: 
                   9592: =over 4
1.191     harris41 9593: 
                   9594: =item *
                   9595: 
1.243     albertel 9596: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9597: 
                   9598: =item *
                   9599: 
1.243     albertel 9600: repcopy($filename) : subscribes to the requested file, and attempts to
                   9601: replicate from the owning library server, Might return
1.607     raeburn  9602: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9603: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9604: resource. Expects the local filesystem pathname
                   9605: (/home/httpd/html/res/....)
                   9606: 
                   9607: =back
                   9608: 
                   9609: =head2 Resource Information
                   9610: 
                   9611: =over 4
1.191     harris41 9612: 
                   9613: =item *
                   9614: 
1.243     albertel 9615: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9616: a vairety of different possible values, $varname should be a request
                   9617: string, and the other parameters can be used to specify who and what
                   9618: one is asking about.
                   9619: 
                   9620: Possible values for $varname are environment.lastname (or other item
                   9621: from the envirnment hash), user.name (or someother aspect about the
                   9622: user), resource.0.maxtries (or some other part and parameter of a
                   9623: resource)
1.204     albertel 9624: 
                   9625: =item *
                   9626: 
1.243     albertel 9627: directcondval($number) : get current value of a condition; reads from a state
                   9628: string
1.204     albertel 9629: 
                   9630: =item *
                   9631: 
1.243     albertel 9632: condval($condidx) : value of condition index based on state
1.204     albertel 9633: 
                   9634: =item *
                   9635: 
1.243     albertel 9636: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9637: resource's metadata, $what should be either a specific key, or either
                   9638: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9639: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9640: 
                   9641: this function automatically caches all requests
1.191     harris41 9642: 
                   9643: =item *
                   9644: 
1.243     albertel 9645: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9646: network of library servers; returns file handle of where SQL and regex results
                   9647: will be stored for query
1.191     harris41 9648: 
                   9649: =item *
                   9650: 
1.243     albertel 9651: symbread($filename) : return symbolic list entry (filename argument optional);
                   9652: returns the data handle
1.191     harris41 9653: 
                   9654: =item *
                   9655: 
1.243     albertel 9656: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9657: a possible symb for the URL in $thisfn, and if is an encryypted
                   9658: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9659: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9660: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9661: 
1.191     harris41 9662: 
                   9663: =item *
                   9664: 
1.243     albertel 9665: symbclean($symb) : removes versions numbers from a symb, returns the
                   9666: cleaned symb
1.191     harris41 9667: 
                   9668: =item *
                   9669: 
1.243     albertel 9670: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9671: course map, user must be in a course for it to work.
1.191     harris41 9672: 
                   9673: =item *
                   9674: 
1.243     albertel 9675: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9676: 
                   9677: =item *
                   9678: 
1.243     albertel 9679: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9680: a random seed, all arguments are optional, if they aren't sent it uses the
                   9681: environment to derive them. Note: if symb isn't sent and it can't get one
                   9682: from &symbread it will use the current time as its return value
1.191     harris41 9683: 
                   9684: =item *
                   9685: 
1.243     albertel 9686: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9687: unfakeable, receipt
1.191     harris41 9688: 
                   9689: =item *
                   9690: 
1.620     albertel 9691: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9692: 
                   9693: =item *
                   9694: 
1.243     albertel 9695: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9696: 
                   9697: =item *
                   9698: 
1.243     albertel 9699: 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
1.191     harris41 9700: 
                   9701: =item *
                   9702: 
1.243     albertel 9703: 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)
1.191     harris41 9704: 
                   9705: =item *
                   9706: 
1.243     albertel 9707: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9708: 
                   9709: =item *
                   9710: 
1.243     albertel 9711: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9712: forcing spreadsheet to reevaluate the resource scores next time.
                   9713: 
                   9714: =back
                   9715: 
                   9716: =head2 Storing/Retreiving Data
                   9717: 
                   9718: =over 4
1.191     harris41 9719: 
                   9720: =item *
                   9721: 
1.243     albertel 9722: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9723: for this url; hashref needs to be given and should be a \%hashname; the
                   9724: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9725: be derived from the env
1.191     harris41 9726: 
                   9727: =item *
                   9728: 
1.243     albertel 9729: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9730: uses critical subroutine
1.191     harris41 9731: 
                   9732: =item *
                   9733: 
1.243     albertel 9734: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9735: all args are optional
1.191     harris41 9736: 
                   9737: =item *
                   9738: 
1.717     albertel 9739: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9740: dumps the complete (or key matching regexp) namespace into a hash
                   9741: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9742: normally &store()ed into
                   9743: 
                   9744: $range should be either an integer '100' (give me the first 100
                   9745:                                            matching records)
                   9746:               or be  two integers sperated by a - with no spaces
                   9747:                  '30-50' (give me the 30th through the 50th matching
                   9748:                           records)
                   9749: 
                   9750: 
                   9751: =item *
                   9752: 
                   9753: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9754: replaces a &store() version of data with a replacement set of data
                   9755: for a particular resource in a namespace passed in the $storehash hash 
                   9756: reference
                   9757: 
                   9758: =item *
                   9759: 
1.243     albertel 9760: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9761: works very similar to store/cstore, but all data is stored in a
                   9762: temporary location and can be reset using tmpreset, $storehash should
                   9763: be a hash reference, returns nothing on success
1.191     harris41 9764: 
                   9765: =item *
                   9766: 
1.243     albertel 9767: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9768: similar to restore, but all data is stored in a temporary location and
                   9769: can be reset using tmpreset. Returns a hash of values on success,
                   9770: error string otherwise.
1.191     harris41 9771: 
                   9772: =item *
                   9773: 
1.243     albertel 9774: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9775: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9776: 
                   9777: =item *
                   9778: 
1.243     albertel 9779: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9780: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9781: 
                   9782: =item *
                   9783: 
1.243     albertel 9784: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9785: namesp ($udom and $uname are optional)
1.191     harris41 9786: 
                   9787: =item *
                   9788: 
1.702     albertel 9789: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9790: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9791: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9792: 
1.702     albertel 9793: $range should be either an integer '100' (give me the first 100
                   9794:                                            matching records)
                   9795:               or be  two integers sperated by a - with no spaces
                   9796:                  '30-50' (give me the 30th through the 50th matching
                   9797:                           records)
1.449     matthew  9798: =item *
                   9799: 
                   9800: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9801: $store can be a scalar, an array reference, or if the amount to be 
                   9802: incremented is > 1, a hash reference.
                   9803: 
                   9804: ($udom and $uname are optional)
1.191     harris41 9805: 
                   9806: =item *
                   9807: 
1.243     albertel 9808: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9809: ($udom and $uname are optional)
1.191     harris41 9810: 
                   9811: =item *
                   9812: 
1.243     albertel 9813: cput($namespace,$storehash,$udom,$uname) : critical put
                   9814: ($udom and $uname are optional)
1.191     harris41 9815: 
                   9816: =item *
                   9817: 
1.748     albertel 9818: newput($namespace,$storehash,$udom,$uname) :
                   9819: 
                   9820: Attempts to store the items in the $storehash, but only if they don't
                   9821: currently exist, if this succeeds you can be certain that you have 
                   9822: successfully created a new key value pair in the $namespace db.
                   9823: 
                   9824: 
                   9825: Args:
                   9826:  $namespace: name of database to store values to
                   9827:  $storehash: hashref to store to the db
                   9828:  $udom: (optional) domain of user containing the db
                   9829:  $uname: (optional) name of user caontaining the db
                   9830: 
                   9831: Returns:
                   9832:  'ok' -> succeeded in storing all keys of $storehash
                   9833:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9834:                         least <key> already existed in the db (other
                   9835:                         requested keys may also already exist)
1.967     bisitz   9836:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 9837:  'con_lost' -> unable to contact request server
                   9838:  'refused' -> action was not allowed by remote machine
                   9839: 
                   9840: 
                   9841: =item *
                   9842: 
1.243     albertel 9843: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9844: reference filled in from namesp (encrypts the return communication)
                   9845: ($udom and $uname are optional)
1.191     harris41 9846: 
                   9847: =item *
                   9848: 
1.243     albertel 9849: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9850: critical subroutine
                   9851: 
1.806     raeburn  9852: =item *
                   9853: 
1.860     raeburn  9854: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9855: array reference filled in from namespace found in domain level on either
                   9856: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9857: 
                   9858: =item *
                   9859: 
1.860     raeburn  9860: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9861: domain level either on specified domain server ($uhome) or primary domain 
                   9862: server ($udom and $uhome are optional)
1.806     raeburn  9863: 
1.943     raeburn  9864: =item * 
                   9865: 
                   9866: get_domain_defaults($target_domain) : returns hash with defaults for
                   9867: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   9868: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   9869: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   9870: Values are retrieved from cache (if current), or from domain's configuration.db
                   9871: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   9872: or lonTabs/domain.tab. 
                   9873: 
                   9874: %domdefaults = &get_auth_defaults($target_domain);
                   9875: 
1.243     albertel 9876: =back
                   9877: 
                   9878: =head2 Network Status Functions
                   9879: 
                   9880: =over 4
1.191     harris41 9881: 
                   9882: =item *
                   9883: 
                   9884: dirlist($uri) : return directory list based on URI
                   9885: 
                   9886: =item *
                   9887: 
1.243     albertel 9888: spareserver() : find server with least workload from spare.tab
                   9889: 
                   9890: =back
                   9891: 
                   9892: =head2 Apache Request
                   9893: 
                   9894: =over 4
1.191     harris41 9895: 
                   9896: =item *
                   9897: 
1.243     albertel 9898: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9899: localhost, posts hash
                   9900: 
                   9901: =back
                   9902: 
                   9903: =head2 Data to String to Data
                   9904: 
                   9905: =over 4
1.191     harris41 9906: 
                   9907: =item *
                   9908: 
1.243     albertel 9909: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9910: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9911: 
                   9912: =item *
                   9913: 
1.243     albertel 9914: hashref2str($hashref) : convert a hashref into a string complete with
                   9915: escaping and '=' and '&' separators, supports elements that are
                   9916: arrayrefs and hashrefs
1.191     harris41 9917: 
                   9918: =item *
                   9919: 
1.243     albertel 9920: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9921: with escaping and '&' separators, supports elements that are arrayrefs
                   9922: and hashrefs
1.191     harris41 9923: 
                   9924: =item *
                   9925: 
1.243     albertel 9926: str2hash($string) : convert string to hash using unescaping and
                   9927: splitting on '=' and '&', supports elements that are arrayrefs and
                   9928: hashrefs
1.191     harris41 9929: 
                   9930: =item *
                   9931: 
1.243     albertel 9932: str2array($string) : convert string to hash using unescaping and
                   9933: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9934: 
                   9935: =back
                   9936: 
                   9937: =head2 Logging Routines
                   9938: 
                   9939: =over 4
                   9940: 
                   9941: These routines allow one to make log messages in the lonnet.log and
                   9942: lonnet.perm logfiles.
1.191     harris41 9943: 
                   9944: =item *
                   9945: 
1.243     albertel 9946: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9947: 
                   9948: =item *
                   9949: 
1.243     albertel 9950: logthis() : append message to the normal lonnet.log file, it gets
                   9951: preiodically rolled over and deleted.
1.191     harris41 9952: 
                   9953: =item *
                   9954: 
1.243     albertel 9955: logperm() : append a permanent message to lonnet.perm.log, this log
                   9956: file never gets deleted by any automated portion of the system, only
                   9957: messages of critical importance should go in here.
                   9958: 
                   9959: =back
                   9960: 
                   9961: =head2 General File Helper Routines
                   9962: 
                   9963: =over 4
1.191     harris41 9964: 
                   9965: =item *
                   9966: 
1.481     raeburn  9967: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9968: (a) files in /uploaded
                   9969:   (i) If a local copy of the file exists - 
                   9970:       compares modification date of local copy with last-modified date for 
                   9971:       definitive version stored on home server for course. If local copy is 
                   9972:       stale, requests a new version from the home server and stores it. 
                   9973:       If the original has been removed from the home server, then local copy 
                   9974:       is unlinked.
                   9975:   (ii) If local copy does not exist -
                   9976:       requests the file from the home server and stores it. 
                   9977:   
                   9978:   If $caller is 'uploadrep':  
                   9979:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9980:     for request for files originally uploaded via DOCS. 
                   9981:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9982:   
                   9983:   Otherwise:
                   9984:      This indicates a call from the content generation phase of the request.
                   9985:      -  returns the entire contents of the file or -1.
                   9986:      
                   9987: (b) files in /res
                   9988:    - returns the entire contents of a file or -1; 
                   9989:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9990: 
1.712     albertel 9991: 
                   9992: =item *
                   9993: 
                   9994: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9995:                   reference
                   9996: 
                   9997: returns either a stat() list of data about the file or an empty list
                   9998: if the file doesn't exist or couldn't find out about it (connection
                   9999: problems or user unknown)
                   10000: 
1.191     harris41 10001: =item *
                   10002: 
1.243     albertel 10003: filelocation($dir,$file) : returns file system location of a file
                   10004: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   10005: directory that relative $file lookups are to looked in ($dir of /a/dir
                   10006: and a file of ../bob will become /a/bob)
1.191     harris41 10007: 
                   10008: =item *
                   10009: 
                   10010: hreflocation($dir,$file) : returns file system location or a URL; same as
                   10011: filelocation except for hrefs
                   10012: 
                   10013: =item *
                   10014: 
                   10015: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   10016: 
1.243     albertel 10017: =back
                   10018: 
1.608     albertel 10019: =head2 Usererfile file routines (/uploaded*)
                   10020: 
                   10021: =over 4
                   10022: 
                   10023: =item *
                   10024: 
                   10025: userfileupload(): main rotine for putting a file in a user or course's
                   10026:                   filespace, arguments are,
                   10027: 
1.620     albertel 10028:  formname - required - this is the name of the element in $env where the
1.608     albertel 10029:            filename, and the contents of the file to create/modifed exist
1.620     albertel 10030:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   10031:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 10032:  coursedoc - if true, store the file in the course of the active role
                   10033:              of the current user
                   10034:  subdir - required - subdirectory to put the file in under ../userfiles/
                   10035:          if undefined, it will be placed in "unknown"
                   10036: 
                   10037:  (This routine calls clean_filename() to remove any dangerous
                   10038:  characters from the filename, and then calls finuserfileupload() to
                   10039:  complete the transaction)
                   10040: 
                   10041:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10042:  and /adm/notfound.html if unsuccessful
                   10043: 
                   10044: =item *
                   10045: 
                   10046: clean_filename(): routine for cleaing a filename up for storage in
                   10047:                  userfile space, argument is:
                   10048: 
                   10049:  filename - proposed filename
                   10050: 
                   10051: returns: the new clean filename
                   10052: 
                   10053: =item *
                   10054: 
                   10055: finishuserfileupload(): routine that creaes and sends the file to
                   10056: userspace, probably shouldn't be called directly
                   10057: 
                   10058:   docuname: username or courseid of destination for the file
                   10059:   docudom: domain of user/course of destination for the file
                   10060:   formname: same as for userfileupload()
                   10061:   fname: filename (inculding subdirectories) for the file
                   10062: 
                   10063:  returns either the url of the uploaded file (/uploaded/....) if successful
                   10064:  and /adm/notfound.html if unsuccessful
                   10065: 
                   10066: =item *
                   10067: 
                   10068: renameuserfile(): renames an existing userfile to a new name
                   10069: 
                   10070:   Args:
                   10071:    docuname: username or courseid of destination for the file
                   10072:    docudom: domain of user/course of destination for the file
                   10073:    old: current file name (including any subdirs under userfiles)
                   10074:    new: desired file name (including any subdirs under userfiles)
                   10075: 
                   10076: =item *
                   10077: 
                   10078: mkdiruserfile(): creates a directory is a userfiles dir
                   10079: 
                   10080:   Args:
                   10081:    docuname: username or courseid of destination for the file
                   10082:    docudom: domain of user/course of destination for the file
                   10083:    dir: dir to create (including any subdirs under userfiles)
                   10084: 
                   10085: =item *
                   10086: 
                   10087: removeuserfile(): removes a file that exists in userfiles
                   10088: 
                   10089:   Args:
                   10090:    docuname: username or courseid of destination for the file
                   10091:    docudom: domain of user/course of destination for the file
                   10092:    fname: filname to delete (including any subdirs under userfiles)
                   10093: 
                   10094: =item *
                   10095: 
                   10096: removeuploadedurl(): convience function for removeuserfile()
                   10097: 
                   10098:   Args:
                   10099:    url:  a full /uploaded/... url to delete
                   10100: 
1.747     albertel 10101: =item * 
                   10102: 
                   10103: get_portfile_permissions():
                   10104:   Args:
                   10105:     domain: domain of user or course contain the portfolio files
                   10106:     user: name of user or num of course contain the portfolio files
                   10107:   Returns:
                   10108:     hashref of a dump of the proper file_permissions.db
                   10109:    
                   10110: 
                   10111: =item * 
                   10112: 
                   10113: get_access_controls():
                   10114: 
                   10115: Args:
                   10116:   current_permissions: the hash ref returned from get_portfile_permissions()
                   10117:   group: (optional) the group you want the files associated with
                   10118:   file: (optional) the file you want access info on
                   10119: 
                   10120: Returns:
1.749     raeburn  10121:     a hash (keys are file names) of hashes containing
                   10122:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   10123:         values are XML containing access control settings (see below) 
1.747     albertel 10124: 
                   10125: Internal notes:
                   10126: 
1.749     raeburn  10127:  access controls are stored in file_permissions.db as key=value pairs.
                   10128:     key -> path to file/file_name\0uniqueID:scope_end_start
                   10129:         where scope -> public,guest,course,group,domains or users.
                   10130:               end -> UNIX time for end of access (0 -> no end date)
                   10131:               start -> UNIX time for start of access
                   10132: 
                   10133:     value -> XML description of access control
                   10134:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   10135:             <start></start>
                   10136:             <end></end>
                   10137: 
                   10138:             <password></password>  for scope type = guest
                   10139: 
                   10140:             <domain></domain>     for scope type = course or group
                   10141:             <number></number>
                   10142:             <roles id="">
                   10143:              <role></role>
                   10144:              <access></access>
                   10145:              <section></section>
                   10146:              <group></group>
                   10147:             </roles>
                   10148: 
                   10149:             <dom></dom>         for scope type = domains
                   10150: 
                   10151:             <users>             for scope type = users
                   10152:              <user>
                   10153:               <uname></uname>
                   10154:               <udom></udom>
                   10155:              </user>
                   10156:             </users>
                   10157:            </scope> 
                   10158:               
                   10159:  Access data is also aggregated for each file in an additional key=value pair:
                   10160:  key -> path to file/file_name\0accesscontrol 
                   10161:  value -> reference to hash
                   10162:           hash contains key = value pairs
                   10163:           where key = uniqueID:scope_end_start
                   10164:                 value = UNIX time record was last updated
                   10165: 
                   10166:           Used to improve speed of look-ups of access controls for each file.  
                   10167:  
                   10168:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   10169: 
                   10170: modify_access_controls():
                   10171: 
                   10172: Modifies access controls for a portfolio file
                   10173: Args
                   10174: 1. file name
                   10175: 2. reference to hash of required changes,
                   10176: 3. domain
                   10177: 4. username
                   10178:   where domain,username are the domain of the portfolio owner 
                   10179:   (either a user or a course) 
                   10180: 
                   10181: Returns:
                   10182: 1. result of additions or updates ('ok' or 'error', with error message). 
                   10183: 2. result of deletions ('ok' or 'error', with error message).
                   10184: 3. reference to hash of any new or updated access controls.
                   10185: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   10186:    key = integer (inbound ID)
                   10187:    value = uniqueID  
1.747     albertel 10188: 
1.608     albertel 10189: =back
                   10190: 
1.243     albertel 10191: =head2 HTTP Helper Routines
                   10192: 
                   10193: =over 4
                   10194: 
1.191     harris41 10195: =item *
                   10196: 
                   10197: escape() : unpack non-word characters into CGI-compatible hex codes
                   10198: 
                   10199: =item *
                   10200: 
                   10201: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   10202: 
1.243     albertel 10203: =back
                   10204: 
                   10205: =head1 PRIVATE SUBROUTINES
                   10206: 
                   10207: =head2 Underlying communication routines (Shouldn't call)
                   10208: 
                   10209: =over 4
                   10210: 
                   10211: =item *
                   10212: 
                   10213: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   10214: 
                   10215: =item *
                   10216: 
                   10217: reply() : uses subreply to send a message to remote machine, logs all failures
                   10218: 
                   10219: =item *
                   10220: 
                   10221: critical() : passes a critical message to another server; if cannot
                   10222: get through then place message in connection buffer directory and
                   10223: returns con_delayed, if incapable of saving message, returns
                   10224: con_failed
                   10225: 
                   10226: =item *
                   10227: 
                   10228: reconlonc() : tries to reconnect lonc client processes.
                   10229: 
                   10230: =back
                   10231: 
                   10232: =head2 Resource Access Logging
                   10233: 
                   10234: =over 4
                   10235: 
                   10236: =item *
                   10237: 
                   10238: flushcourselogs() : flush (save) buffer logs and access logs
                   10239: 
                   10240: =item *
                   10241: 
                   10242: courselog($what) : save message for course in hash
                   10243: 
                   10244: =item *
                   10245: 
                   10246: courseacclog($what) : save message for course using &courselog().  Perform
                   10247: special processing for specific resource types (problems, exams, quizzes, etc).
                   10248: 
1.191     harris41 10249: =item *
                   10250: 
                   10251: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   10252: as a PerlChildExitHandler
1.243     albertel 10253: 
                   10254: =back
                   10255: 
                   10256: =head2 Other
                   10257: 
                   10258: =over 4
                   10259: 
                   10260: =item *
                   10261: 
                   10262: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 10263: 
                   10264: =back
                   10265: 
                   10266: =cut
1.877     foxr     10267: 

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